~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
1712 lines · 99.2 KB Raw History
const std = @import("std");
const clock = @import("../core/clock.zig");
const auth = @import("../auth/tokens.zig");
const browser_session = @import("../internal/browser_session.zig");
const client_icon = @import("oauth/client_icon.zig");
const page = @import("oauth/page.zig");
const scope_display = @import("oauth/scope_display.zig");
const config = @import("../core/config.zig");
const dpop = @import("../internal/dpop.zig");
const document_cache = @import("../internal/document_cache.zig");
const outbound = @import("../internal/outbound.zig");
const log = @import("../core/log.zig");
const http_api = @import("../http/api.zig");
const permission_sets = @import("oauth/permission_sets.zig");
const scope_rules = @import("../internal/scopes.zig");
const store = @import("../storage/store.zig");
const zat = @import("zat");

const http = std.http;
const request_uri_prefix = "urn:ietf:params:oauth:request_uri:";
const par_expires_in: i64 = 600;
const access_token_expires_in: i64 = 15 * 60;
const previous_refresh_grace_in: i64 = 30;

// Session lifetimes follow @atproto/oauth-provider (oauth-constants.ts and
// Client.refreshLifetime/sessionLifetime in client/client.ts): a public client
// gets REFRESH_LIFETIME and SESSION_LIFETIME, two weeks each; a confidential
// client gets REFRESH_LIFETIME_EXTENDED (three months of inactivity) and
// SESSION_LIFETIME_EXTENDED (two years absolute), with its YEAR of 365.25 days.
const day_seconds: i64 = 24 * 60 * 60;
const public_refresh_idle: i64 = 14 * day_seconds;
const public_session_lifetime: i64 = 14 * day_seconds;
const confidential_refresh_idle: i64 = 7_889_400;
const confidential_session_lifetime: i64 = 63_115_200;
const client_document_ttl_seconds: i64 = 10 * 60;

var client_document_cache = document_cache.DocumentCache(64).init(std.heap.page_allocator);

const ClientDisplayInfo = struct {
    name: []const u8,
    uri: []const u8,
};

const ClientMetadata = struct {
    value: std.json.Value,

    fn redirectUriRegistered(self: ClientMetadata, redirect_uri: []const u8) bool {
        const redirect_uris = switch (self.value) {
            .object => |object| switch (object.get("redirect_uris") orelse return false) {
                .array => |array| array,
                else => return false,
            },
            else => return false,
        };
        const native = std.mem.eql(u8, zat.json.getString(self.value, "application_type") orelse "web", "native");
        for (redirect_uris.items) |item| {
            if (item != .string) continue;
            if (std.mem.eql(u8, item.string, redirect_uri)) return true;
            if (native and loopbackRedirectMatchesAnyPort(item.string, redirect_uri)) return true;
        }
        return false;
    }

    fn registeredScope(self: ClientMetadata) ?[]const u8 {
        return zat.json.getString(self.value, "scope");
    }
};

pub fn protectedResource(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    var resource_buf: [512]u8 = undefined;
    const requested_resource = http_api.queryParam(request.url.raw, "resource", &resource_buf);
    const resource = if (requested_resource) |requested|
        if (std.mem.eql(u8, trimTrailingSlash(requested), config.publicUrl())) requested else config.publicUrl()
    else
        config.publicUrl();
    const body = try std.fmt.allocPrint(arena.allocator(),
        \\{{"resource":{f},"authorization_servers":[{f}],"scopes_supported":["atproto","transition:generic","transition:email","transition:chat.bsky"],"bearer_methods_supported":["header"],"resource_documentation":"https://atproto.com"}}
    , .{ std.json.fmt(resource, .{}), std.json.fmt(config.publicUrl(), .{}) });
    try http_api.json(request, .ok, body);
}

pub fn authorizationServer(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const issuer = config.publicUrl();
    const body = try std.fmt.allocPrint(allocator,
        \\{{"issuer":{f},"request_parameter_supported":true,"request_uri_parameter_supported":true,"require_request_uri_registration":true,"scopes_supported":["atproto","transition:generic","transition:email","transition:chat.bsky"],"subject_types_supported":["public"],"response_types_supported":["code"],"response_modes_supported":["query","fragment"],"grant_types_supported":["authorization_code","refresh_token"],"code_challenge_methods_supported":["S256"],"authorization_response_iss_parameter_supported":true,"client_id_metadata_document_supported":true,"require_pushed_authorization_requests":true,"token_endpoint_auth_methods_supported":["none","private_key_jwt"],"token_endpoint_auth_signing_alg_values_supported":["ES256","ES256K"],"dpop_signing_alg_values_supported":["ES256","ES256K"],"prompt_values_supported":["none","login","consent","select_account","create"],"protected_resources":[{f}],"jwks_uri":{f},"authorization_endpoint":{f},"token_endpoint":{f},"revocation_endpoint":{f},"introspection_endpoint":{f},"pushed_authorization_request_endpoint":{f}}}
    , .{
        std.json.fmt(issuer, .{}),
        std.json.fmt(issuer, .{}),
        std.json.fmt(try joinUrl(allocator, issuer, "/oauth/jwks"), .{}),
        std.json.fmt(try joinUrl(allocator, issuer, "/oauth/authorize"), .{}),
        std.json.fmt(try joinUrl(allocator, issuer, "/oauth/token"), .{}),
        std.json.fmt(try joinUrl(allocator, issuer, "/oauth/revoke"), .{}),
        std.json.fmt(try joinUrl(allocator, issuer, "/oauth/introspect"), .{}),
        std.json.fmt(try joinUrl(allocator, issuer, "/oauth/par"), .{}),
    });
    try http_api.json(request, .ok, body);
}

pub fn jwks(request: *http_api.Request) !void {
    try http_api.json(request, .ok, "{\"keys\":[]}");
}

pub fn par(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const content_type = http_api.headerValue(request, "content-type") orelse "";
    const body = try http_api.readBodyAlloc(request, allocator, 64 * 1024);
    if (isJsonContent(content_type)) {
        const parsed = try std.json.parseFromSlice(std.json.Value, allocator, body, .{});
        return parWithParamsHandled(request, allocator, JsonParams{ .json = parsed.value });
    }
    return parWithParamsHandled(request, allocator, Form{ .body = body });
}

fn parWithParamsHandled(request: *http_api.Request, allocator: std.mem.Allocator, params: anytype) !void {
    parWithParams(request, allocator, params) catch |err| switch (err) {
        error.MissingFormField => return,
        else => return err,
    };
}

const LoopbackRedirect = struct {
    host: []const u8,
    port: ?[]const u8,
    rest: []const u8,
};

/// `http://127.0.0.1[:port]<rest>` or `http://[::1][:port]<rest>`; `localhost` is
/// not a loopback redirect (RFC 8252 §8.3) and https never is (§7.3)
fn parseLoopbackRedirect(uri: []const u8) ?LoopbackRedirect {
    const scheme = "http://";
    if (!std.mem.startsWith(u8, uri, scheme)) return null;
    const after = uri[scheme.len..];
    const host: []const u8 = if (std.mem.startsWith(u8, after, "127.0.0.1"))
        "127.0.0.1"
    else if (std.mem.startsWith(u8, after, "[::1]"))
        "[::1]"
    else
        return null;
    var rest = after[host.len..];
    var port: ?[]const u8 = null;
    if (rest.len > 0 and rest[0] == ':') {
        const end = std.mem.indexOfAny(u8, rest, "/?#") orelse rest.len;
        const digits = rest[1..end];
        if (digits.len == 0) return null;
        for (digits) |c| if (!std.ascii.isDigit(c)) return null;
        port = digits;
        rest = rest[end..];
    }
    if (rest.len > 0 and rest[0] != '/' and rest[0] != '?' and rest[0] != '#') return null;
    return .{ .host = host, .port = port, .rest = rest };
}

/// RFC 8252 §7.3: a native client that registers a loopback redirect without a
/// port matches that URI on whatever port it bound at request time. A registered
/// port still has to match exactly, as in the reference provider.
fn loopbackRedirectMatchesAnyPort(registered: []const u8, requested: []const u8) bool {
    const allowed = parseLoopbackRedirect(registered) orelse return false;
    if (allowed.port != null) return false;
    const request = parseLoopbackRedirect(requested) orelse return false;
    return std.mem.eql(u8, allowed.host, request.host) and std.mem.eql(u8, allowed.rest, request.rest);
}

const loopback_client_origin = "http://localhost";

const LoopbackClient = struct {
    scope: []const u8,
    redirect_uris: []const []const u8,
};

/// The spec's localhost client development exception: a client_id whose origin
/// is exactly `http://localhost` (no port) with an empty path is virtual, and
/// its metadata comes from the query string instead of a fetch.
fn isLoopbackClientId(client_id: []const u8) bool {
    if (!std.mem.startsWith(u8, client_id, loopback_client_origin)) return false;
    var rest = client_id[loopback_client_origin.len..];
    if (rest.len > 0 and rest[0] == '/') rest = rest[1..];
    return rest.len == 0 or rest[0] == '?';
}

/// Mirrors `parseOAuthLoopbackClientId` in the reference `@atproto/oauth-types`:
/// only `scope` (once) and `redirect_uri` (repeatable) are allowed, every
/// redirect must be a loopback IP redirect, and the scope must include `atproto`.
fn parseLoopbackClientId(allocator: std.mem.Allocator, client_id: []const u8) !LoopbackClient {
    if (std.mem.indexOfScalar(u8, client_id, '#') != null) return error.InvalidLoopbackClientId;
    var scope: ?[]const u8 = null;
    var redirect_uris: std.ArrayList([]const u8) = .empty;
    if (std.mem.indexOfScalar(u8, client_id, '?')) |query_start| {
        var params = std.mem.splitScalar(u8, client_id[query_start + 1 ..], '&');
        while (params.next()) |param| {
            if (param.len == 0) continue;
            const eq = std.mem.indexOfScalar(u8, param, '=') orelse param.len;
            const raw_value = if (eq < param.len) param[eq + 1 ..] else "";
            const value = http_api.percentDecode(raw_value, try allocator.alloc(u8, raw_value.len)) catch return error.InvalidLoopbackClientId;
            if (std.mem.eql(u8, param[0..eq], "scope")) {
                if (scope != null or !scopeListContains(value, "atproto")) return error.InvalidLoopbackClientId;
                scope = value;
            } else if (std.mem.eql(u8, param[0..eq], "redirect_uri")) {
                if (parseLoopbackRedirect(value) == null) return error.InvalidLoopbackClientId;
                try redirect_uris.append(allocator, value);
            } else return error.InvalidLoopbackClientId;
        }
    }
    if (redirect_uris.items.len == 0) try redirect_uris.appendSlice(allocator, &.{ "http://127.0.0.1/", "http://[::1]/" });
    return .{ .scope = scope orelse "atproto", .redirect_uris = redirect_uris.items };
}

fn scopeListContains(scope_text: []const u8, wanted: []const u8) bool {
    var scopes = std.mem.splitScalar(u8, scope_text, ' ');
    while (scopes.next()) |scope| if (std.mem.eql(u8, scope, wanted)) return true;
    return false;
}

fn loopbackClientMetadata(allocator: std.mem.Allocator, client_id: []const u8) !std.json.Parsed(std.json.Value) {
    const client = try parseLoopbackClientId(allocator, client_id);
    const Document = struct {
        client_id: []const u8,
        client_name: []const u8,
        scope: []const u8,
        redirect_uris: []const []const u8,
        response_types: []const []const u8,
        grant_types: []const []const u8,
        token_endpoint_auth_method: []const u8,
        application_type: []const u8,
        dpop_bound_access_tokens: bool,
    };
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try std.json.Stringify.value(Document{
        .client_id = client_id,
        .client_name = "development client",
        .scope = client.scope,
        .redirect_uris = client.redirect_uris,
        .response_types = &.{"code"},
        .grant_types = &.{ "authorization_code", "refresh_token" },
        .token_endpoint_auth_method = "none",
        .application_type = "native",
        .dpop_bound_access_tokens = true,
    }, .{}, &out.writer);
    return std.json.parseFromSlice(std.json.Value, allocator, out.written(), .{ .allocate = .alloc_always });
}

fn clientMetadata(allocator: std.mem.Allocator, client_id: []const u8) !std.json.Parsed(std.json.Value) {
    if (isLoopbackClientId(client_id)) return loopbackClientMetadata(allocator, client_id);
    return fetchJson(allocator, client_id, 256 * 1024);
}

fn clientMetadataErrorDescription(err: anyerror) []const u8 {
    return switch (err) {
        error.InvalidLoopbackClientId => "Invalid loopback client_id",
        else => "Could not fetch client metadata",
    };
}

fn parWithParams(request: *http_api.Request, allocator: std.mem.Allocator, params: anytype) !void {
    const response_type = try requireParam(request, params, allocator, "response_type");
    if (!std.mem.eql(u8, response_type, "code")) return oauthError(request, .bad_request, "unsupported_response_type", "Only response_type=code is supported");
    const client_id = try requireParam(request, params, allocator, "client_id");
    const client_metadata_doc = clientMetadata(allocator, client_id) catch |err| {
        log.err("oauth par rejected metadata_fetch_failed client={s} err={s}\n", .{ client_id, @errorName(err) });
        return oauthError(request, .bad_request, "invalid_client", clientMetadataErrorDescription(err));
    };
    const client_metadata = ClientMetadata{ .value = client_metadata_doc.value };
    if ((zat.json.getBool(client_metadata.value, "dpop_bound_access_tokens") orelse false) != true) {
        return oauthError(request, .bad_request, "invalid_client", "dpop_bound_access_tokens must be true");
    }
    try requireClientAuth(request, allocator, params, client_id, client_metadata.value);
    const redirect_uri = try requireParam(request, params, allocator, "redirect_uri");
    if (!client_metadata.redirectUriRegistered(redirect_uri)) {
        return oauthError(request, .bad_request, "invalid_request", "redirect_uri not registered for client");
    }
    const code_challenge = try requireParam(request, params, allocator, "code_challenge");
    const code_challenge_method = try requireParam(request, params, allocator, "code_challenge_method");
    if (!std.mem.eql(u8, code_challenge_method, "S256")) return oauthError(request, .bad_request, "invalid_request", "Only S256 PKCE is supported");
    const scope = try params.value(allocator, "scope") orelse "atproto";
    try validateScope(request, allocator, scope, client_metadata.registeredScope());
    const state = try params.value(allocator, "state") orelse "";
    const response_mode = try params.value(allocator, "response_mode") orelse "query";
    if (!validResponseMode(response_mode)) return oauthError(request, .bad_request, "invalid_request", "Invalid response_mode");
    const login_hint = try params.value(allocator, "login_hint");
    const dpop_jkt_param = try params.value(allocator, "dpop_jkt");
    const proof = dpop.verifyRequest(allocator, request, null, dpop_jkt_param) catch |err| {
        return handleAuthorizationDpopError(request, allocator, err);
    };
    const dpop_jkt = dpop_jkt_param orelse proof.jkt;
    if (try params.value(allocator, "prompt")) |prompt| {
        if (!validPrompt(prompt)) return oauthError(request, .bad_request, "invalid_request", "Invalid prompt");
    }

    const request_id = try store.randomToken(allocator, "", 16);
    const expires_at = now() + par_expires_in;
    try store.putOAuthRequest(request_id, client_id, redirect_uri, scope, state, code_challenge, code_challenge_method, response_mode, login_hint, dpop_jkt, expires_at);
    try store.setOAuthPrompt(request_id, try params.value(allocator, "prompt"));
    const request_uri = try std.fmt.allocPrint(allocator, "{s}{s}", .{ request_uri_prefix, request_id });
    const response = try std.fmt.allocPrint(allocator, "{{\"expires_in\":{d},\"request_uri\":{f}}}", .{ par_expires_in, std.json.fmt(request_uri, .{}) });
    try dpop.attachNonce(allocator);
    try http_api.json(request, .created, response);
}

pub fn authorizeGet(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const wants_json = acceptsJson(request);
    var request_id_buf: [512]u8 = undefined;
    const request_id = requestIdFromTarget(request.url.raw, &request_id_buf) orelse return requestFailure(request, allocator, wants_json, .missing);
    const oauth_request = (try store.getOAuthRequest(allocator, request_id)) orelse return requestFailure(request, allocator, wants_json, .unknown);
    if (oauth_request.expires_at < now()) return requestFailure(request, allocator, wants_json, .expired);
    if (wants_json) {
        const client = clientDisplayInfo(allocator, oauth_request.client_id) catch ClientDisplayInfo{ .name = oauth_request.client_id, .uri = oauth_request.client_id };
        const body = try authRequestInfoJson(allocator, oauth_request, client);
        return http_api.json(request, .ok, body);
    }
    var step_buf: [16]u8 = undefined;
    const step = Step.parse(http_api.queryParam(request.url.raw, "step", &step_buf));
    try renderStep(request, allocator, oauth_request, step, .{});
}

/// The card a link asked for. `auto` lets the request and browser decide.
const Step = enum {
    auto,
    signin,
    password,
    consent,

    fn parse(value: ?[]const u8) Step {
        return std.meta.stringToEnum(Step, value orelse return .auto) orelse .auto;
    }
};

/// What a failed sign-in brings back to the card it came from.
const Feedback = struct {
    status: http.Status = .ok,
    err: ?[]const u8 = null,
    username: []const u8 = "",
    remember: bool = false,
};

/// Choose the card: consent once this browser has signed in for the request
/// or remembers an account that may continue; otherwise sign-in, starting from
/// the account the app named or the one this browser remembers.
fn renderStep(request: *http_api.Request, allocator: std.mem.Allocator, oauth_request: store.OAuthRequest, step: Step, feedback: Feedback) !void {
    const common = try commonView(allocator, oauth_request);
    if (try browser_session.signedIn(request, allocator, oauth_request)) |signed| {
        return renderConsent(request, allocator, common, oauth_request, signed.account, true);
    }
    if (step != .signin and step != .password and feedback.err == null) {
        if (try rememberedAccount(request, allocator, oauth_request)) |user| {
            if (oauth_request.login_hint != null or step == .consent) return renderConsent(request, allocator, common, oauth_request, user, false);
            const csrf = browser_session.consentCsrf(request, oauth_request.request_id, false).?;
            return page.respond(request, .ok, try page.picker(allocator, common, try accountView(allocator, user), &csrf));
        }
    }
    if (step != .signin) {
        if (try knownAccount(request, allocator, oauth_request)) |user| {
            return page.respond(request, feedback.status, try page.known(allocator, common, .{
                .account = try accountView(allocator, user),
                .password_open = step == .password or feedback.err != null,
                .remember = feedback.remember,
                .err = feedback.err,
            }));
        }
    }
    const hint = oauth_request.login_hint orelse "";
    const username = if (feedback.username.len > 0) feedback.username else if (std.mem.startsWith(u8, hint, "did:")) "" else hint;
    try page.respond(request, feedback.status, try page.signIn(allocator, common, .{
        .username = username,
        .placeholder = try usernamePlaceholder(allocator),
        .remember = feedback.remember,
        .err = feedback.err,
    }));
}

/// The account the app named with `login_hint` (a handle or DID), or, when
/// the app forces a fresh login, the account this browser remembers.
fn knownAccount(request: *const http_api.Request, allocator: std.mem.Allocator, oauth_request: store.OAuthRequest) !?auth.Account {
    if (oauth_request.login_hint) |hint| return store.findAccount(allocator, accountIdentifier(hint));
    if (!promptForcesLogin(oauth_request.prompt)) return null;
    return browser_session.account(request, allocator);
}

fn renderConsent(request: *http_api.Request, allocator: std.mem.Allocator, common: page.Common, oauth_request: store.OAuthRequest, user: auth.Account, signed_in: bool) !void {
    var sets: std.ArrayList(scope_display.PermissionSetText) = .empty;
    var words = std.mem.tokenizeScalar(u8, oauth_request.scope, ' ');
    while (words.next()) |scope| {
        if (!std.mem.startsWith(u8, scope, "include:")) continue;
        const set = permission_sets.resolvePermissionSet(allocator, scope) catch |err| {
            log.err("oauth authorize permission_set failed client={s} request={s} scope={s} err={s}\n", .{ oauth_request.client_id, oauth_request.request_id, scope, @errorName(err) });
            return page.respond(request, .bad_request, try page.failure(allocator, common.host, "This app's permissions could not be loaded", "Go back to the app and try again later.", "invalid_scope"));
        };
        try sets.append(allocator, .{ .scope = scope, .title = set.title, .detail = set.detail, .expanded = set.expanded_scope });
    }
    const csrf = browser_session.consentCsrf(request, oauth_request.request_id, signed_in) orelse
        return page.respond(request, .unauthorized, try page.failure(allocator, common.host, "Sign in again", "This browser's sign-in has ended. Go back to the app and start again.", "access_denied"));
    const summary = try scope_display.describe(allocator, oauth_request.scope, sets.items, common.client.label);
    // Space grants for one named account read better by its handle.
    var authorities: std.ArrayList(page.Authority) = .empty;
    for (summary.spaces) |space| for (space.access) |access| {
        if (access.owner != .account) continue;
        const account = (try store.findAccount(allocator, access.authority)) orelse continue;
        try authorities.append(allocator, .{ .did = access.authority, .handle = account.handle });
    };
    try page.respond(request, .ok, try page.consent(allocator, common, .{
        .account = try accountView(allocator, user),
        .summary = summary,
        .scope = oauth_request.scope,
        .authorities = authorities.items,
        .csrf = &csrf,
    }));
}

fn commonView(allocator: std.mem.Allocator, oauth_request: store.OAuthRequest) !page.Common {
    const request_uri = try std.fmt.allocPrint(allocator, "{s}{s}", .{ request_uri_prefix, oauth_request.request_id });
    const encoded = try zat.oauth.percentEncodeAlloc(allocator, request_uri);
    var client: page.Client = .{ .label = clientLabel(oauth_request.client_id), .client_id = oauth_request.client_id };
    if (!isLoopbackClientId(oauth_request.client_id)) {
        client.icon_url = try std.fmt.allocPrint(allocator, "/oauth/client-icon?request_uri={s}", .{encoded});
        if (clientMetadata(allocator, oauth_request.client_id)) |metadata| {
            client.name = zat.json.getString(metadata.value, "client_name");
            client.tos_uri = zat.json.getString(metadata.value, "tos_uri");
            client.policy_uri = zat.json.getString(metadata.value, "policy_uri");
        } else |_| {}
    }
    return .{
        .host = displayHost(config.publicUrl()),
        .request_uri = request_uri,
        .page_url = try std.fmt.allocPrint(allocator, "/oauth/authorize?request_uri={s}", .{encoded}),
        .client = client,
    };
}

/// How the consent page names a client. A conventional metadata URL is named
/// by its host; any other client_id is shown whole so its path or port cannot
/// hide behind a familiar host.
fn clientLabel(client_id: []const u8) []const u8 {
    if (isLoopbackClientId(client_id)) return "An app on your device";
    if (!std.mem.startsWith(u8, client_id, "https://")) return client_id;
    const rest = client_id["https://".len..];
    const host_end = std.mem.indexOfScalar(u8, rest, '/') orelse return client_id;
    const host = rest[0..host_end];
    const path = rest[host_end..];
    if (host.len == 0 or std.mem.indexOfAny(u8, host, "@:") != null) return client_id;
    if (std.mem.indexOfAny(u8, path, "?#") != null or !std.mem.endsWith(u8, path, ".json")) return client_id;
    return host;
}

fn accountView(allocator: std.mem.Allocator, user: auth.Account) !page.Account {
    const profile = try store.profileView(allocator, user.did);
    const passkeys = try store.listPasskeys(allocator, user.did);
    return .{
        .handle = user.handle,
        .display_name = profile.display_name,
        .avatar_url = if (profile.avatar_cid) |cid| try std.fmt.allocPrint(allocator, "/xrpc/com.atproto.sync.getBlob?did={s}&cid={s}", .{
            try zat.oauth.percentEncodeAlloc(allocator, user.did),
            try zat.oauth.percentEncodeAlloc(allocator, cid),
        }) else null,
        .has_passkeys = passkeys.len != 0,
    };
}

/// `yourname` under the first handle domain this server offers.
fn usernamePlaceholder(allocator: std.mem.Allocator) ![]const u8 {
    var domains = std.mem.tokenizeAny(u8, config.handleDomains(), ", ");
    const domain = std.mem.trimStart(u8, domains.next() orelse displayHost(config.publicUrl()), ".");
    return std.fmt.allocPrint(allocator, "yourname.{s}", .{domain});
}

/// A typed handle may carry the `@` the field shows.
fn accountIdentifier(value: []const u8) []const u8 {
    const trimmed = std.mem.trim(u8, value, " \t\r\n");
    return if (std.mem.startsWith(u8, trimmed, "@")) trimmed[1..] else trimmed;
}

const RequestFailure = enum { missing, unknown, expired, answered };

fn requestFailure(request: *http_api.Request, allocator: std.mem.Allocator, wants_json: bool, kind: RequestFailure) !void {
    if (wants_json) return switch (kind) {
        .missing => oauthError(request, .bad_request, "invalid_request", "Missing request_uri"),
        .unknown => oauthError(request, .bad_request, "invalid_request_uri", "Unknown request_uri"),
        .expired => oauthError(request, .bad_request, "invalid_request_uri", "Expired request_uri"),
        .answered => oauthError(request, .bad_request, "invalid_request_uri", "Request already answered"),
    };
    const code = if (kind == .missing) "invalid_request" else "invalid_request_uri";
    const title = switch (kind) {
        .expired => "This sign-in has expired",
        .answered => "This sign-in is already done",
        else => "This sign-in link is not valid",
    };
    const message = if (kind == .answered) "Go back to the app." else "Go back to the app and start signing in again.";
    try page.respond(request, .bad_request, try page.failure(allocator, displayHost(config.publicUrl()), title, message, code));
}

/// The requesting client's icon, served from ZDS so the authorization page
/// loads nothing from third parties. Keyed by a live authorization request so
/// this is not a general image proxy.
pub fn clientIcon(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    var request_id_buf: [512]u8 = undefined;
    const icon = found: {
        const request_id = requestIdFromTarget(request.url.raw, &request_id_buf) orelse break :found null;
        const oauth_request = (try store.getOAuthRequest(allocator, request_id)) orelse break :found null;
        if (oauth_request.expires_at < now() or isLoopbackClientId(oauth_request.client_id)) break :found null;
        const metadata = clientMetadata(allocator, oauth_request.client_id) catch break :found null;
        break :found client_icon.resolve(allocator, oauth_request.client_id, metadata.value) catch null;
    } orelse return http_api.respond(request, .not_found, "", &.{.{ .name = "cache-control", .value = "no-store" }});
    try http_api.respond(request, .ok, icon.bytes, &.{
        .{ .name = "content-type", .value = icon.content_type },
        .{ .name = "cache-control", .value = "private, max-age=3600" },
        .{ .name = "x-content-type-options", .value = "nosniff" },
        .{ .name = "content-security-policy", .value = "default-src 'none'; style-src 'unsafe-inline'; sandbox" },
    });
}

fn promptForcesLogin(prompt: ?[]const u8) bool {
    var words = std.mem.tokenizeScalar(u8, prompt orelse return false, ' ');
    while (words.next()) |word| {
        if (std.mem.eql(u8, word, "login") or std.mem.eql(u8, word, "create")) return true;
    }
    return false;
}

fn rememberedAccount(request: *const http_api.Request, allocator: std.mem.Allocator, oauth_request: store.OAuthRequest) !?auth.Account {
    if (promptForcesLogin(oauth_request.prompt)) return null;
    const user = (try browser_session.account(request, allocator)) orelse return null;
    if (!try store.accountMatchesLoginHint(allocator, oauth_request.login_hint, user.did)) return null;
    return user;
}

pub fn authorizePost(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const content_type = http_api.headerValue(request, "content-type") orelse "";
    const body = try http_api.readBodyAlloc(request, allocator, 64 * 1024);
    if (isJsonContent(content_type)) {
        const parsed = try std.json.parseFromSlice(std.json.Value, allocator, body, .{});
        return authorizeWithParams(request, allocator, JsonParams{ .json = parsed.value }, true);
    }
    return authorizeWithParams(request, allocator, Form{ .body = body }, acceptsJson(request));
}

/// Browser forms sign in first and consent second. JSON callers, which have no
/// pages, still submit credentials and consent in one request.
fn authorizeWithParams(request: *http_api.Request, allocator: std.mem.Allocator, params: anytype, wants_json: bool) !void {
    const request_uri = try requireParam(request, params, allocator, "request_uri");
    const request_id = requestIdFromUri(request_uri) orelse return requestFailure(request, allocator, wants_json, .missing);
    const oauth_request = (try store.getOAuthRequest(allocator, request_id)) orelse return requestFailure(request, allocator, wants_json, .unknown);
    if (oauth_request.expires_at <= now()) return requestFailure(request, allocator, wants_json, .expired);
    // Consent is given once: a page restored with Back cannot issue a second
    // code. Forgetting the remembered browser stays allowed.
    const forgetting = std.mem.eql(u8, (try params.value(allocator, "browser_action")) orelse "", "forget");
    if (oauth_request.sub != null and !forgetting) return requestFailure(request, allocator, wants_json, .answered);
    // The page's script asks for a same-origin page to navigate to; see authorizeReturn.
    const via_page = std.mem.eql(u8, (try params.value(allocator, "via")) orelse "", "page");
    if (try params.value(allocator, "deny")) |denied| {
        if (!std.mem.eql(u8, denied, "false")) {
            const location = try authorizationErrorRedirect(allocator, oauth_request.redirect_uri, "access_denied", "Authorization denied", oauth_request.state, oauth_request.response_mode);
            if (wants_json) return redirectJson(request, allocator, if (via_page) try returnPage(allocator, request_uri, "denied") else location);
            return redirectTo(request, location);
        }
    }
    if (try params.value(allocator, "browser_action")) |browser_action| {
        const submitted = (try params.value(allocator, "csrf")) orelse "";
        if (!browser_session.validCsrf(request, request_id, submitted)) {
            if (wants_json) return oauthError(request, .forbidden, "access_denied", "Invalid browser consent");
            return page.respond(request, .forbidden, try page.failure(allocator, displayHost(config.publicUrl()), "This page is out of date", "Go back to the app and start signing in again.", "access_denied"));
        }
        if (std.mem.eql(u8, browser_action, "forget")) {
            try browser_session.forget(request);
            const location = try std.fmt.allocPrint(allocator, "/oauth/authorize?request_uri={s}", .{try zat.oauth.percentEncodeAlloc(allocator, request_uri)});
            return redirectTo(request, location);
        }
        if (!std.mem.eql(u8, browser_action, "continue")) return oauthError(request, .bad_request, "invalid_request", "Invalid browser action");
        const consenting: browser_session.SignIn = if (try browser_session.signedIn(request, allocator, oauth_request)) |signed|
            signed
        else if (try rememberedAccount(request, allocator, oauth_request)) |user|
            .{ .account = user, .method = "password" }
        else {
            if (wants_json) return oauthError(request, .unauthorized, "access_denied", "Browser login expired. Please sign in again.");
            return page.respond(request, .unauthorized, try page.failure(allocator, displayHost(config.publicUrl()), "Sign in again", "This browser's sign-in has ended. Go back to the app and start again.", "access_denied"));
        };
        if (wants_json and via_page) {
            const code = try store.randomToken(allocator, "", 16);
            try store.authorizeOAuthRequest(oauth_request.request_id, consenting.account.did, code, consenting.method);
            return redirectJson(request, allocator, try returnPage(allocator, request_uri, "granted"));
        }
        return completeAuthorization(request, allocator, oauth_request, consenting.account, consenting.method, wants_json);
    }

    const step = Step.parse(try params.value(allocator, "step"));
    const identifier = accountIdentifier((try params.value(allocator, "username")) orelse (try params.value(allocator, "identifier")) orelse "");
    const remember = if (try params.value(allocator, "remember_browser")) |value| std.mem.eql(u8, value, "1") or std.mem.eql(u8, value, "true") else false;
    const refuse = struct {
        fn send(r: *http_api.Request, a: std.mem.Allocator, o: store.OAuthRequest, json: bool, s: Step, status: http.Status, err: []const u8, description: []const u8, name: []const u8, keep: bool) !void {
            if (json) return oauthError(r, status, "access_denied", description);
            return renderStep(r, a, o, if (s == .signin) .signin else .password, .{ .status = status, .err = err, .username = name, .remember = keep });
        }
    }.send;
    const password = (try params.value(allocator, "password")) orelse "";
    if (identifier.len == 0 or password.len == 0) {
        if (wants_json) return oauthError(request, .bad_request, "invalid_request", "Missing required field");
        return refuse(request, allocator, oauth_request, false, step, .bad_request, "Enter your username and password.", "", identifier, remember);
    }
    const user = (try store.findAccount(allocator, identifier)) orelse
        return refuse(request, allocator, oauth_request, wants_json, step, .unauthorized, "Wrong username or password.", "Invalid identifier or password", identifier, remember);
    if (!auth.passwordMatches(user, password) or !(try store.accountStatus(user.did)).isActive()) {
        return refuse(request, allocator, oauth_request, wants_json, step, .unauthorized, "Wrong username or password.", "Invalid identifier or password", identifier, remember);
    }
    if (!try store.accountMatchesLoginHint(allocator, oauth_request.login_hint, user.did)) {
        return refuse(request, allocator, oauth_request, wants_json, step, .bad_request, "This app asked to sign in with a different account.", "Account does not match login hint", identifier, remember);
    }
    if (remember) {
        if (!browser_session.sameOrigin(request)) {
            return refuse(request, allocator, oauth_request, wants_json, step, .forbidden, "Remembering this device needs a sign-in from this page.", "Remembering a browser requires a same-origin login", identifier, false);
        }
        try browser_session.remember(request, allocator, user);
    }
    if (wants_json) return completeAuthorization(request, allocator, oauth_request, user, "password", true);
    try browser_session.beginSignIn(request, allocator, request_id, user, "password", oauth_request.expires_at - now());
    try redirectTo(request, try std.fmt.allocPrint(allocator, "/oauth/authorize?request_uri={s}", .{try zat.oauth.percentEncodeAlloc(allocator, request_uri)}));
}

fn redirectJson(request: *http_api.Request, allocator: std.mem.Allocator, location: []const u8) !void {
    return http_api.json(request, .ok, try std.fmt.allocPrint(allocator, "{{\"redirect_uri\":{f}}}", .{std.json.fmt(location, .{})}));
}

fn returnPage(allocator: std.mem.Allocator, request_uri: []const u8, outcome: []const u8) ![]const u8 {
    return std.fmt.allocPrint(allocator, "/oauth/authorize/return?request_uri={s}&outcome={s}", .{ try zat.oauth.percentEncodeAlloc(allocator, request_uri), outcome });
}

/// Hands the browser back to the client from a fresh page. A navigation that
/// follows a tap, even one made by script shortly after it, onto a domain an
/// installed app claims as a universal link opens that app instead of loading
/// the URL, and the client never receives its code (stream.place claims every
/// path). This page is reached by script after consent and navigates on load,
/// with no tap behind it. A granted code is shown only to the browser that
/// signed in for this request, and only until the client exchanges it.
pub fn authorizeReturn(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const host = displayHost(config.publicUrl());
    var request_id_buf: [512]u8 = undefined;
    var outcome_buf: [16]u8 = undefined;
    const request_id = requestIdFromTarget(request.url.raw, &request_id_buf) orelse return requestFailure(request, allocator, false, .missing);
    const oauth_request = (try store.getOAuthRequest(allocator, request_id)) orelse return requestFailure(request, allocator, false, .unknown);
    const outcome = http_api.queryParam(request.url.raw, "outcome", &outcome_buf) orelse "";
    const location = if (std.mem.eql(u8, outcome, "denied"))
        try authorizationErrorRedirect(allocator, oauth_request.redirect_uri, "access_denied", "Authorization denied", oauth_request.state, oauth_request.response_mode)
    else granted: {
        const code = oauth_request.code orelse return page.respond(request, .gone, try page.failure(allocator, host, "Already returned", "This sign-in has already been handed back to the app.", "invalid_request"));
        const sub = oauth_request.sub orelse return requestFailure(request, allocator, false, .unknown);
        const signed = try browser_session.signedIn(request, allocator, oauth_request);
        const bound = if (signed) |s| std.mem.eql(u8, s.account.did, sub) else if (try rememberedAccount(request, allocator, oauth_request)) |user| std.mem.eql(u8, user.did, sub) else false;
        if (!bound) return page.respond(request, .forbidden, try page.failure(allocator, host, "Sign in again", "This browser didn't approve this request. Go back to the app and start again.", "access_denied"));
        break :granted try authorizationRedirect(allocator, oauth_request.redirect_uri, code, oauth_request.state, oauth_request.response_mode);
    };
    return page.respond(request, .ok, try page.returning(allocator, try commonView(allocator, oauth_request), location));
}

fn completeAuthorization(request: *http_api.Request, allocator: std.mem.Allocator, oauth_request: store.OAuthRequest, user: auth.Account, method: []const u8, wants_json: bool) !void {
    const code = try store.randomToken(allocator, "", 16);
    try store.authorizeOAuthRequest(oauth_request.request_id, user.did, code, method);
    const location = try authorizationRedirect(allocator, oauth_request.redirect_uri, code, oauth_request.state, oauth_request.response_mode);
    if (wants_json) {
        const response = try std.fmt.allocPrint(allocator, "{{\"redirect_uri\":{f}}}", .{std.json.fmt(location, .{})});
        return http_api.json(request, .ok, response);
    }
    try redirectTo(request, location);
}

pub fn token(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const content_type = http_api.headerValue(request, "content-type") orelse "";
    const body = try http_api.readBodyAlloc(request, allocator, 64 * 1024);
    if (isJsonContent(content_type)) {
        const parsed = try std.json.parseFromSlice(std.json.Value, allocator, body, .{});
        return tokenWithParams(request, allocator, JsonParams{ .json = parsed.value });
    }
    return tokenWithParams(request, allocator, Form{ .body = body });
}

fn tokenWithParams(request: *http_api.Request, allocator: std.mem.Allocator, params: anytype) !void {
    const grant_type = try requireParam(request, params, allocator, "grant_type");
    if (std.mem.eql(u8, grant_type, "authorization_code")) return authorizationCodeToken(request, allocator, params);
    if (std.mem.eql(u8, grant_type, "refresh_token")) return refreshToken(request, allocator, params);
    return oauthError(request, .bad_request, "unsupported_grant_type", "Unsupported grant_type");
}

pub fn introspect(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const content_type = http_api.headerValue(request, "content-type") orelse "";
    const body = try http_api.readBodyAlloc(request, allocator, 64 * 1024);
    if (isJsonContent(content_type)) {
        const parsed = try std.json.parseFromSlice(std.json.Value, allocator, body, .{});
        return introspectWithParams(request, allocator, JsonParams{ .json = parsed.value });
    }
    return introspectWithParams(request, allocator, Form{ .body = body });
}

fn introspectWithParams(request: *http_api.Request, allocator: std.mem.Allocator, params: anytype) !void {
    const token_text = try requireParam(request, params, allocator, "token");
    const row = try store.getOAuthToken(allocator, token_text);
    if (row == null or row.?.revoked or tokenExpiry(row.?) < now()) return http_api.json(request, .ok, "{\"active\":false}");
    const response = try std.fmt.allocPrint(allocator, "{{\"active\":true,\"sub\":{f},\"client_id\":{f},\"scope\":{f},\"exp\":{d}}}", .{
        std.json.fmt(row.?.did, .{}),
        std.json.fmt(row.?.client_id, .{}),
        std.json.fmt(row.?.scope, .{}),
        tokenExpiry(row.?),
    });
    try http_api.json(request, .ok, response);
}

fn tokenExpiry(row: store.OAuthToken) i64 {
    return switch (row.kind) {
        .access => row.access_expires_at,
        .refresh => row.refresh_expires_at,
        .previous_refresh => row.previous_refresh_expires_at orelse 0,
        .used_refresh => 0,
    };
}

pub fn revoke(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const content_type = http_api.headerValue(request, "content-type") orelse "";
    const body = try http_api.readBodyAlloc(request, allocator, 64 * 1024);
    if (isJsonContent(content_type)) {
        const parsed = try std.json.parseFromSlice(std.json.Value, allocator, body, .{});
        return revokeWithParams(request, allocator, JsonParams{ .json = parsed.value });
    }
    return revokeWithParams(request, allocator, Form{ .body = body });
}

fn revokeWithParams(request: *http_api.Request, allocator: std.mem.Allocator, params: anytype) !void {
    const token_text = try requireParam(request, params, allocator, "token");
    try store.revokeOAuthToken(token_text);
    try http_api.json(request, .ok, "{}");
}

fn authorizationCodeToken(request: *http_api.Request, allocator: std.mem.Allocator, params: anytype) !void {
    const code = try requireParam(request, params, allocator, "code");
    const redirect_uri = try requireParam(request, params, allocator, "redirect_uri");
    const code_verifier = try requireParam(request, params, allocator, "code_verifier");
    const client_id = try requireParam(request, params, allocator, "client_id");
    const client_metadata = try fetchClientMetadataForAuth(request, allocator, client_id);
    try requireClientAuth(request, allocator, params, client_id, client_metadata.value);
    const oauth_request = (try store.getOAuthRequestByCode(allocator, code)) orelse {
        log.err("oauth code grant invalid_code client={s} code_len={d}\n", .{ client_id, code.len });
        return oauthError(request, .bad_request, "invalid_grant", "Invalid code");
    };
    if (oauth_request.expires_at < now()) {
        log.err("oauth code grant expired request={s} client={s} expires_at={d}\n", .{ oauth_request.request_id, client_id, oauth_request.expires_at });
        return oauthError(request, .bad_request, "invalid_grant", "Expired code");
    }
    if (!std.mem.eql(u8, redirect_uri, oauth_request.redirect_uri) or !std.mem.eql(u8, client_id, oauth_request.client_id)) {
        log.err("oauth code grant mismatch request={s} row_client={s} token_client={s} row_redirect={s} token_redirect={s}\n", .{ oauth_request.request_id, oauth_request.client_id, client_id, oauth_request.redirect_uri, redirect_uri });
        return oauthError(request, .bad_request, "invalid_grant", "Mismatched token request");
    }
    if (!try pkceMatches(allocator, code_verifier, oauth_request.code_challenge)) {
        log.err("oauth code grant pkce_reject request={s} client={s} verifier_len={d}\n", .{ oauth_request.request_id, client_id, code_verifier.len });
        return oauthError(request, .bad_request, "invalid_grant", "Invalid PKCE verifier");
    }
    const did = oauth_request.sub orelse {
        log.err("oauth code grant unauthorized_code request={s} client={s}\n", .{ oauth_request.request_id, client_id });
        return oauthError(request, .bad_request, "invalid_grant", "Code was not authorized");
    };
    const account = (try store.findAccount(allocator, did)) orelse {
        log.err("oauth code grant account_not_found request={s} client={s} did={s}\n", .{ oauth_request.request_id, client_id, did });
        return oauthError(request, .bad_request, "invalid_grant", "Account not found");
    };
    const expected_jkt = oauth_request.dpop_jkt orelse {
        log.err("oauth code grant missing_dpop_binding request={s} client={s} did={s}\n", .{ oauth_request.request_id, client_id, did });
        return oauthError(request, .bad_request, "invalid_grant", "Authorization request is not DPoP-bound");
    };
    _ = dpop.verifyRequest(allocator, request, null, expected_jkt) catch |err| {
        log.err("oauth code grant dpop_reject request={s} client={s} did={s} err={s}\n", .{ oauth_request.request_id, client_id, did, @errorName(err) });
        return handleAuthorizationDpopError(request, allocator, err);
    };
    if (!try store.consumeOAuthCode(oauth_request.request_id, code)) {
        log.err("oauth code grant replay request={s} client={s} did={s}\n", .{ oauth_request.request_id, client_id, did });
        return oauthError(request, .bad_request, "invalid_grant", "Invalid code");
    }
    try issueTokenResponse(request, allocator, account, oauth_request.client_id, oauth_request.scope, null, isConfidentialClient(client_metadata.value), oauth_request.dpop_jkt, oauth_request.auth_method);
    log.info("oauth code grant issued request={s} client={s} did={s} auth_method={s}\n", .{ oauth_request.request_id, client_id, did, oauth_request.auth_method orelse "unknown" });
}

fn refreshToken(request: *http_api.Request, allocator: std.mem.Allocator, params: anytype) !void {
    const refresh = try requireParam(request, params, allocator, "refresh_token");
    const client_id = try requireParam(request, params, allocator, "client_id");
    const client_metadata = try fetchClientMetadataForAuth(request, allocator, client_id);
    try requireClientAuth(request, allocator, params, client_id, client_metadata.value);
    const token_row = (try store.getOAuthToken(allocator, refresh)) orelse {
        log.err("oauth refresh invalid_grant: refresh token not found token_len={d} client={s}\n", .{ refresh.len, client_id });
        return oauthError(request, .bad_request, "invalid_grant", "Invalid refresh token");
    };
    const client_id_match = std.mem.eql(u8, token_row.client_id, client_id);
    const ts = now();
    if (token_row.kind == .used_refresh) {
        log.err("oauth refresh invalid_grant: used refresh token replayed family_id={s} did={s} client={s}\n", .{ token_row.family_id, token_row.did, client_id });
        try store.revokeOAuthTokenFamily(token_row.family_id);
        return oauthError(request, .bad_request, "invalid_grant", "Refresh token replayed");
    }
    if (token_row.kind == .previous_refresh and tokenExpiry(token_row) < ts) {
        log.err("oauth refresh invalid_grant: previous refresh token replayed after grace family_id={s} did={s} client={s}\n", .{ token_row.family_id, token_row.did, client_id });
        try store.revokeOAuthTokenFamily(token_row.family_id);
        return oauthError(request, .bad_request, "invalid_grant", "Refresh token replayed");
    }
    if (token_row.revoked or !client_id_match or tokenExpiry(token_row) < ts) {
        log.err("oauth refresh invalid_grant: kind={s} revoked={} token_expires_at={d} now={d} client_id_match={} row_client={s} request_client={s} did={s}\n", .{ @tagName(token_row.kind), token_row.revoked, tokenExpiry(token_row), ts, client_id_match, token_row.client_id, client_id, token_row.did });
        return oauthError(request, .bad_request, "invalid_grant", "Invalid refresh token");
    }
    if (token_row.kind == .access) return oauthError(request, .bad_request, "invalid_grant", "Invalid refresh token");
    const expected_jkt = token_row.dpop_jkt orelse return oauthError(request, .bad_request, "invalid_grant", "Refresh token is not DPoP-bound");
    _ = dpop.verifyRequest(allocator, request, null, expected_jkt) catch |err| {
        return handleAuthorizationDpopError(request, allocator, err);
    };
    if (token_row.kind == .previous_refresh) return issueExistingTokenResponse(request, allocator, token_row);
    const account = (try store.findAccount(allocator, token_row.did)) orelse return oauthError(request, .bad_request, "invalid_grant", "Account not found");
    try issueTokenResponse(request, allocator, account, token_row.client_id, token_row.scope, token_row, isConfidentialClient(client_metadata.value), token_row.dpop_jkt, token_row.auth_method);
}

/// another refresh of the same token rotated first, so the presented token is
/// now that request's previous refresh token; answer it the way a sequential
/// retry inside the grace window is answered, with the winner's pair
fn answerLostRotation(request: *http_api.Request, allocator: std.mem.Allocator, presented: []const u8) !void {
    const row = (try store.getOAuthToken(allocator, presented)) orelse {
        log.err("oauth refresh invalid_grant: lost rotation and token gone token_len={d}\n", .{presented.len});
        return oauthError(request, .bad_request, "invalid_grant", "Invalid refresh token");
    };
    if (row.kind != .previous_refresh or row.revoked or tokenExpiry(row) < now()) {
        log.err("oauth refresh invalid_grant: lost rotation kind={s} revoked={} family_id={s} did={s}\n", .{ @tagName(row.kind), row.revoked, row.family_id, row.did });
        return oauthError(request, .bad_request, "invalid_grant", "Invalid refresh token");
    }
    log.info("oauth refresh lost rotation race; answering with successor family_id={s} did={s}\n", .{ row.family_id, row.did });
    return issueExistingTokenResponse(request, allocator, row);
}

fn isConfidentialClient(metadata: std.json.Value) bool {
    const method = zat.json.getString(metadata, "token_endpoint_auth_method") orelse "none";
    return !std.mem.eql(u8, method, "none");
}

const TokenLifetime = struct {
    access_expires_at: i64,
    refresh_expires_at: i64,
};

/// null once the family's absolute session lifetime has run out; otherwise
/// neither token outlives it and the refresh token lapses after the client's
/// inactivity window
fn tokenLifetime(confidential: bool, session_started_at: i64, ts: i64) ?TokenLifetime {
    const session_ends_at = session_started_at + if (confidential) confidential_session_lifetime else public_session_lifetime;
    if (session_ends_at <= ts) return null;
    const idle = if (confidential) confidential_refresh_idle else public_refresh_idle;
    return .{
        .access_expires_at = @min(ts + access_token_expires_in, session_ends_at),
        .refresh_expires_at = @min(ts + idle, session_ends_at),
    };
}

fn issueExistingTokenResponse(request: *http_api.Request, allocator: std.mem.Allocator, row: store.OAuthToken) !void {
    if (row.dpop_jkt != null) try dpop.attachNonce(allocator);
    const body = try std.fmt.allocPrint(allocator, "{{\"access_token\":{f},\"refresh_token\":{f},\"token_type\":\"DPoP\",\"expires_in\":{d},\"scope\":{f},\"sub\":{f}}}", .{
        std.json.fmt(row.access_token, .{}),
        std.json.fmt(row.refresh_token, .{}),
        @max(@as(i64, 0), row.access_expires_at - now()),
        std.json.fmt(row.scope, .{}),
        std.json.fmt(row.did, .{}),
    });
    try http_api.json(request, .ok, body);
}

fn issueTokenResponse(
    request: *http_api.Request,
    allocator: std.mem.Allocator,
    account: auth.Account,
    client_id: []const u8,
    scope: []const u8,
    rotating: ?store.OAuthToken,
    confidential: bool,
    dpop_jkt: ?[]const u8,
    auth_method: ?[]const u8,
) !void {
    const ts = now();
    const lifetime = tokenLifetime(confidential, if (rotating) |old| old.session_started_at else ts, ts) orelse {
        log.err("oauth refresh invalid_grant: session lifetime ended client={s} did={s} confidential={}\n", .{ client_id, account.did, confidential });
        return oauthError(request, .bad_request, "invalid_grant", "Session expired");
    };
    const access = if (dpop_jkt) |jkt|
        try auth.createDpopSessionJwt(allocator, "access", account, jkt)
    else
        try auth.createSessionJwt(allocator, "access", account);
    const refresh = try auth.createSessionJwt(allocator, "refresh", account);
    const access_expires_at = lifetime.access_expires_at;
    const refresh_expires_at = lifetime.refresh_expires_at;
    const granted_scope = permission_sets.prepareScopes(allocator, scope, account.did) catch |err| {
        log.err("oauth grant preparation failed client={s} did={s} err={s}\n", .{ client_id, account.did, @errorName(err) });
        return oauthError(request, .bad_request, "invalid_scope", "Failed to resolve requested permission set");
    };
    const token_scope = permission_sets.expandScopes(allocator, granted_scope, account.did) catch |err| {
        log.err("oauth token scope_expand failed client={s} did={s} scope={s} err={s}\n", .{ client_id, account.did, scope, @errorName(err) });
        return oauthError(request, .bad_request, "invalid_scope", "Failed to resolve requested permission set");
    };
    if (!config.permissionedData() and permission_sets.containsSpaceScope(token_scope)) {
        return oauthError(request, .bad_request, "invalid_scope", permissioned_data_disabled_message);
    }
    if (rotating) |old| {
        if (!try store.rotateOAuthToken(old.refresh_token, access, refresh, access_expires_at, refresh_expires_at, now() + previous_refresh_grace_in)) {
            return answerLostRotation(request, allocator, old.refresh_token);
        }
    } else {
        try store.putOAuthToken(account.did, client_id, granted_scope, access, refresh, access_expires_at, refresh_expires_at, dpop_jkt, auth_method);
    }
    if (dpop_jkt != null) try dpop.attachNonce(allocator);
    const token_type = if (dpop_jkt != null) "DPoP" else "Bearer";
    const body = try std.fmt.allocPrint(allocator, "{{\"access_token\":{f},\"refresh_token\":{f},\"token_type\":{f},\"expires_in\":{d},\"scope\":{f},\"sub\":{f}}}", .{
        std.json.fmt(access, .{}),
        std.json.fmt(refresh, .{}),
        std.json.fmt(token_type, .{}),
        access_expires_at - ts,
        std.json.fmt(granted_scope, .{}),
        std.json.fmt(account.did, .{}),
    });
    try http_api.json(request, .ok, body);
}

fn requireClientAuth(request: *http_api.Request, allocator: std.mem.Allocator, params: anytype, client_id: []const u8, metadata: std.json.Value) !void {
    const method = zat.json.getString(metadata, "token_endpoint_auth_method") orelse "none";
    if (std.mem.eql(u8, method, "none")) return;
    if (!std.mem.eql(u8, method, "private_key_jwt")) {
        log.err("oauth client_auth rejected unsupported_method client={s} method={s}\n", .{ client_id, method });
        return oauthError(request, .bad_request, "invalid_client", "Unsupported client authentication method");
    }

    const assertion_type = try params.value(allocator, "client_assertion_type") orelse {
        log.err("oauth client_auth rejected missing_assertion_type client={s}\n", .{client_id});
        return oauthError(request, .bad_request, "invalid_client", "Missing client assertion type");
    };
    if (!std.mem.eql(u8, assertion_type, "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")) {
        log.err("oauth client_auth rejected unsupported_assertion_type client={s} type={s}\n", .{ client_id, assertion_type });
        return oauthError(request, .bad_request, "invalid_client", "Unsupported client assertion type");
    }
    const assertion = try params.value(allocator, "client_assertion") orelse {
        log.err("oauth client_auth rejected missing_assertion client={s}\n", .{client_id});
        return oauthError(request, .bad_request, "invalid_client", "Missing client assertion");
    };
    verifyClientAssertion(allocator, metadata, client_id, assertion) catch |err| {
        log.err("oauth client_auth rejected invalid_assertion client={s} err={s}\n", .{ client_id, @errorName(err) });
        return oauthError(request, .bad_request, "invalid_client", "Invalid client assertion");
    };
}

fn fetchClientMetadataForAuth(request: *http_api.Request, allocator: std.mem.Allocator, client_id: []const u8) !std.json.Parsed(std.json.Value) {
    const metadata = clientMetadata(allocator, client_id) catch |err| {
        log.err("oauth client_auth rejected metadata_fetch_failed client={s} err={s}\n", .{ client_id, @errorName(err) });
        try oauthError(request, .bad_request, "invalid_client", clientMetadataErrorDescription(err));
        return error.HandledResponse;
    };
    if ((zat.json.getBool(metadata.value, "dpop_bound_access_tokens") orelse false) != true) {
        try oauthError(request, .bad_request, "invalid_client", "dpop_bound_access_tokens must be true");
        return error.HandledResponse;
    }
    return metadata;
}

fn fetchJson(allocator: std.mem.Allocator, url: []const u8, max_response_size: usize) !std.json.Parsed(std.json.Value) {
    if (try client_document_cache.get(allocator, url, now())) |body| {
        return try std.json.parseFromSlice(std.json.Value, allocator, body, .{});
    }

    var transport = zat.HttpTransport.init(store.currentIo(), allocator);
    defer transport.deinit();
    const result = try outbound.fetch(allocator, store.currentIo(), &transport, .{
        .url = url,
        .method = .GET,
        .accept = "application/json",
        .max_response_size = max_response_size,
    });
    const status_code = @backingInt(result.status);
    if (status_code < 200 or status_code >= 300) return error.HttpStatus;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, result.body, .{});
    client_document_cache.put(url, result.body, now() + client_document_ttl_seconds) catch {};
    return parsed;
}

fn verifyClientAssertion(allocator: std.mem.Allocator, metadata: std.json.Value, client_id: []const u8, assertion: []const u8) !void {
    var arena = std.heap.ArenaAllocator.init(allocator);
    defer arena.deinit();
    const parsed = try parseClientAssertion(arena.allocator(), client_id, assertion, now());

    var fetched_jwks: ?std.json.Parsed(std.json.Value) = null;
    defer if (fetched_jwks) |document| document.deinit();
    const client_keys = switch (try clientJwksSource(metadata)) {
        .inline_keys => |keys| keys,
        .uri => |jwks_uri| blk: {
            fetched_jwks = try fetchJson(allocator, jwks_uri, 256 * 1024);
            break :blk fetched_jwks.?.value;
        },
    };
    try parsed.verifySignature(client_keys);
}

/// the claims are checked before the client's JWKS is fetched
fn parseClientAssertion(arena: std.mem.Allocator, client_id: []const u8, assertion: []const u8, current_time: i64) zat.oauth.ClientAssertionError!zat.oauth.ClientAssertion {
    return zat.oauth.parseClientAssertion(arena, assertion, .{
        .client_id = client_id,
        .audience = config.publicUrl(),
        .now = current_time,
    }) catch |err| {
        log.err("oauth client_assertion rejected client={s} err={s} expected_aud={s} now={d}\n", .{ client_id, @errorName(err), config.publicUrl(), current_time });
        return err;
    };
}

const ClientJwksSource = union(enum) {
    inline_keys: std.json.Value,
    uri: []const u8,
};

/// client metadata carries its signing keys either inline as `jwks` or by
/// reference as `jwks_uri`; the reference provider treats the two as mutually
/// exclusive and requires one of them for private_key_jwt
fn clientJwksSource(metadata: std.json.Value) !ClientJwksSource {
    const object = switch (metadata) {
        .object => |object| object,
        else => return error.InvalidClientMetadata,
    };
    const inline_keys = object.get("jwks");
    const uri = zat.json.getString(metadata, "jwks_uri");
    if (inline_keys != null and uri != null) return error.InvalidClientMetadata;
    if (inline_keys) |keys| return .{ .inline_keys = keys };
    if (uri) |value| return .{ .uri = value };
    return error.InvalidClientMetadata;
}

const Form = struct {
    body: []const u8,

    fn value(self: Form, allocator: std.mem.Allocator, name: []const u8) !?[]const u8 {
        var params = std.mem.splitScalar(u8, self.body, '&');
        while (params.next()) |param| {
            const eq = std.mem.indexOfScalar(u8, param, '=') orelse continue;
            var name_buf: [256]u8 = undefined;
            const decoded_name = http_api.percentDecode(param[0..eq], &name_buf) catch continue;
            if (!std.mem.eql(u8, decoded_name, name)) continue;
            const out = try allocator.alloc(u8, param.len - eq);
            return try http_api.percentDecode(param[eq + 1 ..], out);
        }
        return null;
    }
};

const JsonParams = struct {
    json: std.json.Value,

    fn value(self: JsonParams, allocator: std.mem.Allocator, name: []const u8) !?[]const u8 {
        if (zat.json.getBool(self.json, name)) |boolean| return if (boolean) "true" else "false";
        const string = zat.json.getString(self.json, name) orelse return null;
        return try allocator.dupe(u8, string);
    }
};

fn requireParam(request: *http_api.Request, params: anytype, allocator: std.mem.Allocator, name: []const u8) ![]const u8 {
    return (try params.value(allocator, name)) orelse {
        try oauthError(request, .bad_request, "invalid_request", "Missing required field");
        return error.MissingFormField;
    };
}

fn isJsonContent(content_type: []const u8) bool {
    return std.mem.indexOf(u8, content_type, "application/json") != null;
}

fn requestIdFromTarget(target: []const u8, out: []u8) ?[]const u8 {
    const value = http_api.queryParam(target, "request_uri", out) orelse return null;
    return requestIdFromUri(value);
}

fn requestIdFromUri(request_uri: []const u8) ?[]const u8 {
    if (!std.mem.startsWith(u8, request_uri, request_uri_prefix)) return null;
    return request_uri[request_uri_prefix.len..];
}

fn authorizationRedirect(allocator: std.mem.Allocator, redirect_uri: []const u8, code: []const u8, state: []const u8, response_mode: []const u8) ![]const u8 {
    const sep = authorizationResponseSeparator(redirect_uri, response_mode);
    const code_enc = try zat.oauth.percentEncodeAlloc(allocator, code);
    const state_enc = try zat.oauth.percentEncodeAlloc(allocator, state);
    const iss_enc = try zat.oauth.percentEncodeAlloc(allocator, config.publicUrl());
    return std.fmt.allocPrint(allocator, "{s}{s}code={s}&state={s}&iss={s}", .{ redirect_uri, sep, code_enc, state_enc, iss_enc });
}

fn authorizationErrorRedirect(allocator: std.mem.Allocator, redirect_uri: []const u8, err: []const u8, description: []const u8, state: []const u8, response_mode: []const u8) ![]const u8 {
    const sep = authorizationResponseSeparator(redirect_uri, response_mode);
    return std.fmt.allocPrint(allocator, "{s}{s}error={s}&error_description={s}&state={s}&iss={s}", .{
        redirect_uri,
        sep,
        try zat.oauth.percentEncodeAlloc(allocator, err),
        try zat.oauth.percentEncodeAlloc(allocator, description),
        try zat.oauth.percentEncodeAlloc(allocator, state),
        try zat.oauth.percentEncodeAlloc(allocator, config.publicUrl()),
    });
}

fn authorizationResponseSeparator(redirect_uri: []const u8, response_mode: []const u8) []const u8 {
    if (std.mem.eql(u8, response_mode, "fragment")) {
        return if (std.mem.indexOfScalar(u8, redirect_uri, '#') == null) "#" else "&";
    }
    return if (std.mem.indexOfScalar(u8, redirect_uri, '?') == null) "?" else "&";
}

fn redirectTo(request: *http_api.Request, location: []const u8) !void {
    const headers = [_]http.Header{
        .{ .name = "location", .value = location },
        .{ .name = "access-control-allow-origin", .value = "*" },
        .{ .name = "connection", .value = "close" },
    };
    try http_api.respondNowClose(request, .see_other, "", &headers);
}

fn clientDisplayInfo(allocator: std.mem.Allocator, client_id: []const u8) !ClientDisplayInfo {
    const metadata = try clientMetadata(allocator, client_id);
    const name = zat.json.getString(metadata.value, "client_name") orelse
        zat.json.getString(metadata.value, "client_id") orelse
        client_id;
    const uri = zat.json.getString(metadata.value, "client_uri") orelse client_id;
    return .{
        .name = try allocator.dupe(u8, name),
        .uri = try allocator.dupe(u8, uri),
    };
}

fn authRequestInfoJson(allocator: std.mem.Allocator, oauth_request: store.OAuthRequest, client: ClientDisplayInfo) ![]const u8 {
    const Response = struct {
        request_uri: []const u8,
        client_id: []const u8,
        client_name: []const u8,
        client_uri: []const u8,
        scope: []const u8,
        response_mode: []const u8,
        login_hint: []const u8,
    };
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try std.json.Stringify.value(Response{
        .request_uri = try std.fmt.allocPrint(allocator, "{s}{s}", .{ request_uri_prefix, oauth_request.request_id }),
        .client_id = oauth_request.client_id,
        .client_name = client.name,
        .client_uri = client.uri,
        .scope = oauth_request.scope,
        .response_mode = oauth_request.response_mode,
        .login_hint = oauth_request.login_hint orelse "",
    }, .{}, &out.writer);
    return out.toOwnedSlice();
}

fn displayHost(public_url: []const u8) []const u8 {
    var value = public_url;
    if (std.mem.startsWith(u8, value, "https://")) value = value["https://".len..];
    if (std.mem.startsWith(u8, value, "http://")) value = value["http://".len..];
    if (std.mem.indexOfScalar(u8, value, '/')) |idx| value = value[0..idx];
    return value;
}

fn pkceMatches(allocator: std.mem.Allocator, verifier: []const u8, challenge: []const u8) !bool {
    const expected = try zat.oauth.generatePkceChallenge(allocator, verifier);
    if (expected.len != 43 or challenge.len != 43) return false;
    return std.crypto.timing_safe.eql([43]u8, expected[0..43].*, challenge[0..43].*);
}

fn validPrompt(prompt: []const u8) bool {
    var parts = std.mem.splitScalar(u8, prompt, ' ');
    while (parts.next()) |part| {
        if (part.len == 0) continue;
        if (!(std.mem.eql(u8, part, "none") or
            std.mem.eql(u8, part, "login") or
            std.mem.eql(u8, part, "consent") or
            std.mem.eql(u8, part, "select_account") or
            std.mem.eql(u8, part, "create"))) return false;
    }
    return true;
}

fn validResponseMode(response_mode: []const u8) bool {
    return std.mem.eql(u8, response_mode, "query") or
        std.mem.eql(u8, response_mode, "fragment");
}

const permissioned_data_disabled_message = "Permissioned data (spaces) is not enabled on this server";

fn validSpaceScopeType(maybe_type: ?[]const u8) bool {
    const space_type = maybe_type orelse return false;
    return std.mem.eql(u8, space_type, "*") or zat.Nsid.parse(space_type) != null;
}

fn validateScope(request: *http_api.Request, allocator: std.mem.Allocator, scope_text: []const u8, client_scope_text: ?[]const u8) !void {
    var scopes = std.mem.splitScalar(u8, scope_text, ' ');
    var saw_scope = false;
    var has_transition = false;
    var has_granular = false;
    while (scopes.next()) |scope| {
        if (scope.len == 0) continue;
        saw_scope = true;
        if (client_scope_text) |client_scopes| {
            if (!scopeRegistered(client_scopes, scope)) {
                return oauthError(request, .bad_request, "invalid_scope", "Scope not registered for this client");
            }
        }
        if (std.mem.eql(u8, scope, "atproto")) continue;
        if (std.mem.eql(u8, scope, "transition:generic") or std.mem.eql(u8, scope, "transition:email") or std.mem.eql(u8, scope, "transition:chat.bsky")) {
            has_transition = true;
            continue;
        }
        if (isGranularScope(scope)) {
            if (std.mem.startsWith(u8, scope, "include:")) {
                const permission_set = permission_sets.resolvePermissionSet(allocator, scope) catch |err| {
                    log.err("oauth validate include failed scope={s} err={s}\n", .{ scope, @errorName(err) });
                    return oauthError(request, .bad_request, "invalid_scope", "Failed to resolve requested permission set");
                };
                if (!config.permissionedData() and permission_sets.containsSpaceScope(permission_set.expanded_scope)) {
                    return oauthError(request, .bad_request, "invalid_scope", permissioned_data_disabled_message);
                }
            } else if (!config.permissionedData() and permission_sets.containsSpaceScope(scope)) {
                return oauthError(request, .bad_request, "invalid_scope", permissioned_data_disabled_message);
            } else if (scope_rules.isSpaceScope(scope) and !validSpaceScopeType(scope_rules.spaceScopeType(scope))) {
                return oauthError(request, .bad_request, "invalid_scope", "A space scope names one type, * or an NSID, positionally or with spaceType");
            } else if (std.mem.startsWith(u8, scope, "repo") and (scope_rules.RepoScope.parse(scope) == null or !try scope_rules.validTypedDataScope(allocator, scope))) {
                return oauthError(request, .bad_request, "invalid_scope", "A repo permission names * or exact collections, positionally or with collection, and only create, update or delete actions");
            } else if (std.mem.startsWith(u8, scope, "blob") and (scope_rules.BlobScope.parse(scope) == null or !try scope_rules.validTypedDataScope(allocator, scope))) {
                return oauthError(request, .bad_request, "invalid_scope", "A blob permission names the MIME types it accepts (*/*, type/* or type/subtype), positionally or with accept");
            } else if (std.mem.startsWith(u8, scope, "rpc") and (scope_rules.RpcScope.parse(scope) == null or !try scope_rules.validTypedDataScope(allocator, scope))) {
                return oauthError(request, .bad_request, "invalid_scope", "An rpc permission names * or exact methods and one DID service reference or wildcard audience");
            }
            has_granular = true;
            continue;
        }
        return oauthError(request, .bad_request, "invalid_scope", "Unsupported scope");
    }
    if (!saw_scope) return oauthError(request, .bad_request, "invalid_scope", "Empty scope");
    if (has_transition and has_granular) {
        return oauthError(request, .bad_request, "invalid_scope", "Cannot mix transition scopes with granular scopes");
    }
}

fn scopeRegistered(client_scope_text: []const u8, requested_scope: []const u8) bool {
    var client_scopes = std.mem.splitScalar(u8, client_scope_text, ' ');
    while (client_scopes.next()) |client_scope| {
        if (client_scope.len == 0) continue;
        if (std.mem.eql(u8, client_scope, requested_scope)) return true;
        if (sameScopeResource(client_scope, requested_scope)) return true;
    }
    return false;
}

fn sameScopeResource(client_scope: []const u8, requested_scope: []const u8) bool {
    const client_base = scopeBase(client_scope);
    const requested_base = scopeBase(requested_scope);
    // Parameters are not compared, so only a registration without them (`repo:*`, `blob:*/*`) covers other
    // scopes; one with them (`rpc:*?aud=…`, `repo?collection=…`) covers only itself, which scopeRegistered
    // checks before calling this.
    if (client_base.len != client_scope.len) return false;
    if (std.mem.indexOfScalar(u8, client_base, ':') == null or std.mem.indexOfScalar(u8, requested_base, ':') == null) return false;
    const resource = scopeResourceType(client_base);
    if (!std.mem.eql(u8, resource, scopeResourceType(requested_base))) return false;
    if (std.mem.eql(u8, resource, "blob")) {
        return blobResourceCovers(scopeResourceName(client_base), scopeResourceName(requested_base));
    }
    return wildcardResourceCovers(scopeResourceName(client_base), scopeResourceName(requested_base));
}

fn scopeBase(scope: []const u8) []const u8 {
    return if (std.mem.indexOfScalar(u8, scope, '?')) |idx| scope[0..idx] else scope;
}

fn scopeResourceType(scope: []const u8) []const u8 {
    return if (std.mem.indexOfScalar(u8, scope, ':')) |idx| scope[0..idx] else scope;
}

fn scopeResourceName(scope: []const u8) []const u8 {
    return if (std.mem.indexOfScalar(u8, scope, ':')) |idx| scope[idx + 1 ..] else "";
}

fn wildcardResourceCovers(allowed: []const u8, requested: []const u8) bool {
    if (std.mem.eql(u8, allowed, "*")) return true;
    if (std.mem.eql(u8, allowed, requested)) return true;
    if (!std.mem.endsWith(u8, allowed, ".*")) return false;
    const prefix = allowed[0 .. allowed.len - 2];
    return std.mem.startsWith(u8, requested, prefix) and requested.len > prefix.len and requested[prefix.len] == '.';
}

fn blobResourceCovers(allowed: []const u8, requested: []const u8) bool {
    if (std.mem.eql(u8, allowed, "*/*")) return true;
    if (std.mem.eql(u8, allowed, requested)) return true;
    if (!std.mem.endsWith(u8, allowed, "/*")) return false;
    const prefix = allowed[0 .. allowed.len - 2];
    return std.mem.startsWith(u8, requested, prefix) and requested.len > prefix.len and requested[prefix.len] == '/';
}

fn isGranularScope(scope: []const u8) bool {
    return std.mem.startsWith(u8, scope, "repo:") or
        std.mem.startsWith(u8, scope, "repo?") or
        std.mem.startsWith(u8, scope, "blob:") or
        std.mem.startsWith(u8, scope, "blob?") or
        std.mem.startsWith(u8, scope, "rpc:") or
        std.mem.startsWith(u8, scope, "rpc?") or
        std.mem.startsWith(u8, scope, "account:") or
        std.mem.startsWith(u8, scope, "identity:") or
        std.mem.startsWith(u8, scope, "include:") or
        std.mem.startsWith(u8, scope, "space:") or
        std.mem.startsWith(u8, scope, "space?");
}

fn joinUrl(allocator: std.mem.Allocator, base: []const u8, path: []const u8) ![]const u8 {
    return std.fmt.allocPrint(allocator, "{s}{s}", .{ base, path });
}

fn trimTrailingSlash(value: []const u8) []const u8 {
    if (value.len > 1 and value[value.len - 1] == '/') return value[0 .. value.len - 1];
    return value;
}

fn acceptsJson(request: *const http_api.Request) bool {
    const accept = http_api.headerValue(request, "accept") orelse return false;
    return std.mem.indexOf(u8, accept, "application/json") != null;
}

fn now() i64 {
    return clock.nowSeconds();
}

// writes the error response and then fails with HandledResponse, so a helper
// that does `return oauthError(...)` stops its caller too: before this, `try
// validateScope(...)` and `try requireClientAuth(...)` returned success after
// writing a 400 and the handler went on to overwrite it with a 201/200.
fn oauthError(request: *http_api.Request, status: http.Status, err: []const u8, description: []const u8) !void {
    var buf: [512]u8 = undefined;
    const body = try std.fmt.bufPrint(&buf, "{{\"error\":{f},\"error_description\":{f}}}", .{ std.json.fmt(err, .{}), std.json.fmt(description, .{}) });
    try http_api.json(request, status, body);
    return error.HandledResponse;
}

fn handleAuthorizationDpopError(request: *http_api.Request, allocator: std.mem.Allocator, err: anyerror) !void {
    return switch (err) {
        error.UseDpopNonce, error.MissingProof => dpop.challengeAuthorizationServer(request, allocator),
        error.KeyBindingMismatch => oauthError(request, .bad_request, "invalid_grant", "DPoP proof does not match the expected JKT"),
        error.Replay, error.InvalidProof => oauthError(request, .unauthorized, "invalid_dpop_proof", "Invalid DPoP proof"),
        else => err,
    };
}

test "client assertion accepts exp or recent iat" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const keypair = try zat.Keypair.fromSecretKey(.p256, @splat(0x45));
    const client_id = "https://client.example/oauth-client-metadata.json";
    const cases = [_]struct { claims: []const u8, ok: bool }{
        .{ .claims = "\"exp\":1060", .ok = true },
        .{ .claims = "\"iat\":940", .ok = true },
        .{ .claims = "\"exp\":999", .ok = false },
        .{ .claims = "\"iat\":699", .ok = false },
        .{ .claims = "\"iat\":1061", .ok = false },
        .{ .claims = "\"iat\":1061,\"exp\":1200", .ok = false },
        .{ .claims = "\"iat\":0", .ok = false },
    };
    for (cases) |case| {
        const payload = try std.fmt.allocPrint(a, "{{\"iss\":\"{s}\",\"sub\":\"{s}\",\"aud\":\"{s}\",\"jti\":\"j\",{s}}}", .{ client_id, client_id, config.publicUrl(), case.claims });
        const signed = try zat.oauth.createJwt(a, "{\"alg\":\"ES256\"}", payload, &keypair);
        if (parseClientAssertion(a, client_id, signed, 1000)) |_| {
            try std.testing.expect(case.ok);
        } else |_| try std.testing.expect(!case.ok);
    }
    const no_time = try std.fmt.allocPrint(a, "{{\"iss\":\"{s}\",\"sub\":\"{s}\",\"aud\":[\"{s}\"],\"jti\":\"j\"}}", .{ client_id, client_id, config.publicUrl() });
    try std.testing.expectError(error.InvalidClientAssertion, parseClientAssertion(a, client_id, try zat.oauth.createJwt(a, "{\"alg\":\"ES256\"}", no_time, &keypair), 1000));
}

test "granular scopes accept query-form repo permissions" {
    try std.testing.expect(isGranularScope("repo:*"));
    try std.testing.expect(isGranularScope("repo?collection=place.stream.live&action=create"));
    try std.testing.expect(isGranularScope("repo?action=create&collection=place.stream.live"));
    try std.testing.expect(isGranularScope("rpc:app.bsky.actor.getProfile?aud=did:web:api.bsky.app%23bsky_appview"));
    try std.testing.expect(isGranularScope("rpc?lxm=*&aud=did:web:api.bsky.app%23bsky_appview"));
    try std.testing.expect(isGranularScope("space:app.bulleted.space?action=read"));
    try std.testing.expect(isGranularScope("space?type=app.bulleted.space"));
    try std.testing.expect(!isGranularScope("transition:generic"));
}

test "hud.place's registered scopes pass validation" {
    const registered = "atproto repo:app.bsky.feed.like repo:app.bsky.feed.post repo:app.bsky.feed.repost repo:app.bsky.feed.threadgate repo:place.hud.theme repo:social.grain.comment repo:social.grain.favorite repo:social.grain.gallery repo:social.grain.gallery.item repo:social.grain.photo repo:social.grain.photo.exif blob:image/jpeg blob:image/png blob:image/webp blob:image/heic rpc?lxm=*&aud=did:web:api.bsky.app%23bsky_appview rpc?lxm=*&aud=did:web:api.bsky.chat%23bsky_chat rpc?lxm=*&aud=did:web:api.next.plyr.fm%23plyr_appview rpc?lxm=*&aud=did:web:grain.social%23grain_appview rpc?lxm=*&aud=did:web:knotless.dev%23knotless_appview rpc:app.bsky.actor.getPreferences?aud=* rpc:app.bsky.feed.sendInteractions?aud=*";
    var scopes = std.mem.splitScalar(u8, registered, ' ');
    while (scopes.next()) |scope| {
        try std.testing.expect(scopeRegistered(registered, scope));
        if (std.mem.eql(u8, scope, "atproto")) continue;
        try std.testing.expect(isGranularScope(scope));
        if (std.mem.startsWith(u8, scope, "rpc")) try std.testing.expect(scope_rules.RpcScope.parse(scope) != null);
        if (std.mem.startsWith(u8, scope, "repo")) try std.testing.expect(scope_rules.RepoScope.parse(scope) != null);
        if (std.mem.startsWith(u8, scope, "blob")) try std.testing.expect(scope_rules.BlobScope.parse(scope) != null);
    }
}

test "repo and blob forms clients send still parse" {
    for ([_][]const u8{
        "repo:*",
        "repo:*?action=create",
        "repo:app.bsky.feed.post?action=create",
        "repo:social.grain.gallery?action=create&action=delete",
        "repo?collection=place.stream.live&action=create",
        "repo?action=create&collection=place.stream.live",
        "repo?collection=app.bsky.actor.status",
    }) |scope| {
        try std.testing.expect(isGranularScope(scope));
        try std.testing.expect(scope_rules.RepoScope.parse(scope) != null);
    }
    for ([_][]const u8{ "blob:*/*", "blob:image/*", "blob:image/jpeg", "blob?accept=image/png&accept=image/jpeg" }) |scope| {
        try std.testing.expect(isGranularScope(scope));
        try std.testing.expect(scope_rules.BlobScope.parse(scope) != null);
    }
}

test "sign-in refuses repo, blob and RPC scopes outside the reference grammar" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    for ([_][]const u8{
        "atproto repo:",
        "atproto repo:app.bsky.feed.*",
        "atproto repo?action=create",
        "atproto repo:*?action=publish",
        "atproto blob:",
        "atproto blob?",
        "atproto blob:*/png",
        "atproto blob?accept=image",
        "atproto rpc:app.bsky.feed.getFeed?aud=did:web:api.bsky.app",
        "atproto rpc:app.bsky.feed.getFeed?aud=*&aud=*",
        "atproto rpc:*?aud=*",
    }) |scope| {
        var ht = @import("httpz").testing.init(.{});
        defer ht.deinit();
        http_api.bindResponse(ht.res);
        defer http_api.unbindResponse();
        try std.testing.expectError(error.HandledResponse, validateScope(ht.req, a, scope, null));
        try ht.expectStatus(400);
        try std.testing.expect(std.mem.indexOf(u8, ht.res.body, "\"error\":\"invalid_scope\"") != null);
    }
    var ht = @import("httpz").testing.init(.{});
    defer ht.deinit();
    http_api.bindResponse(ht.res);
    defer http_api.unbindResponse();
    try validateScope(ht.req, a, "atproto repo:app.bsky.feed.post blob:image/* blob?accept=video/mp4 rpc:app.bsky.feed.getFeed?aud=*", null);
}

test "rpc forms in live grants still parse" {
    for ([_][]const u8{
        "rpc:fm.plyr.next.jam.join?aud=did:web:jams.next.plyr.fm#jams",
        "rpc:org.tangled.temp.notification.markAllRead?aud=*",
        "rpc:com.atproto.moderation.createReport?aud=did:web:api.frequency.app%23frequency_appview",
        "rpc:com.atproto.moderation.createReport?aud=did:web:api.frequency.app",
        "rpc:*?aud=did:web:grain.social%23grain_appview",
    }) |scope| try std.testing.expect(scope_rules.RpcScope.parse(scope) != null);
}

test "registered client scope matching follows resource base" {
    try std.testing.expect(scopeRegistered("atproto repo:*?action=create", "repo:*?action=create"));
    try std.testing.expect(scopeRegistered("atproto repo:*", "repo:*?action=create"));
    try std.testing.expect(scopeRegistered("atproto repo:*", "repo:earth.cirrus.check.testrecord?action=create"));
    try std.testing.expect(scopeRegistered("atproto blob:*/*", "blob:image/*"));
    try std.testing.expect(scopeRegistered("atproto transition:generic", "transition:generic"));
    try std.testing.expect(!scopeRegistered("atproto repo:app.bsky.feed.post", "repo:earth.cirrus.check.testrecord"));
    try std.testing.expect(!scopeRegistered("atproto", "transition:generic"));
    try std.testing.expect(!scopeRegistered("atproto blob:image/*", "blob:*/*"));
    try std.testing.expect(scopeRegistered("atproto rpc?lxm=*&aud=did:web:api.bsky.app%23bsky_appview", "rpc?lxm=*&aud=did:web:api.bsky.app%23bsky_appview"));
    try std.testing.expect(!scopeRegistered("atproto rpc?lxm=app.bsky.feed.getFeed&aud=did:web:api.bsky.app%23bsky_appview", "rpc?lxm=*&aud=did:web:evil.example%23svc"));
    try std.testing.expect(!scopeRegistered("atproto repo?collection=app.bsky.feed.post", "repo?collection=app.bsky.graph.follow"));
    try std.testing.expect(!scopeRegistered("atproto rpc:*?aud=did:web:api.bsky.app%23bsky_appview", "rpc:chat.bsky.convo.sendMessage?aud=*"));
    try std.testing.expect(!scopeRegistered("atproto rpc:app.bsky.feed.getFeed?aud=did:web:api.bsky.app%23bsky_appview", "rpc:app.bsky.feed.getFeed?aud=*"));
    try std.testing.expect(!scopeRegistered("atproto repo:app.bsky.feed.post?action=create", "repo:app.bsky.feed.post"));
}

test "native loopback redirect matches any port; everything else stays exact" {
    try std.testing.expect(loopbackRedirectMatchesAnyPort("http://127.0.0.1/callback", "http://127.0.0.1:49152/callback"));
    try std.testing.expect(loopbackRedirectMatchesAnyPort("http://[::1]/callback", "http://[::1]:8080/callback"));
    try std.testing.expect(loopbackRedirectMatchesAnyPort("http://127.0.0.1/cb?x=1", "http://127.0.0.1:5/cb?x=1"));
    try std.testing.expect(!loopbackRedirectMatchesAnyPort("http://127.0.0.1:3000/callback", "http://127.0.0.1:3001/callback"));
    try std.testing.expect(!loopbackRedirectMatchesAnyPort("http://127.0.0.1/callback", "http://127.0.0.1:49152/other"));
    try std.testing.expect(!loopbackRedirectMatchesAnyPort("http://127.0.0.1/callback", "http://127.0.0.1:49152/callback?x=1"));
    try std.testing.expect(!loopbackRedirectMatchesAnyPort("http://127.0.0.1/callback", "http://[::1]:49152/callback"));
    try std.testing.expect(!loopbackRedirectMatchesAnyPort("http://127.0.0.1/callback", "http://127.0.0.10:49152/callback"));
    try std.testing.expect(!loopbackRedirectMatchesAnyPort("http://127.0.0.1/callback", "http://127.0.0.1:abc/callback"));
    try std.testing.expect(!loopbackRedirectMatchesAnyPort("http://localhost/callback", "http://localhost:49152/callback"));
    try std.testing.expect(!loopbackRedirectMatchesAnyPort("https://127.0.0.1/callback", "https://127.0.0.1:49152/callback"));
    try std.testing.expect(!loopbackRedirectMatchesAnyPort("https://app.example/callback", "https://app.example:443/callback"));
}

test "loopback client ids are virtual: exact http://localhost origin, query-only metadata" {
    try std.testing.expect(isLoopbackClientId("http://localhost"));
    try std.testing.expect(isLoopbackClientId("http://localhost/"));
    try std.testing.expect(isLoopbackClientId("http://localhost?scope=atproto"));
    try std.testing.expect(isLoopbackClientId("http://localhost/?redirect_uri=http%3A%2F%2F127.0.0.1%3A5199%2F"));
    try std.testing.expect(!isLoopbackClientId("http://localhost:3000"));
    try std.testing.expect(!isLoopbackClientId("http://localhost/path?scope=atproto"));
    try std.testing.expect(!isLoopbackClientId("http://localhost.example"));
    try std.testing.expect(!isLoopbackClientId("https://localhost"));
    try std.testing.expect(!isLoopbackClientId("http://127.0.0.1?scope=atproto"));

    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const defaults = try parseLoopbackClientId(allocator, "http://localhost");
    try std.testing.expectEqualStrings("atproto", defaults.scope);
    try std.testing.expectEqual(@as(usize, 2), defaults.redirect_uris.len);
    try std.testing.expectEqualStrings("http://127.0.0.1/", defaults.redirect_uris[0]);
    try std.testing.expectEqualStrings("http://[::1]/", defaults.redirect_uris[1]);

    const configured = try parseLoopbackClientId(allocator, "http://localhost?redirect_uri=http%3A%2F%2F127.0.0.1%3A5199%2Fcb&redirect_uri=http%3A%2F%2F%5B%3A%3A1%5D%2Fcb&scope=atproto%20repo%3A*");
    try std.testing.expectEqualStrings("atproto repo:*", configured.scope);
    try std.testing.expectEqual(@as(usize, 2), configured.redirect_uris.len);
    try std.testing.expectEqualStrings("http://127.0.0.1:5199/cb", configured.redirect_uris[0]);
    try std.testing.expectEqualStrings("http://[::1]/cb", configured.redirect_uris[1]);

    try std.testing.expectError(error.InvalidLoopbackClientId, parseLoopbackClientId(allocator, "http://localhost?redirect_uri=https%3A%2F%2Fevil.example%2F"));
    try std.testing.expectError(error.InvalidLoopbackClientId, parseLoopbackClientId(allocator, "http://localhost?redirect_uri=http%3A%2F%2Flocalhost%3A5199%2F"));
    try std.testing.expectError(error.InvalidLoopbackClientId, parseLoopbackClientId(allocator, "http://localhost?scope=repo%3A*"));
    try std.testing.expectError(error.InvalidLoopbackClientId, parseLoopbackClientId(allocator, "http://localhost?scope=atproto&scope=atproto"));
    try std.testing.expectError(error.InvalidLoopbackClientId, parseLoopbackClientId(allocator, "http://localhost?client_name=x"));
    try std.testing.expectError(error.InvalidLoopbackClientId, parseLoopbackClientId(allocator, "http://localhost?scope=atproto#frag"));

    const document = try loopbackClientMetadata(allocator, "http://localhost?redirect_uri=http%3A%2F%2F127.0.0.1%2Fcb");
    defer document.deinit();
    const client = ClientMetadata{ .value = document.value };
    try std.testing.expect(client.redirectUriRegistered("http://127.0.0.1:61234/cb"));
    try std.testing.expect(!client.redirectUriRegistered("http://[::1]:61234/cb"));
    try std.testing.expectEqualStrings("atproto", client.registeredScope().?);
    try std.testing.expectEqualStrings("none", zat.json.getString(document.value, "token_endpoint_auth_method").?);
    try std.testing.expect(zat.json.getBool(document.value, "dpop_bound_access_tokens").?);
}

test "redirect_uri registration honours application_type for the loopback exception" {
    const native = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, "{\"application_type\":\"native\",\"redirect_uris\":[\"http://127.0.0.1/callback\",\"https://app.example/cb\"]}", .{});
    defer native.deinit();
    const native_client = ClientMetadata{ .value = native.value };
    try std.testing.expect(native_client.redirectUriRegistered("http://127.0.0.1:61234/callback"));
    try std.testing.expect(native_client.redirectUriRegistered("http://127.0.0.1/callback"));
    try std.testing.expect(native_client.redirectUriRegistered("https://app.example/cb"));
    try std.testing.expect(!native_client.redirectUriRegistered("https://app.example:8443/cb"));
    try std.testing.expect(!native_client.redirectUriRegistered("http://127.0.0.1:61234/elsewhere"));

    const web = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, "{\"redirect_uris\":[\"http://127.0.0.1/callback\"]}", .{});
    defer web.deinit();
    const web_client = ClientMetadata{ .value = web.value };
    try std.testing.expect(web_client.redirectUriRegistered("http://127.0.0.1/callback"));
    try std.testing.expect(!web_client.redirectUriRegistered("http://127.0.0.1:61234/callback"));
}

test "private_key_jwt clients may publish keys inline as jwks or by jwks_uri" {
    const allocator = std.testing.allocator;
    const inline_doc = try std.json.parseFromSlice(std.json.Value, allocator, "{\"jwks\":{\"keys\":[{\"kty\":\"EC\",\"crv\":\"P-256\",\"kid\":\"k1\",\"x\":\"meMgEL0CxvtJZgInPqXwHPPCczrXIuVhcaHCE1CXfy0\",\"y\":\"meMgEL0CxvtJZgInPqXwHPPCczrXIuVhcaHCE1CXfy0\"}]}}", .{});
    defer inline_doc.deinit();
    const inline_source = try clientJwksSource(inline_doc.value);
    try std.testing.expect(inline_source == .inline_keys);

    const uri_doc = try std.json.parseFromSlice(std.json.Value, allocator, "{\"jwks_uri\":\"https://client.example/jwks.json\"}", .{});
    defer uri_doc.deinit();
    try std.testing.expectEqualStrings("https://client.example/jwks.json", (try clientJwksSource(uri_doc.value)).uri);

    const both = try std.json.parseFromSlice(std.json.Value, allocator, "{\"jwks\":{\"keys\":[]},\"jwks_uri\":\"https://client.example/jwks.json\"}", .{});
    defer both.deinit();
    try std.testing.expectError(error.InvalidClientMetadata, clientJwksSource(both.value));

    const neither = try std.json.parseFromSlice(std.json.Value, allocator, "{\"token_endpoint_auth_method\":\"private_key_jwt\"}", .{});
    defer neither.deinit();
    try std.testing.expectError(error.InvalidClientMetadata, clientJwksSource(neither.value));
}

test "space scopes name one exact type" {
    try std.testing.expect(validSpaceScopeType(scope_rules.spaceScopeType("space:fm.plyr.privateMedia?action=read")));
    try std.testing.expect(validSpaceScopeType(scope_rules.spaceScopeType("space?spaceType=*")));
    try std.testing.expect(!validSpaceScopeType(scope_rules.spaceScopeType("space:fm.plyr.*")));
    try std.testing.expect(!validSpaceScopeType(scope_rules.spaceScopeType("space:fm.plyr.privateMedia?spaceType=fm.plyr.other")));
    try std.testing.expect(!validSpaceScopeType(scope_rules.spaceScopeType("space?action=read")));
}

test "a PKCE verifier matches only its S256 challenge" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
    try std.testing.expect(try pkceMatches(a, verifier, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"));
    try std.testing.expect(!try pkceMatches(a, verifier, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cN"));
    try std.testing.expect(!try pkceMatches(a, verifier, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-c"));
    try std.testing.expect(!try pkceMatches(a, "another-verifier-another-verifier-another-v", "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"));
}

test "token lifetimes follow the reference's public and confidential windows" {
    const start: i64 = 1_000_000;
    const fresh = tokenLifetime(false, start, start).?;
    try std.testing.expectEqual(start + access_token_expires_in, fresh.access_expires_at);
    try std.testing.expectEqual(start + 14 * day_seconds, fresh.refresh_expires_at);

    // a public session ends 14 days after it started, however often it refreshes
    const late_public = tokenLifetime(false, start, start + 14 * day_seconds - 5 * 60).?;
    try std.testing.expectEqual(start + 14 * day_seconds, late_public.refresh_expires_at);
    try std.testing.expectEqual(start + 14 * day_seconds, late_public.access_expires_at);
    try std.testing.expect(tokenLifetime(false, start, start + 14 * day_seconds) == null);

    // a confidential session slides by the inactivity window until two years
    const month_in = start + 30 * day_seconds;
    const confidential = tokenLifetime(true, start, month_in).?;
    try std.testing.expectEqual(month_in + confidential_refresh_idle, confidential.refresh_expires_at);
    const near_end = start + confidential_session_lifetime - day_seconds;
    try std.testing.expectEqual(start + confidential_session_lifetime, tokenLifetime(true, start, near_end).?.refresh_expires_at);
    try std.testing.expect(tokenLifetime(true, start, start + confidential_session_lifetime) == null);
}

test "only clients that authenticate are confidential" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const public = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"token_endpoint_auth_method\":\"none\"}", .{});
    const unspecified = try std.json.parseFromSliceLeaky(std.json.Value, a, "{}", .{});
    const confidential = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"token_endpoint_auth_method\":\"private_key_jwt\"}", .{});
    try std.testing.expect(!isConfidentialClient(public));
    try std.testing.expect(!isConfidentialClient(unspecified));
    try std.testing.expect(isConfidentialClient(confidential));
}

const httpz_testing = @import("httpz").testing;

fn refreshRaceFixture(a: std.mem.Allocator) !struct { account: auth.Account, loser_view: store.OAuthToken } {
    const account = try store.createAccount(a, "race.test", "race@test.com", "password", "did:plc:refreshrace", true);
    const t = now();
    try store.putOAuthToken(account.did, "https://client.example/client-metadata.json", "atproto", "access-one", "refresh-one", t + 600, t + 6000, "test-jkt", "password");
    // both requests read the row before either rotates
    const loser_view = (try store.getOAuthToken(a, "refresh-one")).?;
    try std.testing.expect(try store.rotateOAuthToken("refresh-one", "access-two", "refresh-two", t + 900, t + 6000, t + previous_refresh_grace_in));
    return .{ .account = account, .loser_view = loser_view };
}

test "a refresh that loses the rotation race answers with the winner's pair" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    try store.init(std.Options.debug_io, ":memory:");
    defer store.close();
    const fixture = try refreshRaceFixture(a);
    const view = fixture.loser_view;

    var ht = httpz_testing.init(.{});
    defer ht.deinit();
    http_api.bindResponse(ht.res);
    defer http_api.unbindResponse();
    try issueTokenResponse(ht.req, a, fixture.account, view.client_id, view.scope, view, false, view.dpop_jkt, view.auth_method);
    try ht.expectStatus(200);
    try std.testing.expect(std.mem.indexOf(u8, ht.res.body, "\"access_token\":\"access-two\"") != null);
    try std.testing.expect(std.mem.indexOf(u8, ht.res.body, "\"refresh_token\":\"refresh-two\"") != null);
    const current = (try store.getOAuthToken(a, "refresh-two")).?;
    try std.testing.expectEqual(store.OAuthToken.Kind.refresh, current.kind);
}

test "a lost rotation whose token has since been retired is invalid_grant" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    try store.init(std.Options.debug_io, ":memory:");
    defer store.close();
    const fixture = try refreshRaceFixture(a);
    const view = fixture.loser_view;
    const t = now();
    try std.testing.expect(try store.rotateOAuthToken("refresh-two", "access-three", "refresh-three", t + 900, t + 6000, t + previous_refresh_grace_in));

    var ht = httpz_testing.init(.{});
    defer ht.deinit();
    http_api.bindResponse(ht.res);
    defer http_api.unbindResponse();
    try std.testing.expectError(error.HandledResponse, issueTokenResponse(ht.req, a, fixture.account, view.client_id, view.scope, view, false, view.dpop_jkt, view.auth_method));
    try ht.expectStatus(400);
    try std.testing.expect(std.mem.indexOf(u8, ht.res.body, "\"error\":\"invalid_grant\"") != null);
    try std.testing.expect((try store.getOAuthToken(a, "refresh-three")).?.kind == .refresh);
}

test "a refresh past the session's absolute lifetime is invalid_grant" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    try store.init(std.Options.debug_io, ":memory:");
    defer store.close();
    const fixture = try refreshRaceFixture(a);
    var view = (try store.getOAuthToken(a, "refresh-two")).?;
    view.session_started_at = now() - public_session_lifetime;

    var ht = httpz_testing.init(.{});
    defer ht.deinit();
    http_api.bindResponse(ht.res);
    defer http_api.unbindResponse();
    try std.testing.expectError(error.HandledResponse, issueTokenResponse(ht.req, a, fixture.account, view.client_id, view.scope, view, false, view.dpop_jkt, view.auth_method));
    try ht.expectStatus(400);
    try std.testing.expect(std.mem.indexOf(u8, ht.res.body, "Session expired") != null);
    try std.testing.expect((try store.getOAuthToken(a, "refresh-two")).?.kind == .refresh);
}