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

zat.dev/zds

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

0
0
1808 lines · 92.2 KB Raw History
const std = @import("std");
const clock = @import("../core/clock.zig");
const auth = @import("../auth/tokens.zig");
const config = @import("../core/config.zig");
const log = @import("../core/log.zig");
const service_auth = @import("../internal/service_auth.zig");
const mail = @import("../core/mail.zig");
const plc = @import("plc.zig");
const sync = @import("sync.zig");
const http_api = @import("../http/api.zig");
const router = @import("../http/router.zig");
const email_tokens = @import("../internal/email_tokens.zig");
const handles = @import("../internal/handles.zig");
const scopes = @import("../internal/scopes.zig");
const store = @import("../storage/store.zig");
const zat = @import("zat");

const refresh_replay_grace_secs: i64 = 30;

const http = std.http;

pub fn describeServer(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const domains = try jsonStringArray(arena.allocator(), config.handleDomains());
    const body = try std.fmt.allocPrint(
        arena.allocator(),
        "{{\"did\":{f},\"availableUserDomains\":{s},\"inviteCodeRequired\":{}{s}}}",
        .{ std.json.fmt(config.serverDid(), .{}), domains, config.inviteRequired(), if (config.permissionedData()) ",\"spacesAlpha\":true" else "" },
    );
    return http_api.json(request, .ok, body);
}

/// community.lexicon.service.describe is an unratified lexicon pioneered by
/// bulleted/atpint for capability discovery; the bodies are generated from the
/// route table so the advertisement always matches what actually routes.
pub fn serviceDescribe(request: *http_api.Request) !void {
    const body = if (config.permissionedData())
        comptime serviceDescribeBody(true)
    else
        comptime serviceDescribeBody(false);
    return http_api.json(request, .ok, body);
}

fn serviceDescribeBody(comptime include_permissioned: bool) []const u8 {
    comptime {
        @setEvalBranchQuota(1_000_000);
        var body: []const u8 = "{\"roles\":[\"pds\"],\"methods\":[";
        var seen: []const []const u8 = &.{};
        for (router.endpoints) |endpoint| {
            const nsid = endpoint.nsid() orelse continue;
            if (nsid[0] == '_') continue;
            if (!include_permissioned and endpoint.route == .permissioned_data) continue;
            var duplicate = false;
            for (seen) |prior| {
                if (std.mem.eql(u8, prior, nsid)) duplicate = true;
            }
            if (duplicate) continue;
            if (seen.len != 0) body = body ++ ",";
            seen = seen ++ &[_][]const u8{nsid};
            body = body ++ "{\"$type\":\"community.lexicon.service.describe#nsid\",\"value\":\"" ++ nsid ++ "\"}";
        }
        return body ++ "]}";
    }
}

test "serviceDescribeBody reflects the permissioned-data flag" {
    const with_spaces = comptime serviceDescribeBody(true);
    const without_spaces = comptime serviceDescribeBody(false);
    try std.testing.expect(std.mem.indexOf(u8, with_spaces, "\"community.lexicon.service.describe\"") != null);
    try std.testing.expect(std.mem.indexOf(u8, without_spaces, "\"community.lexicon.service.describe\"") != null);
    try std.testing.expect(std.mem.indexOf(u8, with_spaces, "\"com.atproto.space.getSpace\"") != null);
    try std.testing.expect(std.mem.indexOf(u8, with_spaces, "\"com.atproto.space.getLatestCommit\"") != null);
    try std.testing.expect(std.mem.indexOf(u8, without_spaces, "com.atproto.space.") == null);
    try std.testing.expect(std.mem.indexOf(u8, without_spaces, "com.atproto.simplespace.") == null);
    try std.testing.expect(std.mem.indexOf(u8, without_spaces, "_health") == null);
    // each nsid appears once even when GET/HEAD share a path
    const first = std.mem.indexOf(u8, with_spaces, "\"com.atproto.sync.getBlob\"").?;
    try std.testing.expect(std.mem.indexOfPos(u8, with_spaces, first + 1, "\"com.atproto.sync.getBlob\"") == null);
    const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, with_spaces, .{});
    defer parsed.deinit();
    try std.testing.expectEqualStrings("pds", parsed.value.object.get("roles").?.array.items[0].string);
}

pub fn didJson(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const body = try std.fmt.allocPrint(
        arena.allocator(),
        "{{\"@context\":[\"https://www.w3.org/ns/did/v1\"],\"id\":{f},\"service\":[{{\"id\":\"#atproto_pds\",\"type\":\"AtprotoPersonalDataServer\",\"serviceEndpoint\":{f}}}]}}",
        .{ std.json.fmt(config.serverDid(), .{}), std.json.fmt(config.publicUrl(), .{}) },
    );
    return http_api.json(request, .ok, body);
}

pub fn atprotoDid(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const host = requestHost(request) orelse {
        return plain(request, .not_found, "User not found");
    };
    const handle = handles.normalize(allocator, stripPort(host)) catch {
        return plain(request, .not_found, "User not found");
    };
    if (!handles.isHosted(handle, config.handleDomains())) {
        return plain(request, .not_found, "User not found");
    }
    const account = store.findActiveAccount(allocator, handle) catch null orelse {
        return plain(request, .not_found, "User not found");
    };
    return plain(request, .ok, account.did);
}

pub fn reserveSigningKey(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const body = try http_api.readBodyAlloc(request, allocator, 16 * 1024);
    const did = if (body.len == 0) null else did: {
        const parsed = try http_api.parseJsonBody(request, allocator, body);
        break :did zat.json.getString(parsed.value, "did");
    };
    if (did) |value| {
        if (zat.Did.parse(value) == null) {
            return http_api.xrpcError(request, .bad_request, "InvalidDid", "invalid did");
        }
    }
    const reserved = try store.reserveSigningKey(allocator, did);
    const body_out = try std.fmt.allocPrint(allocator, "{{\"signingKey\":{f}}}", .{std.json.fmt(reserved.signing_key, .{})});
    return http_api.json(request, .ok, body_out);
}

pub fn createAccount(request: *http_api.Request) !void {
    const authorization = http_api.headerValue(request, "authorization");

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

    const body = try http_api.readBodyAlloc(request, allocator, 1024 * 1024);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const raw_handle = zat.json.getString(parsed.value, "handle") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing handle");
    };
    const handle = handles.normalize(allocator, raw_handle) catch {
        return http_api.xrpcError(request, .bad_request, "InvalidHandle", "invalid handle");
    };
    const email = zat.json.getString(parsed.value, "email") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing email");
    };
    const password = zat.json.getString(parsed.value, "password") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing password");
    };
    if (!isValidEmail(email)) {
        return http_api.xrpcError(request, .bad_request, "InvalidEmail", "invalid email");
    }
    const invite_code = zat.json.getString(parsed.value, "inviteCode");
    if (invite_code) |code| {
        if (!(store.inviteCodeIsAvailable(code) catch false)) {
            return http_api.xrpcError(request, .bad_request, "InvalidInviteCode", "Provided invite code not available");
        }
    } else if (config.inviteRequired()) {
        return http_api.xrpcError(request, .bad_request, "InvalidInviteCode", "No invite code provided");
    }

    const existing_did = zat.json.getString(parsed.value, "did");
    if (handles.isHosted(handle, config.handleDomains())) {
        handles.validateHosted(handle, config.handleDomains()) catch |err| {
            return http_api.xrpcError(request, .bad_request, "InvalidHandle", switch (err) {
                error.ReservedHandle => "reserved hosted handle",
                else => "invalid hosted handle",
            });
        };
    } else if (existing_did) |did| {
        var resolver = zat.HandleResolver.init(store.currentIo(), allocator);
        defer resolver.deinit();
        const resolved_did = resolver.resolve(zat.Handle.parse(handle).?) catch {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "External handle did not resolve to account DID");
        };
        if (!std.mem.eql(u8, resolved_did, did)) {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "External handle did not resolve to account DID");
        }
    } else {
        return http_api.xrpcError(request, .bad_request, "UnsupportedDomain", "not a supported handle domain");
    }
    const plc_op = jsonObjectField(parsed.value, "plcOp");
    const signing_key_input = zat.json.getString(parsed.value, "signingKey");
    const account = if (existing_did) |did| account: {
        if (zat.Did.parse(did) == null) {
            log.debug("xrpc createAccount rejected invalid_did did={s} handle={s}\n", .{ did, handle });
            return http_api.xrpcError(request, .bad_request, "InvalidDid", "invalid did");
        }
        log.debug("xrpc createAccount migration attempt did={s} handle={s}\n", .{ did, handle });
        const signing_key = if (plc_op) |operation| key: {
            const expected_key = signing_key_input orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "signingKey is required when plcOp is provided");
            try validateCreateAccountPlcOperation(request, allocator, handle, operation, expected_key);
            const reserved_key = store.consumeReservedSigningKey(expected_key, did) catch |err| switch (err) {
                error.MissingReservedSigningKey => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "reserved signing key does not exist"),
                else => return err,
            };
            break :key reserved_key;
        } else key: {
            try verifyCreateAccountServiceAuth(request, allocator, authorization, did);
            break :key try store.generateAccountSigningKey();
        };
        // A caller-built PLC operation cannot carry a KEM key it has never seen,
        // so that account is left for the backfill to key and publish.
        const kem_key = if (plc_op == null) try store.generateKemSecretKey() else null;
        break :account store.createAccountWithSigningKeyAndInvite(allocator, handle, email, password, did, plc_op != null, signing_key, kem_key, invite_code) catch |err| switch (err) {
            error.InvalidInviteCode => return http_api.xrpcError(request, .bad_request, "InvalidInviteCode", "Provided invite code not available"),
            else => {
                log.debug("xrpc createAccount rejected account_exists_or_store_error did={s} handle={s}\n", .{ did, handle });
                return http_api.xrpcError(request, .bad_request, "InvalidRequest", "account already exists");
            },
        };
    } else account: {
        log.debug("xrpc createAccount genesis attempt handle={s}\n", .{handle});
        const signing_key = store.generateAccountSigningKey() catch {
            log.err("xrpc createAccount failed signing_key handle={s}\n", .{handle});
            return http_api.xrpcError(request, .internal_server_error, "InternalServerError", "failed to generate account signing key");
        };
        const keypair = zat.Keypair.fromSecretKey(.secp256k1, signing_key) catch {
            log.err("xrpc createAccount failed signing_key_parse handle={s}\n", .{handle});
            return http_api.xrpcError(request, .internal_server_error, "InternalServerError", "failed to prepare account signing key");
        };
        var rotation_keypair = plc.configuredRotationKeypair() catch |err| switch (err) {
            error.MissingPlcRotationKey => return http_api.xrpcError(request, .internal_server_error, "InternalServerError", "PLC rotation key is not configured"),
            error.InvalidPlcRotationKey => return http_api.xrpcError(request, .internal_server_error, "InternalServerError", "PLC rotation key is invalid"),
        };
        const kem_key = try store.generateKemSecretKey();
        const kem_keypair = try zat.Keypair.fromSecretKey(.p256, kem_key);
        const operation = plc.createGenesisOperation(allocator, handle, &keypair, &kem_keypair, &rotation_keypair) catch {
            log.err("xrpc createAccount failed plc_operation handle={s}\n", .{handle});
            return http_api.xrpcError(request, .internal_server_error, "InternalServerError", "failed to create DID operation");
        };
        plc.submitOperation(allocator, operation.did, operation.json, .genesis) catch {
            log.err("xrpc createAccount failed plc_submit did={s} handle={s}\n", .{ operation.did, handle });
            return http_api.xrpcError(request, .bad_gateway, "PlcSubmissionFailed", "PLC directory rejected account DID operation");
        };
        break :account store.createAccountWithSigningKeyAndInvite(allocator, handle, email, password, operation.did, true, signing_key, kem_key, invite_code) catch |err| switch (err) {
            error.InvalidInviteCode => return http_api.xrpcError(request, .bad_request, "InvalidInviteCode", "Provided invite code not available"),
            else => {
                log.debug("xrpc createAccount rejected account_exists_or_store_error did={s} handle={s}\n", .{ operation.did, handle });
                return http_api.xrpcError(request, .bad_request, "InvalidRequest", "account already exists");
            },
        };
    };
    log.debug("xrpc createAccount ok did={s} handle={s}\n", .{ account.did, account.handle });
    if (existing_did == null) {
        store.sequenceNewAccount(allocator, account) catch |err| {
            log.err("xrpc createAccount failed sequence_new_account did={s} err={s}\n", .{ account.did, @errorName(err) });
        };
        sync.notifyCrawlers(true);
    } else {
        try store.initializeRepo(allocator, account);
    }

    const issued = try issueSessionTokens(allocator, account, "account_create", null);
    const body_out = try sessionJson(allocator, account, issued.access.token, issued.refresh.token);
    try http_api.json(request, .ok, body_out);
}

pub fn createInviteCode(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    requireAdminToken(request) catch return;
    var body_buf: [4096]u8 = undefined;
    const body = try http_api.readBody(request, &body_buf);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const use_count = jsonInt(parsed.value, "useCount") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing useCount");
    };
    const for_account = zat.json.getString(parsed.value, "forAccount") orelse "admin";
    const code = store.createInviteCode(allocator, config.publicUrl(), use_count, for_account, "admin") catch |err| switch (err) {
        error.InvalidUseCount => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "useCount must be greater than zero"),
        else => return err,
    };
    const body_out = try std.fmt.allocPrint(allocator, "{{\"code\":{f}}}", .{std.json.fmt(code, .{})});
    return http_api.json(request, .ok, body_out);
}

pub fn createInviteCodes(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    requireAdminToken(request) catch return;
    var body_buf: [8192]u8 = undefined;
    const body = try http_api.readBody(request, &body_buf);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const use_count = jsonInt(parsed.value, "useCount") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing useCount");
    };
    const code_count = jsonInt(parsed.value, "codeCount") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing codeCount");
    };

    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeAll("{\"codes\":[");
    if (jsonStringArrayValue(allocator, parsed.value, "forAccounts") catch |err| switch (err) {
        error.InvalidJsonStringArray => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "forAccounts must be an array of strings"),
        else => return err,
    }) |accounts| {
        if (accounts.len == 0) {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "forAccounts must not be empty");
        }
        for (accounts, 0..) |for_account, idx| {
            if (idx != 0) try out.writer.writeByte(',');
            writeInviteCodeGroup(allocator, &out.writer, for_account, code_count, use_count, "admin") catch |err| switch (err) {
                error.InvalidInviteInput => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "codeCount and useCount must be greater than zero"),
                else => return err,
            };
        }
    } else {
        writeInviteCodeGroup(allocator, &out.writer, "admin", code_count, use_count, "admin") catch |err| switch (err) {
            error.InvalidInviteInput => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "codeCount and useCount must be greater than zero"),
            else => return err,
        };
    }
    try out.writer.writeAll("]}");
    return http_api.json(request, .ok, try out.toOwnedSlice());
}

pub fn getAccountInviteCodes(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const account = requireAccount(request, allocator) catch return;
    try http_api.requireActiveAccount(request, account.did, .takedown);
    var include_buf: [8]u8 = undefined;
    const include_used = if (http_api.queryParam(request.url.raw, "includeUsed", &include_buf)) |value|
        std.ascii.eqlIgnoreCase(value, "true")
    else
        true;
    const codes = try store.getAccountInviteCodes(allocator, account.did, include_used);

    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeAll("{\"codes\":[");
    for (codes, 0..) |code, idx| {
        if (idx != 0) try out.writer.writeByte(',');
        try writeInviteCodeJson(allocator, &out.writer, code);
    }
    try out.writer.writeAll("]}");
    return http_api.json(request, .ok, try out.toOwnedSlice());
}

pub fn listAppPasswords(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireAccountAccess(request, allocator) catch return;
    try requirePasswordSession(request, allocator, auth_ctx.account.did);
    const passwords = try store.listAppPasswords(allocator, auth_ctx.account.did);
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeAll("{\"passwords\":[");
    for (passwords, 0..) |password, idx| {
        if (idx != 0) try out.writer.writeByte(',');
        const created_at = try clock.isoMillis(allocator, password.created_at);
        try out.writer.print(
            "{{\"name\":{f},\"createdAt\":{f},\"privileged\":{}}}",
            .{ std.json.fmt(password.name, .{}), std.json.fmt(created_at, .{}), password.privileged },
        );
    }
    try out.writer.writeAll("]}");
    return http_api.json(request, .ok, try out.toOwnedSlice());
}

pub fn listAccountAccess(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireAccountAccess(request, allocator) catch return;
    try requirePasswordSession(request, allocator, auth_ctx.account.did);
    var kind_buf: [32]u8 = undefined;
    var state_buf: [32]u8 = undefined;
    var group_buf: [4096]u8 = undefined;
    var search_buf: [1024]u8 = undefined;
    var cursor_buf: [32]u8 = undefined;
    var limit_buf: [32]u8 = undefined;
    var query: store.AccessQuery = .{};
    const kind = http_api.queryParam(request.url.raw, "kind", &kind_buf) orelse "oauth";
    query.kind = std.meta.stringToEnum(@TypeOf(query.kind), kind) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "kind must be oauth or password");
    const state = http_api.queryParam(request.url.raw, "state", &state_buf) orelse "authorized";
    query.state = std.meta.stringToEnum(@TypeOf(query.state), state) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "state must be authorized, past, or all");
    query.group = http_api.queryParam(request.url.raw, "group", &group_buf);
    query.search = http_api.queryParam(request.url.raw, "search", &search_buf) orelse "";
    if (http_api.queryParam(request.url.raw, "cursor", &cursor_buf)) |value| {
        query.offset = std.fmt.parseInt(i64, value, 10) catch return http_api.xrpcError(request, .bad_request, "InvalidRequest", "invalid cursor");
        if (query.offset < 0 or query.offset > std.math.maxInt(i64) - 100) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "invalid cursor");
    }
    if (http_api.queryParam(request.url.raw, "limit", &limit_buf)) |value| {
        query.limit = std.fmt.parseInt(i64, value, 10) catch return http_api.xrpcError(request, .bad_request, "InvalidRequest", "invalid limit");
        if (query.limit < 1 or query.limit > 100) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "limit must be 1 through 100");
    }
    const page = try store.listAccountAccess(allocator, auth_ctx.account.did, query);
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.print("{{\"authorized\":{d},\"total\":{d},\"cursor\":", .{ page.authorized, page.total });
    if (page.next) |next| try out.writer.print("\"{d}\"", .{next}) else try out.writer.writeAll("null");
    try out.writer.writeAll(",\"groups\":[");
    for (page.groups, 0..) |group, index| {
        if (index != 0) try out.writer.writeByte(',');
        try out.writer.print("{{\"key\":{f},\"name\":{f},\"count\":{d},\"newest\":{f}}}", .{ std.json.fmt(group.key, .{}), std.json.fmt(group.name, .{}), group.count, std.json.fmt(try clock.isoMillis(allocator, group.newest), .{}) });
    }
    try out.writer.writeAll("],\"connections\":[");
    for (page.grants, 0..) |grant, index| {
        if (index != 0) try out.writer.writeByte(',');
        try writeOAuthGrantJson(allocator, &out.writer, grant);
    }
    for (page.sessions, 0..) |session, index| {
        if (index != 0) try out.writer.writeByte(',');
        try writeSessionJson(allocator, &out.writer, session);
    }
    try out.writer.writeAll("]}");
    return http_api.json(request, .ok, try out.toOwnedSlice());
}

pub fn listSessions(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireAccountAccess(request, allocator) catch return;
    try requirePasswordSession(request, allocator, auth_ctx.account.did);
    const options = sessionListOptions(request);
    const sessions = try store.listSessionsForAccount(allocator, auth_ctx.account.did, options.active_only, options.limit);
    const grants = try store.listOAuthGrantsForAccount(allocator, auth_ctx.account.did, options.active_only, options.limit);
    const body = try sessionsJson(allocator, sessions, grants);
    return http_api.json(request, .ok, body);
}

pub fn adminListSessions(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    requireAdminToken(request) catch return;
    const options = sessionListOptions(request);
    const sessions = try store.listSessionsForAllAccounts(allocator, options.active_only, options.limit);
    const grants = try store.listOAuthGrantsForAllAccounts(allocator, options.active_only, options.limit);
    const body = try sessionsJson(allocator, sessions, grants);
    return http_api.json(request, .ok, body);
}

/// Mail the outbox provider kept, newest first: how a test or eval harness
/// reads the codes this PDS would have emailed.
pub fn adminListMail(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    requireAdminToken(request) catch return;
    var to_buf: [512]u8 = undefined;
    const to = http_api.queryParam(request.url.raw, "to", &to_buf);
    const messages = try store.listOutboxMail(allocator, to, http_api.queryLimit(request.url.raw, 50));
    var out: std.Io.Writer.Allocating = .init(allocator);
    try out.writer.writeAll("{\"messages\":[");
    for (messages, 0..) |message, idx| {
        if (idx != 0) try out.writer.writeByte(',');
        try out.writer.print("{{\"id\":{d},\"to\":{f},\"subject\":{f},\"text\":{f},\"createdAt\":{f}", .{
            message.id,
            std.json.fmt(message.to, .{}),
            std.json.fmt(message.subject, .{}),
            std.json.fmt(message.text, .{}),
            std.json.fmt(try clock.isoMillis(allocator, message.created_at), .{}),
        });
        if (message.code) |code| try out.writer.print(",\"code\":{f}", .{std.json.fmt(code, .{})});
        try out.writer.writeByte('}');
    }
    try out.writer.writeAll("]}");
    return http_api.json(request, .ok, out.written());
}

pub fn createAppPassword(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireAccountAccess(request, allocator) catch return;
    try http_api.requireActiveAccount(request, auth_ctx.account.did, .takedown);
    try requirePasswordSession(request, allocator, auth_ctx.account.did);

    const body = try http_api.readBodyAlloc(request, allocator, 16 * 1024);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const raw_name = zat.json.getString(parsed.value, "name") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "name is required");
    };
    const name = std.mem.trim(u8, raw_name, " \t\r\n");
    if (name.len == 0) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "name is required");
    }
    if (try store.getAppPasswordByName(allocator, auth_ctx.account.did, name) != null) {
        return http_api.xrpcError(request, .bad_request, "DuplicateAppPassword", "An app password with this name already exists");
    }
    const privileged = jsonBool(parsed.value, "privileged") orelse false;
    const app_password = try generateAppPassword(allocator);
    var salt: [16]u8 = undefined;
    store.randomBytes(&salt);
    const password_hash = try auth.hashPassword(allocator, app_password, salt);
    const app_password_scopes: []const u8 = if (privileged) "transition:generic transition:chat.bsky" else "transition:generic";
    const row = try store.createAppPassword(allocator, auth_ctx.account.did, name, password_hash, privileged, app_password_scopes, null);
    try store.recordAuditEvent(auth_ctx.account.did, auth_ctx.account.did, null, "app_password_created", "{}");
    const created_at = try clock.isoMillis(allocator, row.created_at);
    const body_out = try std.fmt.allocPrint(
        allocator,
        "{{\"name\":{f},\"password\":{f},\"createdAt\":{f},\"privileged\":{}}}",
        .{ std.json.fmt(row.name, .{}), std.json.fmt(app_password, .{}), std.json.fmt(created_at, .{}), row.privileged },
    );
    return http_api.json(request, .ok, body_out);
}

pub fn revokeAppPassword(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireAccountAccess(request, allocator) catch return;
    try requirePasswordSession(request, allocator, auth_ctx.account.did);

    const body = try http_api.readBodyAlloc(request, allocator, 16 * 1024);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const raw_name = zat.json.getString(parsed.value, "name") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "name is required");
    };
    const name = std.mem.trim(u8, raw_name, " \t\r\n");
    if (name.len == 0) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "name is required");
    }
    try store.revokeAppPassword(auth_ctx.account.did, name);
    try store.recordAuditEvent(auth_ctx.account.did, auth_ctx.account.did, null, "app_password_revoked", "{}");
    return http_api.json(request, .ok, "{}");
}

/// Ends every grant the signed-in account gave one OAuth client. Like the
/// other resident credential controls, it takes a password session, so an
/// OAuth app cannot use it to remove its rivals.
pub fn revokeAccountApp(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireAccountAccess(request, allocator) catch return;
    try requirePasswordSession(request, allocator, auth_ctx.account.did);

    const body = try http_api.readBodyAlloc(request, allocator, 16 * 1024);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const client_id = zat.json.getString(parsed.value, "clientId") orelse "";
    if (client_id.len == 0) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "clientId is required");
    }
    const revoked = try store.revokeOAuthClient(auth_ctx.account.did, client_id);
    if (revoked != 0) try store.recordAuditEvent(auth_ctx.account.did, auth_ctx.account.did, null, "oauth_client_revoked", "{}");
    return http_api.json(request, .ok, try std.fmt.allocPrint(allocator, "{{\"revoked\":{d}}}", .{revoked}));
}

fn jsonStringArray(allocator: std.mem.Allocator, raw: []const u8) ![]const u8 {
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeByte('[');
    var parts = std.mem.splitScalar(u8, raw, ',');
    var index: usize = 0;
    while (parts.next()) |part| {
        const trimmed = std.mem.trim(u8, part, " \t\r\n");
        if (trimmed.len == 0) continue;
        if (index != 0) try out.writer.writeByte(',');
        try out.writer.print("{f}", .{std.json.fmt(trimmed, .{})});
        index += 1;
    }
    try out.writer.writeByte(']');
    return out.toOwnedSlice();
}

fn jsonStringArrayValue(allocator: std.mem.Allocator, value: std.json.Value, key: []const u8) !?[][]const u8 {
    if (value != .object) return null;
    const raw = value.object.get(key) orelse return null;
    if (raw != .array) return error.InvalidJsonStringArray;
    var out: std.ArrayList([]const u8) = .empty;
    for (raw.array.items) |item| {
        if (item != .string) return error.InvalidJsonStringArray;
        try out.append(allocator, item.string);
    }
    return try out.toOwnedSlice(allocator);
}

fn jsonInt(value: std.json.Value, key: []const u8) ?i64 {
    if (value != .object) return null;
    const raw = value.object.get(key) orelse return null;
    return switch (raw) {
        .integer => |n| n,
        else => null,
    };
}

fn jsonBool(value: std.json.Value, key: []const u8) ?bool {
    if (value != .object) return null;
    const raw = value.object.get(key) orelse return null;
    return switch (raw) {
        .bool => |n| n,
        else => null,
    };
}

fn jsonObjectField(value: std.json.Value, key: []const u8) ?std.json.Value {
    return switch (value) {
        .object => |object| object.get(key),
        else => null,
    };
}

fn validateCreateAccountPlcOperation(
    request: *http_api.Request,
    allocator: std.mem.Allocator,
    handle: []const u8,
    operation: std.json.Value,
    signing_did_key: []const u8,
) !void {
    const object = switch (operation) {
        .object => |object| object,
        else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "invalid plc operation"),
    };
    if (!jsonObjectStringEquals(operation, "type", "plc_operation")) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "invalid plc operation type");
    }
    if (!jsonObjectStringEquals(object.get("verificationMethods") orelse .null, "atproto", signing_did_key)) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "PLC operation does not use reserved signing key");
    }
    var rotation_keypair = plc.configuredRotationKeypair() catch |err| switch (err) {
        error.MissingPlcRotationKey => return http_api.xrpcError(request, .internal_server_error, "InternalServerError", "PLC rotation key is not configured"),
        error.InvalidPlcRotationKey => return http_api.xrpcError(request, .internal_server_error, "InternalServerError", "PLC rotation key is invalid"),
    };
    const server_rotation_key = try rotation_keypair.did(allocator);
    if (!jsonArrayContainsString(object.get("rotationKeys"), server_rotation_key)) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "PLC operation does not include server rotation key");
    }
    if (jsonArrayContainsString(object.get("rotationKeys"), signing_did_key)) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "PLC operation must not include reserved signing key as a rotation key");
    }
    const also_known_as = try std.fmt.allocPrint(allocator, "at://{s}", .{handle});
    if (!jsonArrayFirstStringEquals(object.get("alsoKnownAs"), also_known_as)) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "PLC operation handle does not match account handle");
    }
    const services = object.get("services") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "PLC operation missing services");
    };
    const atproto_pds = switch (services) {
        .object => |services_object| services_object.get("atproto_pds") orelse {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "PLC operation missing atproto_pds service");
        },
        else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "PLC operation services must be an object"),
    };
    if (!jsonObjectStringEquals(atproto_pds, "type", "AtprotoPersonalDataServer") or
        !jsonObjectStringEquals(atproto_pds, "endpoint", config.publicUrl()))
    {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "PLC operation service does not match this PDS");
    }
}

fn jsonObjectStringEquals(value: std.json.Value, key: []const u8, expected: []const u8) bool {
    return switch (value) {
        .object => |object| switch (object.get(key) orelse return false) {
            .string => |string| std.mem.eql(u8, string, expected),
            else => false,
        },
        else => false,
    };
}

fn jsonArrayContainsString(value: ?std.json.Value, expected: []const u8) bool {
    const items = switch (value orelse return false) {
        .array => |array| array.items,
        else => return false,
    };
    for (items) |item| switch (item) {
        .string => |string| if (std.mem.eql(u8, string, expected)) return true,
        else => {},
    };
    return false;
}

fn jsonArrayFirstStringEquals(value: ?std.json.Value, expected: []const u8) bool {
    const items = switch (value orelse return false) {
        .array => |array| array.items,
        else => return false,
    };
    if (items.len == 0) return false;
    return switch (items[0]) {
        .string => |string| std.mem.eql(u8, string, expected),
        else => false,
    };
}

fn writeInviteCodeGroup(allocator: std.mem.Allocator, writer: anytype, for_account: []const u8, code_count: i64, use_count: i64, created_by: []const u8) !void {
    const codes = store.createInviteCodes(allocator, config.publicUrl(), code_count, use_count, for_account, created_by) catch |err| switch (err) {
        error.InvalidUseCount => return error.InvalidInviteInput,
        else => return err,
    };
    try writer.print("{{\"account\":{f},\"codes\":[", .{std.json.fmt(for_account, .{})});
    for (codes, 0..) |code, idx| {
        if (idx != 0) try writer.writeByte(',');
        try writer.print("{f}", .{std.json.fmt(code, .{})});
    }
    try writer.writeAll("]}");
}

fn writeInviteCodeJson(allocator: std.mem.Allocator, writer: anytype, code: store.InviteCode) !void {
    const created_at = try clock.isoMillis(allocator, code.created_at);
    try writer.print(
        "{{\"code\":{f},\"available\":{d},\"disabled\":{},\"forAccount\":{f},\"createdBy\":{f},\"createdAt\":{f},\"uses\":[",
        .{
            std.json.fmt(code.code, .{}),
            code.available,
            code.disabled,
            std.json.fmt(code.for_account, .{}),
            std.json.fmt(code.created_by, .{}),
            std.json.fmt(created_at, .{}),
        },
    );
    for (code.uses, 0..) |use, idx| {
        if (idx != 0) try writer.writeByte(',');
        const used_at = try clock.isoMillis(allocator, use.used_at);
        try writer.print("{{\"usedBy\":{f},\"usedAt\":{f}}}", .{ std.json.fmt(use.used_by, .{}), std.json.fmt(used_at, .{}) });
    }
    try writer.writeAll("]}");
}

const SessionListOptions = struct {
    active_only: bool = true,
    limit: i64 = 100,
};

fn sessionListOptions(request: *http_api.Request) SessionListOptions {
    var active_buf: [16]u8 = undefined;
    const active_only = if (http_api.queryParam(request.url.raw, "active", &active_buf)) |value|
        !(std.mem.eql(u8, value, "false") or std.mem.eql(u8, value, "0"))
    else
        true;
    var limit_buf: [16]u8 = undefined;
    const parsed_limit = if (http_api.queryParam(request.url.raw, "limit", &limit_buf)) |value|
        std.fmt.parseInt(i64, value, 10) catch 100
    else
        100;
    return .{ .active_only = active_only, .limit = std.math.clamp(parsed_limit, 1, 500) };
}

fn sessionsJson(allocator: std.mem.Allocator, sessions: []const store.SessionInfo, grants: []const store.OAuthGrantInfo) ![]const u8 {
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeAll("{\"sessions\":[");
    for (sessions, 0..) |session, idx| {
        if (idx != 0) try out.writer.writeByte(',');
        try writeSessionJson(allocator, &out.writer, session);
    }
    try out.writer.writeAll("],\"oauthGrants\":[");
    for (grants, 0..) |grant, idx| {
        if (idx != 0) try out.writer.writeByte(',');
        try writeOAuthGrantJson(allocator, &out.writer, grant);
    }
    try out.writer.writeAll("]}");
    return out.toOwnedSlice();
}

fn writeSessionJson(allocator: std.mem.Allocator, writer: anytype, session: store.SessionInfo) !void {
    const created_at = try clock.isoMillis(allocator, session.created_at);
    const updated_at = try clock.isoMillis(allocator, session.updated_at);
    const access_expires_at = try clock.isoMillis(allocator, session.access_expires_at);
    const refresh_expires_at = try clock.isoMillis(allocator, session.refresh_expires_at);
    try writer.print(
        "{{\"id\":{f},\"did\":{f},\"handle\":{f},\"authMethod\":{f},\"appPasswordName\":",
        .{
            std.json.fmt(session.id, .{}),
            std.json.fmt(session.did, .{}),
            std.json.fmt(session.handle, .{}),
            std.json.fmt(session.auth_method, .{}),
        },
    );
    try writeOptionalString(writer, session.app_password_name);
    try writer.writeAll(",\"controllerDid\":");
    try writeOptionalString(writer, session.controller_did);
    try writer.print(
        ",\"createdAt\":{f},\"updatedAt\":{f},\"lastUsedAt\":",
        .{ std.json.fmt(created_at, .{}), std.json.fmt(updated_at, .{}) },
    );
    try writeOptionalTimestamp(allocator, writer, session.last_used_at);
    try writer.print(
        ",\"accessExpiresAt\":{f},\"refreshExpiresAt\":{f},\"revokedAt\":",
        .{ std.json.fmt(access_expires_at, .{}), std.json.fmt(refresh_expires_at, .{}) },
    );
    try writeOptionalTimestamp(allocator, writer, session.revoked_at);
    try writer.print(",\"active\":{}}}", .{session.active});
}

fn writeOAuthGrantJson(allocator: std.mem.Allocator, writer: anytype, grant: store.OAuthGrantInfo) !void {
    const created_at = try clock.isoMillis(allocator, grant.created_at);
    const expires_at = try clock.isoMillis(allocator, grant.expires_at);
    try writer.print(
        "{{\"did\":{f},\"handle\":{f},\"clientId\":{f},\"scope\":{f},\"createdAt\":{f},\"expiresAt\":{f},\"authMethod\":",
        .{
            std.json.fmt(grant.did, .{}),
            std.json.fmt(grant.handle, .{}),
            std.json.fmt(grant.client_id, .{}),
            std.json.fmt(grant.scope, .{}),
            std.json.fmt(created_at, .{}),
            std.json.fmt(expires_at, .{}),
        },
    );
    try writeOptionalString(writer, grant.auth_method);
    try writer.writeAll(",\"revokedAt\":");
    try writeOptionalTimestamp(allocator, writer, grant.revoked_at);
    try writer.print(",\"active\":{}}}", .{grant.active});
}

fn writeOptionalString(writer: anytype, value: ?[]const u8) !void {
    if (value) |text| {
        try writer.print("{f}", .{std.json.fmt(text, .{})});
    } else {
        try writer.writeAll("null");
    }
}

fn writeOptionalTimestamp(allocator: std.mem.Allocator, writer: anytype, value: ?i64) !void {
    if (value) |seconds| {
        const text = try clock.isoMillis(allocator, seconds);
        try writer.print("{f}", .{std.json.fmt(text, .{})});
    } else {
        try writer.writeAll("null");
    }
}

fn requestHost(request: *const http_api.Request) ?[]const u8 {
    return http_api.headerValue(request, "host") orelse http_api.headerValue(request, ":authority");
}

fn stripPort(host: []const u8) []const u8 {
    if (std.mem.startsWith(u8, host, "[")) return host;
    if (std.mem.lastIndexOfScalar(u8, host, ':')) |idx| return host[0..idx];
    return host;
}

fn plain(request: *http_api.Request, status: http.Status, body: []const u8) !void {
    try http_api.respond(request, status, body, &plain_headers);
}

const plain_headers = [_]http.Header{
    .{ .name = "content-type", .value = "text/plain; charset=utf-8" },
    .{ .name = "access-control-allow-origin", .value = "*" },
    .{ .name = "connection", .value = "close" },
};

fn verifyCreateAccountServiceAuth(request: *http_api.Request, allocator: std.mem.Allocator, maybe_authorization: ?[]const u8, did: []const u8) !void {
    const raw_header = maybe_authorization orelse {
        log.debug("xrpc createAccount service_auth missing did={s}\n", .{did});
        return http_api.xrpcError(request, .unauthorized, "AuthenticationRequired", "service auth required to migrate an existing did");
    };
    if (!std.ascii.startsWithIgnoreCase(raw_header, "bearer ")) {
        log.debug("xrpc createAccount service_auth malformed did={s}\n", .{did});
        return http_api.xrpcError(request, .unauthorized, "AuthenticationRequired", "service auth required to migrate an existing did");
    }
    const token = std.mem.trim(u8, raw_header["bearer ".len..], " \t");
    var arena = std.heap.ArenaAllocator.init(allocator);
    defer arena.deinit();
    _ = zat.service_auth.verify(arena.allocator(), token, .{
        .now = clock.nowSeconds(),
        .audiences = &.{config.serverDid()},
        .lxm = "com.atproto.server.createAccount",
        .issuer = did,
    }, service_auth.KeyResolver{}) catch |err| {
        log.debug("xrpc createAccount service_auth rejected did={s} err={s}\n", .{ did, @errorName(err) });
        return switch (err) {
            error.OutOfMemory => err,
            error.JwtExpired => http_api.xrpcError(request, .bad_request, "ExpiredToken", "token expired"),
            error.BadJwt, error.BadJwtType => http_api.xrpcError(request, .unauthorized, "InvalidToken", "invalid service auth token"),
            error.BadJwtIss => http_api.xrpcError(request, .unauthorized, "InvalidToken", "jwt issuer does not match did"),
            error.BadJwtAudience => http_api.xrpcError(request, .unauthorized, "InvalidToken", "jwt audience does not match service did"),
            error.BadJwtLexiconMethod => http_api.xrpcError(request, .unauthorized, "InvalidToken", "jwt lxm must be com.atproto.server.createAccount"),
            error.BadJwtSignature => http_api.xrpcError(request, .unauthorized, "InvalidToken", "jwt signature does not match jwt issuer"),
            else => http_api.xrpcError(request, .bad_gateway, "DidResolutionFailed", "could not resolve jwt issuer did"),
        };
    };
    log.debug("xrpc createAccount service_auth ok did={s}\n", .{did});
}

pub fn createSession(request: *http_api.Request) !void {
    var body_buf: [4096]u8 = undefined;
    const body = try http_api.readBody(request, &body_buf);

    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();

    const parsed = std.json.parseFromSlice(std.json.Value, arena.allocator(), body, .{}) catch {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Expected JSON body with identifier and password");
    };
    const identifier = zat.json.getString(parsed.value, "identifier") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing identifier");
    };
    const password = zat.json.getString(parsed.value, "password") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing password");
    };

    log.debug("xrpc createSession attempt identifier={s}\n", .{identifier});
    const account = (store.findAccount(arena.allocator(), identifier) catch null) orelse {
        log.debug("xrpc createSession rejected account_not_found identifier={s}\n", .{identifier});
        return http_api.xrpcError(request, .unauthorized, "AuthenticationRequired", "Invalid identifier or password");
    };
    const allow_takendown = switch (parsed.value) {
        .object => |object| if (object.get("allowTakendown")) |value| value == .bool and value.bool else false,
        else => false,
    };
    const primary_password_matches = auth.passwordMatches(account, password);
    const app_password = if (primary_password_matches)
        null
    else
        try store.findMatchingAppPassword(arena.allocator(), account.did, password);
    if (!primary_password_matches and app_password == null) {
        log.debug("xrpc createSession rejected password_mismatch identifier={s} did={s} handle={s}\n", .{ identifier, account.did, account.handle });
        return http_api.xrpcError(request, .unauthorized, "AuthenticationRequired", "Invalid identifier or password");
    }
    // Status is checked only after the password, so it is not disclosed to
    // anyone who lacks it.
    const takendown = switch (try store.accountStatus(account.did)) {
        .active, .deactivated => false,
        .takendown => if (allow_takendown) true else return http_api.xrpcError(request, .unauthorized, "AccountTakedown", "Account has been taken down"),
        .suspended => return http_api.xrpcError(request, .unauthorized, "AccountSuspended", "Account is suspended"),
        .deleted => return http_api.xrpcError(request, .unauthorized, "AuthenticationRequired", "Invalid identifier or password"),
    };
    log.debug("xrpc createSession ok identifier={s} did={s} handle={s}\n", .{ identifier, account.did, account.handle });

    const auth_method: []const u8 = if (takendown)
        "takendown"
    else if (app_password) |value|
        if (value.privileged) "app_password_privileged" else "app_password"
    else
        "password";
    const issued = try issueSessionTokens(arena.allocator(), account, auth_method, if (app_password) |value| value.name else null);
    const info = store.getEmailInfo(arena.allocator(), account.did) orelse {
        return http_api.xrpcError(request, .not_found, "AccountNotFound", "Account not found");
    };
    const status = try store.accountStatus(account.did);
    const body_out = try sessionJsonWithInfo(arena.allocator(), account, info.email, info.email_confirmed, status, issued.access.token, issued.refresh.token);
    try http_api.json(request, .ok, body_out);
}

pub fn refreshSession(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const auth_ctx = http_api.requireBearerAccountWithScope(request, allocator, "com.atproto.refresh") catch |err| return http_api.bearerErrorResponse(request, err);
    const account = auth_ctx.account;
    const old_claims = currentBearerClaims(request, allocator) catch {
        return http_api.xrpcError(request, .unauthorized, "InvalidToken", "Invalid token");
    };
    defer allocator.free(old_claims.did);
    defer allocator.free(old_claims.scope);
    defer allocator.free(old_claims.jti);
    defer if (old_claims.cnf_jkt) |jkt| allocator.free(jkt);
    const issued = try rotateOrReplaySession(allocator, account, old_claims.jti) orelse {
        return http_api.xrpcError(request, .bad_request, "ExpiredToken", "Token has been revoked");
    };
    const info = store.getEmailInfo(allocator, account.did) orelse {
        return http_api.xrpcError(request, .not_found, "AccountNotFound", "Account not found");
    };
    const status = try store.accountStatus(account.did);
    const body_out = try sessionJsonWithInfo(allocator, account, info.email, info.email_confirmed, status, issued.access.token, issued.refresh.token);
    try http_api.json(request, .ok, body_out);
}

pub fn deleteSession(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const auth_ctx = http_api.requireBearerAccountWithScope(request, allocator, "com.atproto.refresh") catch |err| return http_api.bearerErrorResponse(request, err);
    const claims = currentBearerClaims(request, allocator) catch {
        return http_api.xrpcError(request, .unauthorized, "InvalidToken", "Invalid token");
    };
    try store.revokeSessionToken(auth_ctx.account.did, claims.jti);
    try store.recordAuditEvent(auth_ctx.account.did, auth_ctx.account.did, null, "session_deleted", "{}");
    try http_api.json(request, .ok, "{}");
}

/// a refresh presented twice inside the grace window (a client racing itself, or
/// one that lost the race to rotate) gets the successor already on the row, so
/// neither request sees its session vanish; null means the row is gone, revoked,
/// or past its grace window
fn rotateOrReplaySession(allocator: std.mem.Allocator, account: auth.Account, presented_jti: []const u8) !?auth.SessionPair {
    // one retry: a rotation that loses the race re-reads the row and finds the winner's
    // successor as a replay; anything else on the second read means the session moved on
    for (0..2) |_| {
        const session = try store.refreshSessionByJti(allocator, account.did, presented_jti) orelse return null;
        const access_scope = accessScopeForAuthMethod(session.auth_method);
        if (session.replayed) {
            log.info("refresh token replayed inside grace window did={s} session={s}\n", .{ account.did, session.id });
            return try auth.reissueSessionPair(allocator, account, access_scope, session.access_jti, session.access_expires_at, session.refresh_jti, session.refresh_expires_at);
        }
        const issued = try auth.createSessionPairWithAccessScope(allocator, account, access_scope);
        store.rotateSessionToken(session.id, presented_jti, issued.access.jti, issued.refresh.jti, issued.access.exp, issued.refresh.exp, refresh_replay_grace_secs) catch |err| switch (err) {
            error.InvalidRefreshSession => continue,
            else => return err,
        };
        try store.recordAuditEvent(account.did, account.did, null, "session_refreshed", "{}");
        return issued;
    }
    return null;
}

pub fn getSession(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const account = http_api.requireBearerAccount(request, allocator) catch |err| return http_api.bearerErrorResponse(request, err);

    const info = store.getEmailInfo(allocator, account.did) orelse {
        return http_api.xrpcError(request, .not_found, "AccountNotFound", "Account not found");
    };
    const status = try store.accountStatus(account.did);
    const body_out = try sessionJsonWithInfo(allocator, account, info.email, info.email_confirmed, status, null, null);
    return http_api.json(request, .ok, body_out);
}

fn sessionJson(
    allocator: std.mem.Allocator,
    account: auth.Account,
    access: []const u8,
    refresh: []const u8,
) ![]const u8 {
    const info = store.getEmailInfo(allocator, account.did) orelse return error.AccountNotFound;
    return sessionJsonWithInfo(allocator, account, info.email, info.email_confirmed, try store.accountStatus(account.did), access, refresh);
}

fn issueSessionTokens(allocator: std.mem.Allocator, account: auth.Account, auth_method: []const u8, app_password_name: ?[]const u8) !auth.SessionPair {
    const issued = try auth.createSessionPairWithAccessScope(allocator, account, accessScopeForAuthMethod(auth_method));
    _ = try store.createSessionTokenRow(
        allocator,
        account.did,
        issued.access.jti,
        issued.refresh.jti,
        issued.access.exp,
        issued.refresh.exp,
        auth_method,
        null,
        app_password_name,
    );
    try store.recordAuditEvent(account.did, account.did, null, "session_created", "{}");
    return issued;
}

fn accessScopeForAuthMethod(auth_method: []const u8) []const u8 {
    if (std.mem.eql(u8, auth_method, "takendown")) return http_api.takendown_scope;
    if (std.mem.eql(u8, auth_method, "app_password_privileged")) return "com.atproto.appPassPrivileged";
    if (std.mem.eql(u8, auth_method, "app_password")) return "com.atproto.appPass";
    return "com.atproto.access";
}

fn currentBearerClaims(request: *http_api.Request, allocator: std.mem.Allocator) !auth.TokenClaims {
    const auth_header = http_api.headerValue(request, "authorization") orelse return error.AuthRequired;
    if (!std.ascii.startsWithIgnoreCase(auth_header, "bearer ")) return error.AuthRequired;
    const token = std.mem.trim(u8, auth_header["bearer ".len..], " \t");
    return auth.claimsFromSessionJwt(allocator, token) orelse error.InvalidToken;
}

fn sessionJsonWithInfo(
    allocator: std.mem.Allocator,
    account: auth.Account,
    email: []const u8,
    email_confirmed: bool,
    status: store.AccountStatus,
    access: ?[]const u8,
    refresh: ?[]const u8,
) ![]const u8 {
    const did_doc = try sessionDidDocJson(allocator, account);
    const parsed_did_doc = try std.json.parseFromSlice(std.json.Value, allocator, did_doc, .{});

    const Response = struct {
        accessJwt: ?[]const u8 = null,
        refreshJwt: ?[]const u8 = null,
        did: []const u8,
        didDoc: std.json.Value,
        handle: []const u8,
        email: []const u8,
        emailConfirmed: bool,
        active: bool,
        status: ?[]const u8 = null,
    };
    return std.json.Stringify.valueAlloc(allocator, Response{
        .accessJwt = access,
        .refreshJwt = refresh,
        .did = account.did,
        .didDoc = parsed_did_doc.value,
        .handle = account.handle,
        .email = email,
        .emailConfirmed = email_confirmed,
        .active = status.isActive(),
        .status = if (status.isActive()) null else status.asString(),
    }, .{ .emit_null_optional_fields = false });
}

fn sessionDidDocJson(allocator: std.mem.Allocator, account: auth.Account) ![]const u8 {
    var keypair = try store.signingKeypair(account.did);
    const signing_did_key = try keypair.did(allocator);
    const also_known_as = try std.fmt.allocPrint(allocator, "at://{s}", .{account.handle});
    const kem_method = if (try store.kemDidKey(allocator, account.did)) |kem_did_key|
        try std.fmt.allocPrint(allocator, ",{{\"id\":\"#atproto_kem\",\"type\":\"Multikey\",\"controller\":{f},\"publicKeyMultibase\":{f}}}", .{
            std.json.fmt(account.did, .{}),
            std.json.fmt(kem_did_key["did:key:".len..], .{}),
        })
    else
        "";
    return std.fmt.allocPrint(
        allocator,
        "{{\"@context\":[\"https://www.w3.org/ns/did/v1\"],\"id\":{f},\"alsoKnownAs\":[{f}],\"verificationMethod\":[{{\"id\":\"#atproto\",\"type\":\"Multikey\",\"controller\":{f},\"publicKeyMultibase\":{f}}}{s}],\"service\":[{{\"id\":\"#atproto_pds\",\"type\":\"AtprotoPersonalDataServer\",\"serviceEndpoint\":{f}}}]}}",
        .{
            std.json.fmt(account.did, .{}),
            std.json.fmt(also_known_as, .{}),
            std.json.fmt(account.did, .{}),
            std.json.fmt(signing_did_key["did:key:".len..], .{}),
            kem_method,
            std.json.fmt(config.publicUrl(), .{}),
        },
    );
}

pub fn activateAccount(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const account = requireAccount(request, allocator) catch return;
    store.setAccountActive(account.did, true) catch |err| switch (err) {
        error.InvalidAccountStatus => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Account cannot be activated while takendown, suspended, or deleted"),
        else => return err,
    };
    // Repos are created on first use; the sync event below needs one.
    try store.initializeRepo(allocator, account);
    try store.sequenceAccountEvent(allocator, account.did, .active);
    try store.sequenceIdentityEvent(allocator, account.did, account.handle);
    try store.sequenceSyncEvent(allocator, account.did);
    sync.notifyCrawlers(true);
    return http_api.json(request, .ok, "{}");
}

pub fn deactivateAccount(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    // A taken down account may deactivate too; it stays taken down (see
    // store.setAccountActive), so the event carries its real status.
    const account = (http_api.requireBearerAccessOrTakendown(request, allocator) catch |err| {
        return http_api.bearerErrorResponse(request, err);
    }).account;
    store.setAccountActive(account.did, false) catch |err| switch (err) {
        error.InvalidAccountStatus => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Account cannot be deactivated while suspended or deleted"),
        else => return err,
    };
    try store.sequenceAccountEvent(allocator, account.did, try store.accountStatus(account.did));
    sync.notifyCrawlers(true);
    return http_api.json(request, .ok, "{}");
}

pub fn updateSubjectStatus(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    requireAdminToken(request) catch return;
    var body_buf: [8192]u8 = undefined;
    const body = try http_api.readBody(request, &body_buf);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const subject = switch (parsed.value) {
        .object => |object| object.get("subject") orelse {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing subject");
        },
        else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Expected object"),
    };
    switch (subjectKind(subject)) {
        .account => {},
        .record, .blob => |kind| return updateContentSubjectStatus(request, allocator, kind, subject, objectValue(parsed.value, "takedown")),
        .invalid => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid subject"),
    }
    const did = switch (subject) {
        .object => |object| switch (object.get("did") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing subject did")) {
            .string => |value| value,
            else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid subject did"),
        },
        else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid subject"),
    };
    if (zat.Did.parse(did) == null) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid subject did");
    }

    const takedown = objectValue(parsed.value, "takedown");
    const deactivated = objectValue(parsed.value, "deactivated");
    const takedown_applied = if (takedown) |value| valueBool(value, "applied") orelse false else false;
    const deactivated_applied = if (deactivated) |value| valueBool(value, "applied") else null;
    if (takedown_applied and deactivated_applied != null and deactivated_applied.? == false) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Cannot activate and takedown an account at the same time");
    }

    if (takedown) |value| {
        const applied = valueBool(value, "applied") orelse {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing takedown.applied");
        };
        if (!applied) {
            try store.setAccountTakendown(did, false, null);
        }
    }
    if (!takedown_applied) {
        if (deactivated) |value| {
            const applied = valueBool(value, "applied") orelse {
                return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing deactivated.applied");
            };
            store.setAccountActive(did, !applied) catch |err| switch (err) {
                error.InvalidAccountStatus => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Account cannot be activated while takendown, suspended, or deleted"),
                else => return err,
            };
        }
    }
    if (takedown) |value| {
        const applied = valueBool(value, "applied") orelse {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing takedown.applied");
        };
        if (applied) {
            const status_ref = zat.json.getString(value, "ref");
            try store.setAccountTakendown(did, true, status_ref);
        }
    }
    if (takedown == null and deactivated == null) {
        _ = try store.accountStatus(did);
    }

    const status = try store.accountStatus(did);
    try store.sequenceAccountEvent(allocator, did, status);
    sync.notifyCrawlers(true);
    const body_out = try std.fmt.allocPrint(
        allocator,
        "{{\"subject\":{{\"$type\":\"com.atproto.admin.defs#repoRef\",\"did\":{f}}},\"active\":{},\"status\":{f}}}",
        .{ std.json.fmt(did, .{}), status.isActive(), std.json.fmt(status.asString(), .{}) },
    );
    return http_api.json(request, .ok, body_out);
}

const SubjectKind = enum { account, record, blob, invalid };

fn subjectKind(subject: std.json.Value) SubjectKind {
    if (subject != .object) return .invalid;
    if (zat.json.getString(subject, "$type")) |kind| {
        if (std.mem.eql(u8, kind, "com.atproto.admin.defs#repoRef")) return .account;
        if (std.mem.eql(u8, kind, "com.atproto.repo.strongRef")) return .record;
        if (std.mem.eql(u8, kind, "com.atproto.admin.defs#repoBlobRef")) return .blob;
        return .invalid;
    }
    if (zat.json.getString(subject, "uri") != null) return .record;
    if (zat.json.getString(subject, "cid") != null) return .blob;
    return .account;
}

/// Record and blob takedowns, as on the reference PDS: `deactivated` applies
/// only to accounts, and a takedown without a ref is stamped with the time.
fn updateContentSubjectStatus(
    request: *http_api.Request,
    allocator: std.mem.Allocator,
    kind: SubjectKind,
    subject: std.json.Value,
    takedown: ?std.json.Value,
) !void {
    const takedown_value = takedown orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing takedown");
    const applied = valueBool(takedown_value, "applied") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing takedown.applied");
    };
    const ref: ?[]const u8 = if (!applied) null else zat.json.getString(takedown_value, "ref") orelse try clock.isoMillis(allocator, clock.nowSeconds());
    var subject_json: []const u8 = undefined;
    switch (kind) {
        .record => {
            const uri = zat.json.getString(subject, "uri") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing subject uri");
            const cid = zat.json.getString(subject, "cid") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing subject cid");
            store.setRecordTakedown(uri, applied, ref) catch |err| switch (err) {
                error.SubjectNotFound => return http_api.xrpcError(request, .bad_request, "NotFound", "Subject not found"),
                else => return err,
            };
            subject_json = try std.fmt.allocPrint(allocator, "{{\"$type\":\"com.atproto.repo.strongRef\",\"uri\":{f},\"cid\":{f}}}", .{ std.json.fmt(uri, .{}), std.json.fmt(cid, .{}) });
        },
        .blob => {
            const did = zat.json.getString(subject, "did") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing subject did");
            const cid = zat.json.getString(subject, "cid") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing subject cid");
            if (zat.Did.parse(did) == null) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid subject did");
            store.setBlobTakedown(did, cid, applied, ref) catch |err| switch (err) {
                error.SubjectNotFound => return http_api.xrpcError(request, .bad_request, "NotFound", "Subject not found"),
                else => return err,
            };
            subject_json = try std.fmt.allocPrint(allocator, "{{\"$type\":\"com.atproto.admin.defs#repoBlobRef\",\"did\":{f},\"cid\":{f}}}", .{ std.json.fmt(did, .{}), std.json.fmt(cid, .{}) });
        },
        .account, .invalid => unreachable,
    }
    const body_out = try std.fmt.allocPrint(allocator, "{{\"subject\":{s},\"takedown\":{s}}}", .{ subject_json, try takedownJson(allocator, .{ .applied = applied, .ref = ref }) });
    return http_api.json(request, .ok, body_out);
}

fn takedownJson(allocator: std.mem.Allocator, takedown: store.SubjectTakedown) ![]const u8 {
    if (takedown.ref) |ref| return std.fmt.allocPrint(allocator, "{{\"applied\":{},\"ref\":{f}}}", .{ takedown.applied, std.json.fmt(ref, .{}) });
    return std.fmt.allocPrint(allocator, "{{\"applied\":{}}}", .{takedown.applied});
}

pub fn getSubjectStatus(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    requireAdminToken(request) catch return;
    var did_buf: [256]u8 = undefined;
    var uri_buf: [1024]u8 = undefined;
    var blob_buf: [256]u8 = undefined;
    const did = http_api.queryParam(request.url.raw, "did", &did_buf);
    const uri = http_api.queryParam(request.url.raw, "uri", &uri_buf);
    const blob = http_api.queryParam(request.url.raw, "blob", &blob_buf);
    var body_out: ?[]const u8 = null;
    if (blob) |cid| {
        const repo = did orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Must provide a did to request blob state");
        if (try store.blobTakedown(allocator, repo, cid)) |takedown| {
            body_out = try std.fmt.allocPrint(allocator, "{{\"subject\":{{\"$type\":\"com.atproto.admin.defs#repoBlobRef\",\"did\":{f},\"cid\":{f}}},\"takedown\":{s}}}", .{ std.json.fmt(repo, .{}), std.json.fmt(cid, .{}), try takedownJson(allocator, takedown) });
        }
    } else if (uri) |record_uri| {
        if (try store.recordTakedownStatus(allocator, record_uri)) |status| {
            if (status.takedown.applied) {
                body_out = try std.fmt.allocPrint(allocator, "{{\"subject\":{{\"$type\":\"com.atproto.repo.strongRef\",\"uri\":{f},\"cid\":{f}}},\"takedown\":{s}}}", .{ std.json.fmt(record_uri, .{}), std.json.fmt(status.cid, .{}), try takedownJson(allocator, status.takedown) });
            }
        }
    } else if (did) |account_did| {
        if (try store.accountAdminStatus(allocator, account_did)) |status| {
            body_out = try std.fmt.allocPrint(allocator, "{{\"subject\":{{\"$type\":\"com.atproto.admin.defs#repoRef\",\"did\":{f}}},\"takedown\":{s},\"deactivated\":{{\"applied\":{}}}}}", .{ std.json.fmt(account_did, .{}), try takedownJson(allocator, status.takedown), status.deactivated });
        }
    } else {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "No provided subject");
    }
    return http_api.json(request, .ok, body_out orelse return http_api.xrpcError(request, .bad_request, "NotFound", "Subject not found"));
}

pub fn adminDeleteAccount(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    requireAdminToken(request) catch return;
    var body_buf: [1024]u8 = undefined;
    const body = try http_api.readBody(request, &body_buf);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const did = zat.json.getString(parsed.value, "did") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing did");
    };
    if (zat.Did.parse(did) == null) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid did");
    }
    if ((store.findAccount(allocator, did) catch null) == null) {
        return http_api.xrpcError(request, .bad_request, "AccountNotFound", "Account not found");
    }
    tombstoneBeforeDelete(request, allocator, did) catch return;
    store.deleteAccount(allocator, did) catch |err| switch (err) {
        error.RepoNotFound => return http_api.xrpcError(request, .bad_request, "AccountNotFound", "Account not found"),
        else => return err,
    };
    sync.forgetRepoExport(did);
    sync.notifyCrawlers(true);
    return http_api.json(request, .ok, "{}");
}

/// Emails a delete_account code, as the reference PDS does: the account's own
/// session only, not OAuth or an app password, and not under a takedown.
pub fn requestAccountDelete(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireAccountAccess(request, allocator) catch return;
    if (auth_ctx.oauth_scope != null) {
        return http_api.xrpcError(request, .forbidden, "Forbidden", "OAuth credentials are not supported for this endpoint");
    }
    if (auth_ctx.app_password) return http_api.xrpcError(request, .bad_request, "InvalidToken", "Bad token scope");
    const account = auth_ctx.account;
    try http_api.requireActiveAccount(request, account.did, .takedown);
    const info = store.getEmailInfo(allocator, account.did) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "account not found");
    };
    if (info.email.len == 0) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "account does not have an email address");
    var code_buf: [11]u8 = undefined;
    const code = email_tokens.makeCode(&code_buf);
    try store.setEmailToken(account.did, .delete_account, code, expiresInTenMinutes());
    try sendCode(allocator, info.email, account.handle, "Delete account", "account deletion", code);
    return http_api.json(request, .ok, "{}");
}

/// Deletes the account given its DID, password, and the emailed delete_account
/// code; unauthenticated, as on the reference PDS. A deactivated or taken down
/// account can delete itself too.
pub fn deleteAccount(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    var body_buf: [4096]u8 = undefined;
    const body = try http_api.readBody(request, &body_buf);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const did = zat.json.getString(parsed.value, "did") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing did");
    const password = zat.json.getString(parsed.value, "password") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing password");
    const token = zat.json.getString(parsed.value, "token") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing token");
    if (zat.Did.parse(did) == null) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid did");
    const account = (store.findAccount(allocator, did) catch null) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "account not found");
    };
    if (!std.mem.eql(u8, account.did, did) or !auth.passwordMatches(account, password)) {
        return http_api.xrpcError(request, .unauthorized, "AuthenticationRequired", "Invalid did or password");
    }
    switch (store.validateEmailToken(account.did, .delete_account, token, store.nowMs())) {
        .valid => {},
        .expired => return http_api.xrpcError(request, .bad_request, "ExpiredToken", "Token is expired"),
        .invalid => return http_api.xrpcError(request, .bad_request, "InvalidToken", "Token is invalid"),
    }
    tombstoneBeforeDelete(request, allocator, account.did) catch return;
    store.deleteAccount(allocator, account.did) catch |err| switch (err) {
        error.RepoNotFound => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "account not found"),
        else => return err,
    };
    sync.forgetRepoExport(account.did);
    sync.notifyCrawlers(true);
    return http_api.json(request, .ok, "{}");
}

/// With ZDS_PLC_TOMBSTONE_ON_DELETE, the DID is tombstoned before the account
/// goes, so a failure leaves the account in place to delete again.
fn tombstoneBeforeDelete(request: *http_api.Request, allocator: std.mem.Allocator, did: []const u8) !void {
    if (!config.plcTombstoneOnDelete()) return;
    plc.tombstone(allocator, did) catch |err| {
        log.err("plc tombstone failed did={s} err={s}\n", .{ did, @errorName(err) });
        try http_api.xrpcError(request, .bad_gateway, "UpstreamFailure", "Could not tombstone the DID; the account was not deleted");
        return error.HandledResponse;
    };
}

pub fn getServiceAuth(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const auth_ctx = http_api.requireBearerAccessOrTakendown(request, allocator) catch |err| return http_api.bearerErrorResponse(request, err);
    const account = auth_ctx.account;

    var aud_buf: [256]u8 = undefined;
    const audience = http_api.queryParam(request.url.raw, "aud", &aud_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing aud");
    };
    if (!validServiceAuthAudience(audience)) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid aud");
    }

    var lxm_buf: [256]u8 = undefined;
    const lxm = http_api.queryParam(request.url.raw, "lxm", &lxm_buf);
    // A taken-down account may only authorize creating its account on a new host.
    if (auth_ctx.takendown and !std.mem.eql(u8, lxm orelse "", "com.atproto.server.createAccount")) {
        return http_api.xrpcError(request, .bad_request, "InvalidToken", "Bad token scope");
    }
    if (lxm) |method| {
        if (zat.Nsid.parse(method) == null) {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid lxm");
        }
        if (serviceAuthProtectedMethod(method)) {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Cannot request service auth for protected method");
        }
        if (!scopes.rpcAllows(auth_ctx.oauth_scope, audience, method)) {
            return http_api.xrpcError(request, .forbidden, "InsufficientScope", "Insufficient scope");
        }
    } else if (auth_ctx.oauth_scope != null and !scopes.hasFullAccess(auth_ctx.oauth_scope)) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "OAuth tokens with granular scopes must specify an lxm parameter");
    }

    const requested_exp = try requestedServiceAuthExpiration(request, lxm != null);

    var keypair = try store.signingKeypair(account.did);
    const token = try zat.service_auth.create(allocator, store.currentIo(), &keypair, .{ .iss = account.did, .sub = account.did, .aud = audience, .lxm = lxm, .exp = requested_exp });
    const body_out = try std.fmt.allocPrint(allocator, "{{\"token\":\"{s}\"}}", .{token});
    return http_api.json(request, .ok, body_out);
}

fn validServiceAuthAudience(audience: []const u8) bool {
    if (zat.Did.parse(audience) != null) return true;
    const hash = std.mem.indexOfScalar(u8, audience, '#') orelse return false;
    if (hash == 0 or hash + 1 >= audience.len) return false;
    if (std.mem.indexOfScalarPos(u8, audience, hash + 1, '#') != null) return false;
    return zat.Did.parse(audience[0..hash]) != null;
}

fn requestedServiceAuthExpiration(request: *http_api.Request, has_lxm: bool) !?i64 {
    var exp_buf: [32]u8 = undefined;
    const raw = http_api.queryParam(request.url.raw, "exp", &exp_buf) orelse return null;
    const exp = std.fmt.parseInt(i64, raw, 10) catch {
        try http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid exp");
        return error.HandledResponse;
    };
    const now = unixNow();
    const diff = exp - now;
    if (diff < 0) {
        try http_api.xrpcError(request, .bad_request, "BadExpiration", "expiration is in past");
        return error.HandledResponse;
    }
    if (diff > 60 * 60) {
        try http_api.xrpcError(request, .bad_request, "BadExpiration", "cannot request a token with an expiration more than an hour in the future");
        return error.HandledResponse;
    }
    if (!has_lxm and diff > 60) {
        try http_api.xrpcError(request, .bad_request, "BadExpiration", "cannot request a method-less token with an expiration more than a minute in the future");
        return error.HandledResponse;
    }
    return exp;
}

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

fn serviceAuthProtectedMethod(method: []const u8) bool {
    const protected = [_][]const u8{
        "com.atproto.admin.sendEmail",
        "com.atproto.identity.requestPlcOperationSignature",
        "com.atproto.identity.signPlcOperation",
        "com.atproto.identity.updateHandle",
        "com.atproto.server.activateAccount",
        "com.atproto.server.confirmEmail",
        "com.atproto.server.createAppPassword",
        "com.atproto.server.deactivateAccount",
        "com.atproto.server.getAccountInviteCodes",
        "com.atproto.server.getSession",
        "com.atproto.server.listAppPasswords",
        "com.atproto.server.requestAccountDelete",
        "com.atproto.server.requestEmailConfirmation",
        "com.atproto.server.requestEmailUpdate",
        "com.atproto.server.revokeAppPassword",
        "com.atproto.server.updateEmail",
    };
    for (protected) |item| {
        if (std.ascii.eqlIgnoreCase(method, item)) return true;
    }
    return false;
}

pub fn adminUpdateAccountPassword(request: *http_api.Request) !void {
    try requireAdminToken(request);
    return changeAccountPassword(request, false);
}

pub fn resetPassword(request: *http_api.Request) !void {
    return changeAccountPassword(request, true);
}

fn changeAccountPassword(request: *http_api.Request, reset: bool) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const body = try http_api.readBodyAlloc(request, allocator, 4096);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const password = zat.json.getString(parsed.value, "password") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing password");
    if (password.len > 256) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid password length");
    const target: store.PasswordTarget = if (reset)
        .{ .reset_token = zat.json.getString(parsed.value, "token") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing token") }
    else
        .{ .did = zat.json.getString(parsed.value, "did") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing did") };
    if (target == .did and zat.Did.parse(target.did) == null) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid did");
    store.changePassword(allocator, target, password, config.serverDid()) catch |err| switch (err) {
        error.InvalidToken, error.ExpiredToken => return http_api.xrpcError(request, .bad_request, @errorName(err), "Invalid or expired password reset token"),
        error.AccountNotFound => return http_api.xrpcError(request, .bad_request, "AccountNotFound", "Account not found"),
        else => return err,
    };
    return http_api.json(request, .ok, "{}");
}

pub fn requestPasswordReset(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const body = try http_api.readBodyAlloc(request, allocator, 4096);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const email = zat.json.getString(parsed.value, "email") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing email");
    const account = (try store.findAccount(allocator, email)) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Account does not have an email address");
    if (!std.ascii.eqlIgnoreCase(account.email, email) or try store.accountStatus(account.did) == .deleted) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Account does not have an email address");
    var code_buf: [11]u8 = undefined;
    const code = email_tokens.makeCode(&code_buf);
    if (!try store.setPasswordResetToken(account.did, account.email, code, expiresInTenMinutes())) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Account email changed; request a new reset code");
    try sendCode(allocator, account.email, account.handle, "Reset password", "password reset", code);
    return http_api.json(request, .ok, "{}");
}

pub fn requestEmailConfirmation(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireAccountAccess(request, allocator) catch return;
    try requireAccountScope(request, auth_ctx.oauth_scope, .email, .manage);
    const account = auth_ctx.account;
    try http_api.requireActiveAccount(request, account.did, .takedown);
    const info = store.getEmailInfo(allocator, account.did) orelse {
        return http_api.xrpcError(request, .not_found, "AccountNotFound", "Account not found");
    };
    if (info.email_confirmed) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "email already confirmed");
    }
    var code_buf: [11]u8 = undefined;
    const code = email_tokens.makeCode(&code_buf);
    try store.setEmailToken(account.did, .confirm_email, code, expiresInTenMinutes());
    try sendCode(allocator, info.email, account.handle, "Confirm email", "email confirmation", code);
    return http_api.json(request, .ok, "{}");
}

pub fn confirmEmail(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireAccountAccess(request, allocator) catch return;
    try requireAccountScope(request, auth_ctx.oauth_scope, .email, .manage);
    const account = auth_ctx.account;
    var body_buf: [4096]u8 = undefined;
    const body = try http_api.readBody(request, &body_buf);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const email = zat.json.getString(parsed.value, "email") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing email");
    };
    const token = zat.json.getString(parsed.value, "token") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing token");
    };
    const info = store.getEmailInfo(allocator, account.did) orelse {
        return http_api.xrpcError(request, .not_found, "AccountNotFound", "Account not found");
    };
    if (!std.ascii.eqlIgnoreCase(info.email, email)) {
        return http_api.xrpcError(request, .bad_request, "InvalidEmail", "email does not match");
    }
    switch (store.validateEmailToken(account.did, .confirm_email, token, store.nowMs())) {
        .valid => try store.confirmEmail(account.did),
        .expired => return http_api.xrpcError(request, .bad_request, "ExpiredToken", "token expired"),
        .invalid => return http_api.xrpcError(request, .bad_request, "InvalidToken", "invalid token"),
    }
    return http_api.json(request, .ok, "{}");
}

pub fn requestEmailUpdate(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireAccountAccess(request, allocator) catch return;
    try requireAccountScope(request, auth_ctx.oauth_scope, .email, .manage);
    const account = auth_ctx.account;
    try http_api.requireActiveAccount(request, account.did, .takedown);
    const info = store.getEmailInfo(allocator, account.did) orelse {
        return http_api.xrpcError(request, .not_found, "AccountNotFound", "Account not found");
    };
    if (!info.email_confirmed) {
        return http_api.json(request, .ok, "{\"tokenRequired\":false}");
    }
    var code_buf: [11]u8 = undefined;
    const code = email_tokens.makeCode(&code_buf);
    try store.setEmailToken(account.did, .update_email, code, expiresInTenMinutes());
    try sendCode(allocator, info.email, account.handle, "Update email", "email update", code);
    return http_api.json(request, .ok, "{\"tokenRequired\":true}");
}

pub fn updateEmail(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireAccountAccess(request, allocator) catch return;
    try requireAccountScope(request, auth_ctx.oauth_scope, .email, .manage);
    const account = auth_ctx.account;
    var body_buf: [4096]u8 = undefined;
    const body = try http_api.readBody(request, &body_buf);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const email = zat.json.getString(parsed.value, "email") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing email");
    };
    if (!isValidEmail(email)) {
        return http_api.xrpcError(request, .bad_request, "InvalidEmail", "invalid email");
    }
    const info = store.getEmailInfo(allocator, account.did) orelse {
        return http_api.xrpcError(request, .not_found, "AccountNotFound", "Account not found");
    };
    if (info.email_confirmed) {
        const token = zat.json.getString(parsed.value, "token") orelse {
            return http_api.xrpcError(request, .bad_request, "TokenRequired", "confirmation token required");
        };
        switch (store.validateEmailToken(account.did, .update_email, token, store.nowMs())) {
            .valid => {},
            .expired => return http_api.xrpcError(request, .bad_request, "ExpiredToken", "token expired"),
            .invalid => return http_api.xrpcError(request, .bad_request, "InvalidToken", "invalid token"),
        }
    }
    try store.updateEmail(account.did, email);
    return http_api.json(request, .ok, "{}");
}

pub fn checkAccountStatus(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const account = requireAccount(request, allocator) catch return;
    try store.initializeRepo(allocator, account);
    const body = try store.writeAccountStatusJson(allocator, account.did);
    return http_api.json(request, .ok, body);
}

fn requireAccount(request: *http_api.Request, allocator: std.mem.Allocator) !auth.Account {
    return (try requireAccountAccess(request, allocator)).account;
}

fn requireAccountAccess(request: *http_api.Request, allocator: std.mem.Allocator) !http_api.BearerAccount {
    return http_api.requireBearerAccess(request, allocator) catch |err| {
        try http_api.bearerErrorResponse(request, err);
        return error.HandledResponse;
    };
}

fn requireAccountScope(request: *http_api.Request, maybe_scope: ?[]const u8, attr: scopes.AccountAttr, action: scopes.AccountAction) !void {
    if (scopes.accountAllows(maybe_scope, attr, action)) return;
    try http_api.xrpcError(request, .forbidden, "InsufficientScope", "Insufficient scope");
    return error.HandledResponse;
}

fn requirePasswordSession(request: *http_api.Request, allocator: std.mem.Allocator, did: []const u8) !void {
    const claims = currentBearerClaims(request, allocator) catch {
        try http_api.xrpcError(request, .forbidden, "AuthFactorTokenRequired", "Password session required");
        return error.HandledResponse;
    };
    defer allocator.free(claims.did);
    defer allocator.free(claims.scope);
    defer allocator.free(claims.jti);
    defer if (claims.cnf_jkt) |jkt| allocator.free(jkt);
    if (!std.mem.eql(u8, claims.did, did)) {
        try http_api.xrpcError(request, .forbidden, "AuthFactorTokenRequired", "Password session required");
        return error.HandledResponse;
    }
    const method = try store.sessionAuthMethod(allocator, did, claims.jti) orelse {
        try http_api.xrpcError(request, .forbidden, "AuthFactorTokenRequired", "Password session required");
        return error.HandledResponse;
    };
    if (!std.mem.eql(u8, method, "password") and !std.mem.eql(u8, method, "account_create")) {
        try http_api.xrpcError(request, .forbidden, "AuthFactorTokenRequired", "Password session required");
        return error.HandledResponse;
    }
}

fn requireAdminToken(request: *http_api.Request) !void {
    const expected = config.adminToken() orelse {
        try http_api.xrpcError(request, .forbidden, "AdminRequired", "Admin token not configured");
        return error.HandledResponse;
    };
    var basic_buf: [1024]u8 = undefined;
    const provided = http_api.adminCredential(http_api.headerValue(request, "authorization") orelse "", &basic_buf) orelse {
        try http_api.xrpcError(request, .unauthorized, "AuthenticationRequired", "Authentication required");
        return error.HandledResponse;
    };
    if (!http_api.adminTokenMatches(provided, expected)) {
        try http_api.xrpcError(request, .forbidden, "AdminRequired", "Admin token required");
        return error.HandledResponse;
    }
}

fn objectValue(value: std.json.Value, key: []const u8) ?std.json.Value {
    return switch (value) {
        .object => |object| object.get(key),
        else => null,
    };
}

fn valueBool(value: std.json.Value, key: []const u8) ?bool {
    return switch (value) {
        .object => |object| switch (object.get(key) orelse return null) {
            .bool => |boolean| boolean,
            else => null,
        },
        else => null,
    };
}

fn expiresInTenMinutes() i64 {
    return store.nowMs() + (10 * 60 * 1000);
}

fn generateAppPassword(allocator: std.mem.Allocator) ![]const u8 {
    const alphabet = "abcdefghijklmnopqrstuvwxyz234567";
    var random: [16]u8 = undefined;
    store.randomBytes(&random);
    var out: [19]u8 = undefined;
    for (random, 0..) |byte, idx| {
        const write_idx = idx + @divTrunc(idx, 4);
        out[write_idx] = alphabet[byte & 31];
    }
    out[4] = '-';
    out[9] = '-';
    out[14] = '-';
    return allocator.dupe(u8, out[0..]);
}

fn sendCode(
    allocator: std.mem.Allocator,
    email: []const u8,
    handle: []const u8,
    subject: []const u8,
    label: []const u8,
    code: []const u8,
) !void {
    return mail.sendCode(store.currentIo(), allocator, email, handle, subject, label, code) catch {
        return error.EmailDeliveryFailed;
    };
}

fn isValidEmail(email: []const u8) bool {
    const at = std.mem.indexOfScalar(u8, email, '@') orelse return false;
    if (at == 0 or at + 1 >= email.len) return false;
    return std.mem.indexOfScalar(u8, email[at + 1 ..], '.') != null;
}