Microservice to bring 2FA to self hosted PDSes

Adding an RBAC functionality for Admins.

Problem: Bluesky's reference PDS using a PDS_ADMIN_PASSWORD with basic auth as
an admin api authz. If the PDS is managed by a team, then this
becomes a shared password.

Solution: have pds-gateway manage the PDS_ADMIN_PASSWORD and have the
PDS administration team login to pds-gateway via OAuth with their
corresponding PDS, and then they'll be given a portal scoped to their
capabilities specified by the RBAC scpecification, see ADMIN.md. Admin
portal is inspired by https://github.com/betamax/pds-admin. When an
admin team member wants to perform an operation (e.g. send a new users
an invite code), the team member can click through the portal to do so
and the pds-gateway will perform the operations with the
PDS_ADMIN_PASSWORD on their behalf. This prevents the shared password
problem whilst giving admins a tool to manage their PDS easier!

+5198 -6
+203
ADMIN.md
··· 1 + # PDS Admin Portal 2 + 3 + ## Overview 4 + 5 + Bluesky's PDS admin API relies on `PDS_ADMIN_PASSWORD` — a single shared secret that grants unrestricted access to every administrative endpoint. This is workable for solo operators but becomes a liability when multiple team members need admin access. There is no way to limit what any individual can do, no audit trail of who performed an action, and credential rotation affects everyone simultaneously. 6 + 7 + The pds-gatekeeper admin portal solves this by introducing role-based access control (RBAC). Team members authenticate with ATProto OAuth using their own identity, and gatekeeper enforces per-user permissions based on a YAML configuration file. Authorized requests are proxied to the PDS using the admin password on behalf of the authenticated user — the password itself is never exposed to browsers or end users. 8 + 9 + ## Prerequisites 10 + 11 + - A PDS instance running behind pds-gatekeeper 12 + - HTTPS with a valid TLS certificate (required for ATProto OAuth flows) 13 + - SMTP configured on the PDS for email functionality (used by the PDS itself, not strictly by the admin portal) 14 + 15 + ## Quick Start 16 + 17 + ### 1. Create an RBAC configuration file 18 + 19 + Copy the example configuration as a starting point: 20 + 21 + ```sh 22 + cp examples/admin_rbac.yaml /path/to/your/admin_rbac.yaml 23 + ``` 24 + 25 + ### 2. Find your team members' DIDs 26 + 27 + Use [`goat`](https://github.com/bluesky-social/indigo/tree/main/cmd/goat) to resolve a handle to its DID: 28 + 29 + ```sh 30 + goat resolve alice.example.com 31 + ``` 32 + 33 + The DID is the `id` field in the output (e.g. `did:plc:abcdef1234567890`). 34 + 35 + ### 3. Set environment variables 36 + 37 + ```sh 38 + # Required 39 + GATEKEEPER_ADMIN_RBAC_CONFIG=/path/to/your/admin_rbac.yaml 40 + PDS_ADMIN_PASSWORD=your-pds-admin-password 41 + 42 + # Optional 43 + GATEKEEPER_ADMIN_COOKIE_SECRET=<64-character-hex-string> 44 + GATEKEEPER_ADMIN_SESSION_TTL_HOURS=24 45 + ``` 46 + 47 + ### 4. Restart pds-gatekeeper 48 + 49 + ```sh 50 + # If running with systemd: 51 + sudo systemctl restart pds-gatekeeper 52 + 53 + # If running with Docker: 54 + docker restart pds-gatekeeper 55 + ``` 56 + 57 + ### 5. Navigate to the admin portal 58 + 59 + Open your browser and go to: 60 + 61 + ``` 62 + https://your-pds.example.com/admin/login 63 + ``` 64 + 65 + ## RBAC Configuration 66 + 67 + The RBAC configuration is a YAML file with two top-level sections: `roles` and `members`. 68 + 69 + - **Roles** define named sets of endpoint patterns that grant access to specific admin operations. 70 + - **Members** map an ATProto DID to one or more roles. 71 + 72 + A member's effective permissions are the **union** of all endpoints from all of their assigned roles. 73 + 74 + Endpoint patterns support wildcard matching: `com.atproto.admin.*` matches all endpoints under the `com.atproto.admin` namespace. 75 + 76 + Example: 77 + 78 + ```yaml 79 + roles: 80 + pds-admin: 81 + endpoints: 82 + - "com.atproto.admin.*" 83 + - "com.atproto.server.createInviteCode" 84 + - "com.atproto.server.createAccount" 85 + 86 + moderator: 87 + endpoints: 88 + - "com.atproto.admin.getAccountInfo" 89 + - "com.atproto.admin.getAccountInfos" 90 + - "com.atproto.admin.searchAccounts" 91 + - "com.atproto.admin.getSubjectStatus" 92 + - "com.atproto.admin.updateSubjectStatus" 93 + - "com.atproto.admin.sendEmail" 94 + - "com.atproto.admin.getInviteCodes" 95 + 96 + invite-manager: 97 + endpoints: 98 + - "com.atproto.server.createInviteCode" 99 + - "com.atproto.admin.getInviteCodes" 100 + - "com.atproto.admin.disableInviteCodes" 101 + - "com.atproto.admin.enableAccountInvites" 102 + - "com.atproto.admin.disableAccountInvites" 103 + 104 + members: 105 + - did: "did:plc:abcdef1234567890" 106 + roles: 107 + - pds-admin 108 + 109 + - did: "did:plc:bbbbbbbbbbbbbbbb" 110 + roles: 111 + - moderator 112 + - invite-manager 113 + ``` 114 + 115 + ## Available Roles (Reference) 116 + 117 + ### Suggested role templates 118 + 119 + You can make your own roles and teams 120 + 121 + | Role | Description | Endpoints | 122 + |---|---|---| 123 + | `pds-admin` | Full administrative access | `com.atproto.admin.*`, `createInviteCode`, `createAccount` | 124 + | `moderator` | View accounts, manage takedowns, search, send email, view invite codes | `getAccountInfo`, `getAccountInfos`, `searchAccounts`, `getSubjectStatus`, `updateSubjectStatus`, `sendEmail`, `getInviteCodes` | 125 + | `invite-manager` | Manage invite codes and per-account invite permissions | `createInviteCode`, `getInviteCodes`, `disableInviteCodes`, `enableAccountInvites`, `disableAccountInvites` | 126 + 127 + ### All admin XRPC endpoints 128 + 129 + | Endpoint | Description | 130 + |---|---| 131 + | `com.atproto.admin.getAccountInfo` | View single account details | 132 + | `com.atproto.admin.getAccountInfos` | View multiple accounts | 133 + | `com.atproto.admin.searchAccounts` | Search accounts | 134 + | `com.atproto.admin.getSubjectStatus` | Get takedown status | 135 + | `com.atproto.admin.updateSubjectStatus` | Apply or remove takedowns | 136 + | `com.atproto.admin.deleteAccount` | Permanently delete an account | 137 + | `com.atproto.admin.updateAccountPassword` | Reset account password | 138 + | `com.atproto.admin.enableAccountInvites` | Enable invites for an account | 139 + | `com.atproto.admin.disableAccountInvites` | Disable invites for an account | 140 + | `com.atproto.admin.getInviteCodes` | List invite codes | 141 + | `com.atproto.admin.disableInviteCodes` | Disable specific invite codes | 142 + | `com.atproto.admin.sendEmail` | Send email to an account | 143 + | `com.atproto.server.createInviteCode` | Create a new invite code | 144 + | `com.atproto.server.createAccount` | Create a new account | 145 + 146 + ## How It Works 147 + 148 + ### 1. OAuth Login 149 + 150 + The user navigates to `/admin/login` and enters their ATProto handle. Gatekeeper initiates an OAuth authorization flow, redirecting the user to their identity's authorization server. The user authenticates there and is redirected back to gatekeeper with an authorization code. 151 + 152 + ### 2. Session Creation 153 + 154 + Gatekeeper exchanges the authorization code for tokens, extracts the user's DID from the OAuth session, and checks it against the RBAC configuration. If the DID is found in the members list, a signed session cookie is created and set in the browser. 155 + 156 + ### 3. Request Flow 157 + 158 + When the user performs an admin action, gatekeeper: 159 + 160 + 1. Validates the session cookie signature and expiration 161 + 2. Looks up the user's DID in the RBAC configuration 162 + 3. Checks whether the user's roles grant access to the target XRPC endpoint 163 + 4. If authorized, proxies the request to the PDS with `Authorization: Basic` using `PDS_ADMIN_PASSWORD` 164 + 5. Returns the PDS response to the user 165 + 166 + ### 4. UI Rendering 167 + 168 + The admin portal uses server-rendered pages that show or hide actions based on the authenticated user's permissions. However, RBAC is always enforced server-side in route handlers regardless of what the UI displays — hiding a button in the template is a convenience, not a security boundary. 169 + 170 + ## Environment Variables 171 + 172 + | Variable | Required | Default | Description | 173 + |---|---|---|---| 174 + | `GATEKEEPER_ADMIN_RBAC_CONFIG` | Yes | — | Path to the RBAC YAML configuration file | 175 + | `PDS_ADMIN_PASSWORD` | Yes | — | PDS admin password used for proxied requests | 176 + | `GATEKEEPER_ADMIN_COOKIE_SECRET` | No | Derived from `GATEKEEPER_JWE_KEY` | 32-byte hex key for signing session cookies | 177 + | `GATEKEEPER_ADMIN_SESSION_TTL_HOURS` | No | `24` | Admin session lifetime in hours | 178 + 179 + ## Security Considerations 180 + 181 + - **Password isolation**: `PDS_ADMIN_PASSWORD` is never sent to or accessible from browsers. It is only used server-side when proxying authorized requests to the PDS. 182 + - **OAuth security**: The OAuth flow uses DPoP binding and PKCE to prevent token interception and replay attacks. 183 + - **Cookie protections**: Session cookies are signed (tamper-proof) and set with `HttpOnly`, `Secure`, and `SameSite=Lax` attributes. 184 + - **Server-side enforcement**: RBAC is enforced in route handlers, not just in template rendering. Manipulating the UI cannot bypass access controls. 185 + - **Session lifecycle**: Sessions expire after a configurable TTL. Expired sessions are cleaned up automatically. 186 + - **Opt-in activation**: The admin portal is completely opt-in. If `GATEKEEPER_ADMIN_RBAC_CONFIG` is not set, no admin routes are mounted and the portal is entirely inactive. 187 + 188 + ## Troubleshooting 189 + 190 + **OAuth callback failures** 191 + Ensure HTTPS is properly configured with a valid certificate, DNS resolves correctly for your PDS hostname, and the hostname the user accesses matches the PDS configuration. 192 + 193 + **"Access Denied" after login** 194 + Verify that the DID in your RBAC configuration exactly matches the DID of the authenticating identity. Use `goat resolve {handle}` to confirm the correct DID. 195 + 196 + **Session expired** 197 + Sessions expire after the configured TTL (default 24 hours). Either increase `GATEKEEPER_ADMIN_SESSION_TTL_HOURS` or log in again. 198 + 199 + **403 on admin action** 200 + The authenticated user's roles do not include the endpoint being accessed. Check the `members` and `roles` sections of your RBAC config to ensure the required endpoint pattern is granted. 201 + 202 + **Admin portal not appearing** 203 + Confirm that `GATEKEEPER_ADMIN_RBAC_CONFIG` is set in the environment, the file path is correct, and the file exists and is readable by the gatekeeper process.
+329 -5
Cargo.lock
··· 215 215 ] 216 216 217 217 [[package]] 218 + name = "axum-extra" 219 + version = "0.10.3" 220 + source = "registry+https://github.com/rust-lang/crates.io-index" 221 + checksum = "9963ff19f40c6102c76756ef0a46004c0d58957d87259fc9208ff8441c12ab96" 222 + dependencies = [ 223 + "axum", 224 + "axum-core", 225 + "bytes", 226 + "cookie", 227 + "futures-util", 228 + "http", 229 + "http-body", 230 + "http-body-util", 231 + "mime", 232 + "pin-project-lite", 233 + "rustversion", 234 + "serde_core", 235 + "tower-layer", 236 + "tower-service", 237 + "tracing", 238 + ] 239 + 240 + [[package]] 218 241 name = "axum-macros" 219 242 version = "0.5.0" 220 243 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 552 575 version = "0.4.3" 553 576 source = "registry+https://github.com/rust-lang/crates.io-index" 554 577 checksum = "2f421161cb492475f1661ddc9815a745a1c894592070661180fdec3d4872e9c3" 578 + 579 + [[package]] 580 + name = "cookie" 581 + version = "0.18.1" 582 + source = "registry+https://github.com/rust-lang/crates.io-index" 583 + checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" 584 + dependencies = [ 585 + "base64", 586 + "hmac", 587 + "percent-encoding", 588 + "rand 0.8.5", 589 + "sha2", 590 + "subtle", 591 + "time", 592 + "version_check", 593 + ] 555 594 556 595 [[package]] 557 596 name = "cordyceps" ··· 930 969 checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" 931 970 dependencies = [ 932 971 "base16ct", 972 + "base64ct", 933 973 "crypto-bigint", 934 974 "digest", 935 975 "ff", ··· 939 979 "pkcs8", 940 980 "rand_core 0.6.4", 941 981 "sec1", 982 + "serde_json", 983 + "serdect", 942 984 "subtle", 943 985 "zeroize", 944 986 ] ··· 993 1035 checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" 994 1036 dependencies = [ 995 1037 "libc", 996 - "windows-sys 0.59.0", 1038 + "windows-sys 0.61.2", 997 1039 ] 998 1040 999 1041 [[package]] ··· 1286 1328 "r-efi", 1287 1329 "wasip2", 1288 1330 "wasm-bindgen", 1331 + ] 1332 + 1333 + [[package]] 1334 + name = "getrandom" 1335 + version = "0.4.1" 1336 + source = "registry+https://github.com/rust-lang/crates.io-index" 1337 + checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec" 1338 + dependencies = [ 1339 + "cfg-if", 1340 + "libc", 1341 + "r-efi", 1342 + "wasip2", 1343 + "wasip3", 1289 1344 ] 1290 1345 1291 1346 [[package]] ··· 1740 1795 "zerotrie", 1741 1796 "zerovec", 1742 1797 ] 1798 + 1799 + [[package]] 1800 + name = "id-arena" 1801 + version = "2.3.0" 1802 + source = "registry+https://github.com/rust-lang/crates.io-index" 1803 + checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" 1743 1804 1744 1805 [[package]] 1745 1806 name = "ident_case" ··· 1979 2040 ] 1980 2041 1981 2042 [[package]] 2043 + name = "jacquard-oauth" 2044 + version = "0.9.6" 2045 + source = "registry+https://github.com/rust-lang/crates.io-index" 2046 + checksum = "68bf0b0e061d85b09cfa78588dc098918d5b62f539a719165c6a806a1d2c0ef2" 2047 + dependencies = [ 2048 + "base64", 2049 + "bytes", 2050 + "chrono", 2051 + "dashmap", 2052 + "elliptic-curve", 2053 + "http", 2054 + "jacquard-common", 2055 + "jacquard-identity", 2056 + "jose-jwa", 2057 + "jose-jwk", 2058 + "miette", 2059 + "p256", 2060 + "rand 0.8.5", 2061 + "serde", 2062 + "serde_html_form", 2063 + "serde_json", 2064 + "sha2", 2065 + "smol_str", 2066 + "thiserror 2.0.17", 2067 + "tokio", 2068 + "trait-variant", 2069 + "url", 2070 + ] 2071 + 2072 + [[package]] 1982 2073 name = "jobserver" 1983 2074 version = "0.1.34" 1984 2075 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 1989 2080 ] 1990 2081 1991 2082 [[package]] 2083 + name = "jose-b64" 2084 + version = "0.1.2" 2085 + source = "registry+https://github.com/rust-lang/crates.io-index" 2086 + checksum = "bec69375368709666b21c76965ce67549f2d2db7605f1f8707d17c9656801b56" 2087 + dependencies = [ 2088 + "base64ct", 2089 + "serde", 2090 + "subtle", 2091 + "zeroize", 2092 + ] 2093 + 2094 + [[package]] 2095 + name = "jose-jwa" 2096 + version = "0.1.2" 2097 + source = "registry+https://github.com/rust-lang/crates.io-index" 2098 + checksum = "9ab78e053fe886a351d67cf0d194c000f9d0dcb92906eb34d853d7e758a4b3a7" 2099 + dependencies = [ 2100 + "serde", 2101 + ] 2102 + 2103 + [[package]] 2104 + name = "jose-jwk" 2105 + version = "0.1.2" 2106 + source = "registry+https://github.com/rust-lang/crates.io-index" 2107 + checksum = "280fa263807fe0782ecb6f2baadc28dffc04e00558a58e33bfdb801d11fd58e7" 2108 + dependencies = [ 2109 + "jose-b64", 2110 + "jose-jwa", 2111 + "p256", 2112 + "p384", 2113 + "rsa", 2114 + "serde", 2115 + "zeroize", 2116 + ] 2117 + 2118 + [[package]] 1992 2119 name = "josekit" 1993 2120 version = "0.10.3" 1994 2121 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 2068 2195 dependencies = [ 2069 2196 "spin 0.9.8", 2070 2197 ] 2198 + 2199 + [[package]] 2200 + name = "leb128fmt" 2201 + version = "0.1.0" 2202 + source = "registry+https://github.com/rust-lang/crates.io-index" 2203 + checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" 2071 2204 2072 2205 [[package]] 2073 2206 name = "lettre" ··· 2349 2482 source = "registry+https://github.com/rust-lang/crates.io-index" 2350 2483 checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" 2351 2484 dependencies = [ 2352 - "windows-sys 0.59.0", 2485 + "windows-sys 0.61.2", 2353 2486 ] 2354 2487 2355 2488 [[package]] ··· 2506 2639 "elliptic-curve", 2507 2640 "primeorder", 2508 2641 "sha2", 2642 + ] 2643 + 2644 + [[package]] 2645 + name = "p384" 2646 + version = "0.13.1" 2647 + source = "registry+https://github.com/rust-lang/crates.io-index" 2648 + checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" 2649 + dependencies = [ 2650 + "elliptic-curve", 2651 + "primeorder", 2509 2652 ] 2510 2653 2511 2654 [[package]] ··· 2565 2708 "anyhow", 2566 2709 "aws-lc-rs", 2567 2710 "axum", 2711 + "axum-extra", 2568 2712 "axum-template", 2713 + "base64", 2569 2714 "chrono", 2570 2715 "dashmap", 2571 2716 "dotenvy", ··· 2575 2720 "hyper-util", 2576 2721 "jacquard-common", 2577 2722 "jacquard-identity", 2723 + "jacquard-oauth", 2724 + "jose-jwk", 2578 2725 "josekit", 2579 2726 "jwt-compact", 2580 2727 "lettre", 2581 2728 "multibase", 2729 + "p256", 2582 2730 "rand 0.9.2", 2583 2731 "reqwest", 2584 2732 "rust-embed", ··· 2586 2734 "scrypt", 2587 2735 "serde", 2588 2736 "serde_json", 2737 + "serde_yaml", 2589 2738 "sha2", 2590 2739 "sqlx", 2591 2740 "tokio", ··· 2594 2743 "tower_governor", 2595 2744 "tracing", 2596 2745 "tracing-subscriber", 2746 + "url", 2597 2747 "urlencoding", 2748 + "uuid", 2598 2749 ] 2599 2750 2600 2751 [[package]] ··· 2899 3050 "once_cell", 2900 3051 "socket2", 2901 3052 "tracing", 2902 - "windows-sys 0.59.0", 3053 + "windows-sys 0.60.2", 2903 3054 ] 2904 3055 2905 3056 [[package]] ··· 3331 3482 "der", 3332 3483 "generic-array", 3333 3484 "pkcs8", 3485 + "serdect", 3334 3486 "subtle", 3335 3487 "zeroize", 3336 3488 ] ··· 3510 3662 ] 3511 3663 3512 3664 [[package]] 3665 + name = "serde_yaml" 3666 + version = "0.9.34+deprecated" 3667 + source = "registry+https://github.com/rust-lang/crates.io-index" 3668 + checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" 3669 + dependencies = [ 3670 + "indexmap 2.12.1", 3671 + "itoa", 3672 + "ryu", 3673 + "serde", 3674 + "unsafe-libyaml", 3675 + ] 3676 + 3677 + [[package]] 3678 + name = "serdect" 3679 + version = "0.2.0" 3680 + source = "registry+https://github.com/rust-lang/crates.io-index" 3681 + checksum = "a84f14a19e9a014bb9f4512488d9829a68e04ecabffb0f9904cd1ace94598177" 3682 + dependencies = [ 3683 + "base16ct", 3684 + "serde", 3685 + ] 3686 + 3687 + [[package]] 3513 3688 name = "sha1" 3514 3689 version = "0.10.6" 3515 3690 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 4370 4545 checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" 4371 4546 4372 4547 [[package]] 4548 + name = "unsafe-libyaml" 4549 + version = "0.2.11" 4550 + source = "registry+https://github.com/rust-lang/crates.io-index" 4551 + checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" 4552 + 4553 + [[package]] 4373 4554 name = "unsigned-varint" 4374 4555 version = "0.8.0" 4375 4556 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 4418 4599 checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" 4419 4600 4420 4601 [[package]] 4602 + name = "uuid" 4603 + version = "1.21.0" 4604 + source = "registry+https://github.com/rust-lang/crates.io-index" 4605 + checksum = "b672338555252d43fd2240c714dc444b8c6fb0a5c5335e65a07bba7742735ddb" 4606 + dependencies = [ 4607 + "getrandom 0.4.1", 4608 + "js-sys", 4609 + "wasm-bindgen", 4610 + ] 4611 + 4612 + [[package]] 4421 4613 name = "valuable" 4422 4614 version = "0.1.1" 4423 4615 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 4466 4658 source = "registry+https://github.com/rust-lang/crates.io-index" 4467 4659 checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" 4468 4660 dependencies = [ 4469 - "wit-bindgen", 4661 + "wit-bindgen 0.46.0", 4662 + ] 4663 + 4664 + [[package]] 4665 + name = "wasip3" 4666 + version = "0.4.0+wasi-0.3.0-rc-2026-01-06" 4667 + source = "registry+https://github.com/rust-lang/crates.io-index" 4668 + checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" 4669 + dependencies = [ 4670 + "wit-bindgen 0.51.0", 4470 4671 ] 4471 4672 4472 4673 [[package]] ··· 4534 4735 ] 4535 4736 4536 4737 [[package]] 4738 + name = "wasm-encoder" 4739 + version = "0.244.0" 4740 + source = "registry+https://github.com/rust-lang/crates.io-index" 4741 + checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" 4742 + dependencies = [ 4743 + "leb128fmt", 4744 + "wasmparser", 4745 + ] 4746 + 4747 + [[package]] 4748 + name = "wasm-metadata" 4749 + version = "0.244.0" 4750 + source = "registry+https://github.com/rust-lang/crates.io-index" 4751 + checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" 4752 + dependencies = [ 4753 + "anyhow", 4754 + "indexmap 2.12.1", 4755 + "wasm-encoder", 4756 + "wasmparser", 4757 + ] 4758 + 4759 + [[package]] 4760 + name = "wasmparser" 4761 + version = "0.244.0" 4762 + source = "registry+https://github.com/rust-lang/crates.io-index" 4763 + checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" 4764 + dependencies = [ 4765 + "bitflags", 4766 + "hashbrown 0.15.5", 4767 + "indexmap 2.12.1", 4768 + "semver", 4769 + ] 4770 + 4771 + [[package]] 4537 4772 name = "web-sys" 4538 4773 version = "0.3.83" 4539 4774 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 4603 4838 source = "registry+https://github.com/rust-lang/crates.io-index" 4604 4839 checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" 4605 4840 dependencies = [ 4606 - "windows-sys 0.48.0", 4841 + "windows-sys 0.61.2", 4607 4842 ] 4608 4843 4609 4844 [[package]] ··· 4920 5155 checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" 4921 5156 4922 5157 [[package]] 5158 + name = "wit-bindgen" 5159 + version = "0.51.0" 5160 + source = "registry+https://github.com/rust-lang/crates.io-index" 5161 + checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" 5162 + dependencies = [ 5163 + "wit-bindgen-rust-macro", 5164 + ] 5165 + 5166 + [[package]] 5167 + name = "wit-bindgen-core" 5168 + version = "0.51.0" 5169 + source = "registry+https://github.com/rust-lang/crates.io-index" 5170 + checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" 5171 + dependencies = [ 5172 + "anyhow", 5173 + "heck 0.5.0", 5174 + "wit-parser", 5175 + ] 5176 + 5177 + [[package]] 5178 + name = "wit-bindgen-rust" 5179 + version = "0.51.0" 5180 + source = "registry+https://github.com/rust-lang/crates.io-index" 5181 + checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" 5182 + dependencies = [ 5183 + "anyhow", 5184 + "heck 0.5.0", 5185 + "indexmap 2.12.1", 5186 + "prettyplease", 5187 + "syn 2.0.112", 5188 + "wasm-metadata", 5189 + "wit-bindgen-core", 5190 + "wit-component", 5191 + ] 5192 + 5193 + [[package]] 5194 + name = "wit-bindgen-rust-macro" 5195 + version = "0.51.0" 5196 + source = "registry+https://github.com/rust-lang/crates.io-index" 5197 + checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" 5198 + dependencies = [ 5199 + "anyhow", 5200 + "prettyplease", 5201 + "proc-macro2", 5202 + "quote", 5203 + "syn 2.0.112", 5204 + "wit-bindgen-core", 5205 + "wit-bindgen-rust", 5206 + ] 5207 + 5208 + [[package]] 5209 + name = "wit-component" 5210 + version = "0.244.0" 5211 + source = "registry+https://github.com/rust-lang/crates.io-index" 5212 + checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" 5213 + dependencies = [ 5214 + "anyhow", 5215 + "bitflags", 5216 + "indexmap 2.12.1", 5217 + "log", 5218 + "serde", 5219 + "serde_derive", 5220 + "serde_json", 5221 + "wasm-encoder", 5222 + "wasm-metadata", 5223 + "wasmparser", 5224 + "wit-parser", 5225 + ] 5226 + 5227 + [[package]] 5228 + name = "wit-parser" 5229 + version = "0.244.0" 5230 + source = "registry+https://github.com/rust-lang/crates.io-index" 5231 + checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" 5232 + dependencies = [ 5233 + "anyhow", 5234 + "id-arena", 5235 + "indexmap 2.12.1", 5236 + "log", 5237 + "semver", 5238 + "serde", 5239 + "serde_derive", 5240 + "serde_json", 5241 + "unicode-xid", 5242 + "wasmparser", 5243 + ] 5244 + 5245 + [[package]] 4923 5246 name = "writeable" 4924 5247 version = "0.6.2" 4925 5248 source = "registry+https://github.com/rust-lang/crates.io-index" ··· 5001 5324 source = "registry+https://github.com/rust-lang/crates.io-index" 5002 5325 checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" 5003 5326 dependencies = [ 5327 + "serde", 5004 5328 "zeroize_derive", 5005 5329 ] 5006 5330
+8
Cargo.toml
··· 39 39 josekit = "0.10.3" 40 40 dashmap = "6.1" 41 41 tower = "0.5" 42 + serde_yaml = "0.9" 43 + jacquard-oauth = "0.9.6" 44 + axum-extra = { version = "0.10", features = ["cookie-signed"] } 45 + uuid = { version = "1", features = ["v4"] } 46 + p256 = { version = "0.13", features = ["ecdsa", "jwk"] } 47 + jose-jwk = { version = "0.1", features = ["p256"] } 48 + base64 = "0.22" 49 + url = "2"
+67
examples/admin_rbac.yaml
··· 1 + # PDS Admin Team — Role-Based Access Control 2 + # 3 + # This file defines which ATProto identities can perform admin operations 4 + # through pds-gatekeeper's admin portal. Each member authenticates via 5 + # ATProto OAuth (using their Bluesky/AT Protocol identity) and is granted 6 + # access only to the endpoints their roles permit. 7 + # 8 + # Endpoint patterns: 9 + # - Exact match: "com.atproto.admin.getAccountInfo" 10 + # - Wildcard: "com.atproto.admin.*" (matches all admin endpoints) 11 + # 12 + # Usage: 13 + # 1. Copy this file and customize for your team 14 + # 2. Set GATEKEEPER_ADMIN_RBAC_CONFIG=/path/to/your/admin_rbac.yaml 15 + # 3. Set PDS_ADMIN_PASSWORD=your-pds-admin-password 16 + # 4. Restart pds-gatekeeper 17 + # 5. Navigate to https://your-pds.example.com/admin/login 18 + 19 + roles: 20 + pds-admin: 21 + description: "Full PDS administrator — all admin endpoints + account/invite creation" 22 + endpoints: 23 + - "com.atproto.admin.*" 24 + - "com.atproto.server.createInviteCode" 25 + - "com.atproto.server.createInviteCodes" 26 + - "com.atproto.server.createAccount" 27 + 28 + moderator: 29 + description: "Content moderation — view accounts, manage takedowns and subject status" 30 + endpoints: 31 + - "com.atproto.admin.getAccountInfo" 32 + - "com.atproto.admin.getAccountInfos" 33 + - "com.atproto.admin.getSubjectStatus" 34 + - "com.atproto.admin.updateSubjectStatus" 35 + - "com.atproto.admin.sendEmail" 36 + - "com.atproto.admin.searchAccounts" 37 + - "com.atproto.admin.getInviteCodes" 38 + 39 + invite-manager: 40 + description: "Invite code management — create and manage invite codes" 41 + endpoints: 42 + - "com.atproto.admin.getInviteCodes" 43 + - "com.atproto.admin.disableInviteCodes" 44 + - "com.atproto.admin.enableAccountInvites" 45 + - "com.atproto.admin.disableAccountInvites" 46 + - "com.atproto.server.createInviteCode" 47 + - "com.atproto.server.createInviteCodes" 48 + 49 + members: 50 + # Replace these with your team members' DIDs. 51 + # Resolve a handle to its DID with: goat resolve {handle} 52 + 53 + # Example: Full admin 54 + - did: "did:plc:your-admin-did-here" 55 + roles: 56 + - pds-admin 57 + 58 + # Example: Moderator only 59 + - did: "did:plc:your-moderator-did-here" 60 + roles: 61 + - moderator 62 + 63 + # Example: Someone with both moderator and invite manager roles 64 + - did: "did:plc:your-team-member-did-here" 65 + roles: 66 + - moderator 67 + - invite-manager
+490
html_templates/admin/account_detail.hbs
··· 1 + <!DOCTYPE html> 2 + <html lang="en"> 3 + <head> 4 + <meta charset="utf-8"/> 5 + <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, viewport-fit=cover"/> 6 + <meta name="referrer" content="origin-when-cross-origin"/> 7 + <title>{{account.handle}} - {{pds_hostname}}</title> 8 + <style> 9 + :root, 10 + :root.light-mode { 11 + --brand-color: rgb(16, 131, 254); 12 + --primary-color: rgb(7, 10, 13); 13 + --secondary-color: rgb(66, 86, 108); 14 + --bg-primary-color: rgb(255, 255, 255); 15 + --bg-secondary-color: rgb(240, 242, 245); 16 + --border-color: rgb(220, 225, 230); 17 + --danger-color: rgb(220, 38, 38); 18 + --success-color: rgb(22, 163, 74); 19 + --warning-color: rgb(234, 179, 8); 20 + --table-stripe: rgba(0, 0, 0, 0.02); 21 + } 22 + 23 + @media (prefers-color-scheme: dark) { 24 + :root { 25 + --brand-color: rgb(16, 131, 254); 26 + --primary-color: rgb(255, 255, 255); 27 + --secondary-color: rgb(133, 152, 173); 28 + --bg-primary-color: rgb(7, 10, 13); 29 + --bg-secondary-color: rgb(13, 18, 23); 30 + --border-color: rgb(40, 45, 55); 31 + --table-stripe: rgba(255, 255, 255, 0.02); 32 + } 33 + } 34 + 35 + :root.dark-mode { 36 + --brand-color: rgb(16, 131, 254); 37 + --primary-color: rgb(255, 255, 255); 38 + --secondary-color: rgb(133, 152, 173); 39 + --bg-primary-color: rgb(7, 10, 13); 40 + --bg-secondary-color: rgb(13, 18, 23); 41 + --border-color: rgb(40, 45, 55); 42 + --table-stripe: rgba(255, 255, 255, 0.02); 43 + } 44 + 45 + * { margin: 0; padding: 0; box-sizing: border-box; } 46 + 47 + body { 48 + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; 49 + background: var(--bg-secondary-color); 50 + color: var(--primary-color); 51 + text-rendering: optimizeLegibility; 52 + -webkit-font-smoothing: antialiased; 53 + } 54 + 55 + .layout { display: flex; min-height: 100vh; } 56 + 57 + .sidebar { 58 + width: 220px; 59 + background: var(--bg-primary-color); 60 + border-right: 1px solid var(--border-color); 61 + padding: 20px 0; 62 + position: fixed; 63 + top: 0; left: 0; bottom: 0; 64 + overflow-y: auto; 65 + display: flex; 66 + flex-direction: column; 67 + } 68 + 69 + .sidebar-title { 70 + font-size: 0.8125rem; 71 + font-weight: 700; 72 + padding: 0 20px; 73 + margin-bottom: 4px; 74 + white-space: nowrap; 75 + overflow: hidden; 76 + text-overflow: ellipsis; 77 + } 78 + 79 + .sidebar-subtitle { 80 + font-size: 0.6875rem; 81 + color: var(--secondary-color); 82 + padding: 0 20px; 83 + margin-bottom: 20px; 84 + } 85 + 86 + .sidebar nav { flex: 1; } 87 + 88 + .sidebar nav a { 89 + display: block; 90 + padding: 8px 20px; 91 + font-size: 0.8125rem; 92 + color: var(--secondary-color); 93 + text-decoration: none; 94 + transition: background 0.1s, color 0.1s; 95 + } 96 + 97 + .sidebar nav a:hover { 98 + background: var(--bg-secondary-color); 99 + color: var(--primary-color); 100 + } 101 + 102 + .sidebar nav a.active { 103 + color: var(--brand-color); 104 + font-weight: 500; 105 + } 106 + 107 + .sidebar-footer { 108 + padding: 16px 20px 0; 109 + border-top: 1px solid var(--border-color); 110 + margin-top: 16px; 111 + } 112 + 113 + .sidebar-footer .session-info { 114 + font-size: 0.75rem; 115 + color: var(--secondary-color); 116 + margin-bottom: 8px; 117 + } 118 + 119 + .sidebar-footer form { display: inline; } 120 + 121 + .sidebar-footer button { 122 + background: none; 123 + border: none; 124 + font-size: 0.75rem; 125 + color: var(--secondary-color); 126 + cursor: pointer; 127 + padding: 0; 128 + text-decoration: underline; 129 + } 130 + 131 + .sidebar-footer button:hover { color: var(--primary-color); } 132 + 133 + .main { 134 + margin-left: 220px; 135 + flex: 1; 136 + padding: 32px; 137 + max-width: 960px; 138 + } 139 + 140 + .page-title { 141 + font-size: 1.5rem; 142 + font-weight: 700; 143 + margin-bottom: 4px; 144 + } 145 + 146 + .page-subtitle { 147 + font-size: 0.8125rem; 148 + color: var(--secondary-color); 149 + font-family: 'SF Mono', SFMono-Regular, Menlo, Consolas, monospace; 150 + margin-bottom: 24px; 151 + word-break: break-all; 152 + } 153 + 154 + .flash-success { 155 + background: rgba(22, 163, 74, 0.1); 156 + color: var(--success-color); 157 + border: 1px solid rgba(22, 163, 74, 0.2); 158 + border-radius: 8px; 159 + padding: 10px 14px; 160 + font-size: 0.875rem; 161 + margin-bottom: 20px; 162 + } 163 + 164 + .flash-error { 165 + background: rgba(220, 38, 38, 0.1); 166 + color: var(--danger-color); 167 + border: 1px solid rgba(220, 38, 38, 0.2); 168 + border-radius: 8px; 169 + padding: 10px 14px; 170 + font-size: 0.875rem; 171 + margin-bottom: 20px; 172 + } 173 + 174 + .detail-section { 175 + background: var(--bg-primary-color); 176 + border: 1px solid var(--border-color); 177 + border-radius: 10px; 178 + padding: 20px; 179 + margin-bottom: 16px; 180 + } 181 + 182 + .detail-section h3 { 183 + font-size: 0.875rem; 184 + font-weight: 600; 185 + margin-bottom: 12px; 186 + } 187 + 188 + .detail-row { 189 + display: flex; 190 + justify-content: space-between; 191 + align-items: center; 192 + padding: 8px 0; 193 + font-size: 0.8125rem; 194 + border-bottom: 1px solid var(--border-color); 195 + } 196 + 197 + .detail-row:last-child { 198 + border-bottom: none; 199 + } 200 + 201 + .detail-row .label { 202 + color: var(--secondary-color); 203 + flex-shrink: 0; 204 + } 205 + 206 + .detail-row .value { 207 + font-weight: 500; 208 + word-break: break-all; 209 + text-align: right; 210 + max-width: 65%; 211 + } 212 + 213 + .badge { 214 + display: inline-block; 215 + padding: 2px 8px; 216 + border-radius: 4px; 217 + font-size: 0.75rem; 218 + font-weight: 500; 219 + } 220 + 221 + .badge-success { 222 + background: rgba(22, 163, 74, 0.1); 223 + color: var(--success-color); 224 + } 225 + 226 + .badge-danger { 227 + background: rgba(220, 38, 38, 0.1); 228 + color: var(--danger-color); 229 + } 230 + 231 + .badge-warning { 232 + background: rgba(234, 179, 8, 0.1); 233 + color: var(--warning-color); 234 + } 235 + 236 + .actions { 237 + display: flex; 238 + flex-wrap: wrap; 239 + gap: 8px; 240 + margin-top: 8px; 241 + } 242 + 243 + .actions form { 244 + display: inline; 245 + } 246 + 247 + .btn { 248 + display: inline-flex; 249 + align-items: center; 250 + justify-content: center; 251 + padding: 8px 16px; 252 + font-size: 0.8125rem; 253 + font-weight: 500; 254 + border: 1px solid var(--border-color); 255 + border-radius: 8px; 256 + cursor: pointer; 257 + transition: opacity 0.15s; 258 + text-decoration: none; 259 + background: var(--bg-primary-color); 260 + color: var(--primary-color); 261 + } 262 + 263 + .btn:hover { opacity: 0.85; } 264 + 265 + .btn-primary { 266 + background: var(--brand-color); 267 + color: #fff; 268 + border-color: var(--brand-color); 269 + } 270 + 271 + .btn-danger { 272 + background: var(--danger-color); 273 + color: #fff; 274 + border-color: var(--danger-color); 275 + } 276 + 277 + .btn-warning { 278 + background: var(--warning-color); 279 + color: #000; 280 + border-color: var(--warning-color); 281 + } 282 + 283 + .password-box { 284 + background: rgba(22, 163, 74, 0.08); 285 + border: 1px solid rgba(22, 163, 74, 0.2); 286 + border-radius: 10px; 287 + padding: 16px 20px; 288 + margin-bottom: 16px; 289 + } 290 + 291 + .password-box .pw-label { 292 + font-size: 0.75rem; 293 + font-weight: 600; 294 + color: var(--success-color); 295 + margin-bottom: 6px; 296 + } 297 + 298 + .password-box .pw-value { 299 + font-family: 'SF Mono', SFMono-Regular, Menlo, Consolas, monospace; 300 + font-size: 1rem; 301 + font-weight: 600; 302 + user-select: all; 303 + } 304 + 305 + .back-link { 306 + display: inline-block; 307 + color: var(--brand-color); 308 + text-decoration: none; 309 + font-size: 0.8125rem; 310 + margin-bottom: 16px; 311 + } 312 + 313 + .back-link:hover { text-decoration: underline; } 314 + 315 + @media (max-width: 768px) { 316 + .sidebar { display: none; } 317 + .main { margin-left: 0; } 318 + } 319 + </style> 320 + </head> 321 + <body> 322 + <div class="layout"> 323 + <aside class="sidebar"> 324 + <div class="sidebar-title">{{pds_hostname}}</div> 325 + <div class="sidebar-subtitle">Admin Portal</div> 326 + <nav> 327 + <a href="/admin/">Dashboard</a> 328 + <a href="/admin/accounts" class="active">Accounts</a> 329 + {{#if can_manage_invites}} 330 + <a href="/admin/invite-codes">Invite Codes</a> 331 + {{/if}} 332 + {{#if can_create_account}} 333 + <a href="/admin/create-account">Create Account</a> 334 + {{/if}} 335 + </nav> 336 + <div class="sidebar-footer"> 337 + <div class="session-info">Signed in as {{handle}}</div> 338 + <form method="POST" action="/admin/logout"> 339 + <button type="submit">Sign out</button> 340 + </form> 341 + </div> 342 + </aside> 343 + 344 + <main class="main"> 345 + {{#if flash_success}} 346 + <div class="flash-success">{{flash_success}}</div> 347 + {{/if}} 348 + {{#if flash_error}} 349 + <div class="flash-error">{{flash_error}}</div> 350 + {{/if}} 351 + 352 + <a href="/admin/accounts" class="back-link">&larr; Back to Accounts</a> 353 + 354 + <h1 class="page-title">{{account.handle}}</h1> 355 + <div class="page-subtitle">{{account.did}}</div> 356 + 357 + {{#if new_password}} 358 + <div class="password-box"> 359 + <div class="pw-label">New Password (copy now -- it will not be shown again)</div> 360 + <div class="pw-value">{{new_password}}</div> 361 + </div> 362 + {{/if}} 363 + 364 + <div class="detail-section"> 365 + <h3>Account Information</h3> 366 + <div class="detail-row"> 367 + <span class="label">Handle</span> 368 + <span class="value">{{account.handle}}</span> 369 + </div> 370 + <div class="detail-row"> 371 + <span class="label">DID</span> 372 + <span class="value">{{account.did}}</span> 373 + </div> 374 + <div class="detail-row"> 375 + <span class="label">Email</span> 376 + <span class="value">{{account.email}}</span> 377 + </div> 378 + {{#if account.indexedAt}} 379 + <div class="detail-row"> 380 + <span class="label">Indexed At</span> 381 + <span class="value">{{account.indexedAt}}</span> 382 + </div> 383 + {{/if}} 384 + </div> 385 + 386 + <div class="detail-section"> 387 + <h3>Status</h3> 388 + <div class="detail-row"> 389 + <span class="label">Takedown</span> 390 + <span class="value"> 391 + {{#if account.takendown}} 392 + <span class="badge badge-danger">Taken Down</span> 393 + {{else}} 394 + <span class="badge badge-success">Active</span> 395 + {{/if}} 396 + </span> 397 + </div> 398 + <div class="detail-row"> 399 + <span class="label">Email Confirmed</span> 400 + <span class="value"> 401 + {{#if account.emailConfirmedAt}} 402 + <span class="badge badge-success">Confirmed</span> 403 + {{else}} 404 + <span class="badge badge-warning">Unconfirmed</span> 405 + {{/if}} 406 + </span> 407 + </div> 408 + <div class="detail-row"> 409 + <span class="label">Deactivated</span> 410 + <span class="value"> 411 + {{#if account.deactivatedAt}} 412 + <span class="badge badge-warning">{{account.deactivatedAt}}</span> 413 + {{else}} 414 + <span class="badge badge-success">No</span> 415 + {{/if}} 416 + </span> 417 + </div> 418 + </div> 419 + 420 + <div class="detail-section"> 421 + <h3>Invite Information</h3> 422 + {{#if account.invitedBy}} 423 + <div class="detail-row"> 424 + <span class="label">Invited By</span> 425 + <span class="value">{{account.invitedBy}}</span> 426 + </div> 427 + {{/if}} 428 + <div class="detail-row"> 429 + <span class="label">Invites Disabled</span> 430 + <span class="value"> 431 + {{#if account.invitesDisabled}} 432 + <span class="badge badge-danger">Yes</span> 433 + {{else}} 434 + <span class="badge badge-success">No</span> 435 + {{/if}} 436 + </span> 437 + </div> 438 + {{#if account.inviteNote}} 439 + <div class="detail-row"> 440 + <span class="label">Invite Note</span> 441 + <span class="value">{{account.inviteNote}}</span> 442 + </div> 443 + {{/if}} 444 + </div> 445 + 446 + <div class="detail-section"> 447 + <h3>Actions</h3> 448 + <div class="actions"> 449 + {{#if can_manage_takedowns}} 450 + {{#if account.takendown}} 451 + <form method="POST" action="/admin/accounts/{{account.did}}/untakedown"> 452 + <button type="submit" class="btn btn-primary">Remove Takedown</button> 453 + </form> 454 + {{else}} 455 + <form method="POST" action="/admin/accounts/{{account.did}}/takedown"> 456 + <button type="submit" class="btn btn-warning">Takedown Account</button> 457 + </form> 458 + {{/if}} 459 + {{/if}} 460 + 461 + {{#if can_reset_password}} 462 + <form method="POST" action="/admin/accounts/{{account.did}}/reset-password" onsubmit="return confirm('Are you sure you want to reset this account password? The current password will be invalidated.');"> 463 + <button type="submit" class="btn">Reset Password</button> 464 + </form> 465 + {{/if}} 466 + 467 + {{#if can_manage_invites}} 468 + {{#if account.invitesDisabled}} 469 + <form method="POST" action="/admin/accounts/{{account.did}}/enable-invites"> 470 + <button type="submit" class="btn">Enable Invites</button> 471 + </form> 472 + {{else}} 473 + <form method="POST" action="/admin/accounts/{{account.did}}/disable-invites"> 474 + <button type="submit" class="btn">Disable Invites</button> 475 + </form> 476 + {{/if}} 477 + {{/if}} 478 + 479 + {{#if can_delete_account}} 480 + <form method="POST" action="/admin/accounts/{{account.did}}/delete" onsubmit="return confirm('PERMANENTLY DELETE this account? This action cannot be undone.');"> 481 + <button type="submit" class="btn btn-danger">Delete Account</button> 482 + </form> 483 + {{/if}} 484 + </div> 485 + </div> 486 + </main> 487 + </div> 488 + 489 + </body> 490 + </html>
+347
html_templates/admin/accounts.hbs
··· 1 + <!DOCTYPE html> 2 + <html lang="en"> 3 + <head> 4 + <meta charset="utf-8"/> 5 + <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, viewport-fit=cover"/> 6 + <meta name="referrer" content="origin-when-cross-origin"/> 7 + <title>Accounts - {{pds_hostname}}</title> 8 + <style> 9 + :root, 10 + :root.light-mode { 11 + --brand-color: rgb(16, 131, 254); 12 + --primary-color: rgb(7, 10, 13); 13 + --secondary-color: rgb(66, 86, 108); 14 + --bg-primary-color: rgb(255, 255, 255); 15 + --bg-secondary-color: rgb(240, 242, 245); 16 + --border-color: rgb(220, 225, 230); 17 + --danger-color: rgb(220, 38, 38); 18 + --success-color: rgb(22, 163, 74); 19 + --warning-color: rgb(234, 179, 8); 20 + --table-stripe: rgba(0, 0, 0, 0.02); 21 + } 22 + 23 + @media (prefers-color-scheme: dark) { 24 + :root { 25 + --brand-color: rgb(16, 131, 254); 26 + --primary-color: rgb(255, 255, 255); 27 + --secondary-color: rgb(133, 152, 173); 28 + --bg-primary-color: rgb(7, 10, 13); 29 + --bg-secondary-color: rgb(13, 18, 23); 30 + --border-color: rgb(40, 45, 55); 31 + --table-stripe: rgba(255, 255, 255, 0.02); 32 + } 33 + } 34 + 35 + :root.dark-mode { 36 + --brand-color: rgb(16, 131, 254); 37 + --primary-color: rgb(255, 255, 255); 38 + --secondary-color: rgb(133, 152, 173); 39 + --bg-primary-color: rgb(7, 10, 13); 40 + --bg-secondary-color: rgb(13, 18, 23); 41 + --border-color: rgb(40, 45, 55); 42 + --table-stripe: rgba(255, 255, 255, 0.02); 43 + } 44 + 45 + * { margin: 0; padding: 0; box-sizing: border-box; } 46 + 47 + body { 48 + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; 49 + background: var(--bg-secondary-color); 50 + color: var(--primary-color); 51 + text-rendering: optimizeLegibility; 52 + -webkit-font-smoothing: antialiased; 53 + } 54 + 55 + .layout { display: flex; min-height: 100vh; } 56 + 57 + .sidebar { 58 + width: 220px; 59 + background: var(--bg-primary-color); 60 + border-right: 1px solid var(--border-color); 61 + padding: 20px 0; 62 + position: fixed; 63 + top: 0; left: 0; bottom: 0; 64 + overflow-y: auto; 65 + display: flex; 66 + flex-direction: column; 67 + } 68 + 69 + .sidebar-title { 70 + font-size: 0.8125rem; 71 + font-weight: 700; 72 + padding: 0 20px; 73 + margin-bottom: 4px; 74 + white-space: nowrap; 75 + overflow: hidden; 76 + text-overflow: ellipsis; 77 + } 78 + 79 + .sidebar-subtitle { 80 + font-size: 0.6875rem; 81 + color: var(--secondary-color); 82 + padding: 0 20px; 83 + margin-bottom: 20px; 84 + } 85 + 86 + .sidebar nav { flex: 1; } 87 + 88 + .sidebar nav a { 89 + display: block; 90 + padding: 8px 20px; 91 + font-size: 0.8125rem; 92 + color: var(--secondary-color); 93 + text-decoration: none; 94 + transition: background 0.1s, color 0.1s; 95 + } 96 + 97 + .sidebar nav a:hover { 98 + background: var(--bg-secondary-color); 99 + color: var(--primary-color); 100 + } 101 + 102 + .sidebar nav a.active { 103 + color: var(--brand-color); 104 + font-weight: 500; 105 + } 106 + 107 + .sidebar-footer { 108 + padding: 16px 20px 0; 109 + border-top: 1px solid var(--border-color); 110 + margin-top: 16px; 111 + } 112 + 113 + .sidebar-footer .session-info { 114 + font-size: 0.75rem; 115 + color: var(--secondary-color); 116 + margin-bottom: 8px; 117 + } 118 + 119 + .sidebar-footer form { display: inline; } 120 + 121 + .sidebar-footer button { 122 + background: none; 123 + border: none; 124 + font-size: 0.75rem; 125 + color: var(--secondary-color); 126 + cursor: pointer; 127 + padding: 0; 128 + text-decoration: underline; 129 + } 130 + 131 + .sidebar-footer button:hover { color: var(--primary-color); } 132 + 133 + .main { 134 + margin-left: 220px; 135 + flex: 1; 136 + padding: 32px; 137 + max-width: 960px; 138 + } 139 + 140 + .page-title { 141 + font-size: 1.5rem; 142 + font-weight: 700; 143 + margin-bottom: 24px; 144 + } 145 + 146 + .flash-success { 147 + background: rgba(22, 163, 74, 0.1); 148 + color: var(--success-color); 149 + border: 1px solid rgba(22, 163, 74, 0.2); 150 + border-radius: 8px; 151 + padding: 10px 14px; 152 + font-size: 0.875rem; 153 + margin-bottom: 20px; 154 + } 155 + 156 + .flash-error { 157 + background: rgba(220, 38, 38, 0.1); 158 + color: var(--danger-color); 159 + border: 1px solid rgba(220, 38, 38, 0.2); 160 + border-radius: 8px; 161 + padding: 10px 14px; 162 + font-size: 0.875rem; 163 + margin-bottom: 20px; 164 + } 165 + 166 + .search-form { 167 + display: flex; 168 + gap: 8px; 169 + margin-bottom: 24px; 170 + } 171 + 172 + .search-form input { 173 + flex: 1; 174 + padding: 10px 12px; 175 + font-size: 0.875rem; 176 + border: 1px solid var(--border-color); 177 + border-radius: 8px; 178 + background: var(--bg-primary-color); 179 + color: var(--primary-color); 180 + outline: none; 181 + } 182 + 183 + .search-form input:focus { 184 + border-color: var(--brand-color); 185 + } 186 + 187 + .btn { 188 + display: inline-flex; 189 + align-items: center; 190 + justify-content: center; 191 + padding: 10px 20px; 192 + font-size: 0.875rem; 193 + font-weight: 500; 194 + border: none; 195 + border-radius: 8px; 196 + cursor: pointer; 197 + transition: opacity 0.15s; 198 + text-decoration: none; 199 + } 200 + 201 + .btn:hover { opacity: 0.85; } 202 + 203 + .btn-primary { 204 + background: var(--brand-color); 205 + color: #fff; 206 + } 207 + 208 + .table-container { 209 + background: var(--bg-primary-color); 210 + border: 1px solid var(--border-color); 211 + border-radius: 10px; 212 + overflow: hidden; 213 + } 214 + 215 + table { 216 + width: 100%; 217 + border-collapse: collapse; 218 + } 219 + 220 + thead th { 221 + text-align: left; 222 + padding: 12px 16px; 223 + font-size: 0.75rem; 224 + font-weight: 600; 225 + color: var(--secondary-color); 226 + text-transform: uppercase; 227 + letter-spacing: 0.5px; 228 + border-bottom: 1px solid var(--border-color); 229 + } 230 + 231 + tbody tr { 232 + border-bottom: 1px solid var(--border-color); 233 + } 234 + 235 + tbody tr:last-child { 236 + border-bottom: none; 237 + } 238 + 239 + tbody tr:nth-child(even) { 240 + background: var(--table-stripe); 241 + } 242 + 243 + tbody td { 244 + padding: 10px 16px; 245 + font-size: 0.8125rem; 246 + } 247 + 248 + tbody td a { 249 + color: var(--brand-color); 250 + text-decoration: none; 251 + } 252 + 253 + tbody td a:hover { 254 + text-decoration: underline; 255 + } 256 + 257 + .empty-state { 258 + text-align: center; 259 + padding: 40px 20px; 260 + color: var(--secondary-color); 261 + font-size: 0.875rem; 262 + } 263 + 264 + .did-cell { 265 + font-family: 'SF Mono', SFMono-Regular, Menlo, Consolas, monospace; 266 + font-size: 0.75rem; 267 + color: var(--secondary-color); 268 + } 269 + 270 + @media (max-width: 768px) { 271 + .sidebar { display: none; } 272 + .main { margin-left: 0; } 273 + } 274 + </style> 275 + </head> 276 + <body> 277 + <div class="layout"> 278 + <aside class="sidebar"> 279 + <div class="sidebar-title">{{pds_hostname}}</div> 280 + <div class="sidebar-subtitle">Admin Portal</div> 281 + <nav> 282 + <a href="/admin/">Dashboard</a> 283 + <a href="/admin/accounts" class="active">Accounts</a> 284 + {{#if can_manage_invites}} 285 + <a href="/admin/invite-codes">Invite Codes</a> 286 + {{/if}} 287 + {{#if can_create_account}} 288 + <a href="/admin/create-account">Create Account</a> 289 + {{/if}} 290 + </nav> 291 + <div class="sidebar-footer"> 292 + <div class="session-info">Signed in as {{handle}}</div> 293 + <form method="POST" action="/admin/logout"> 294 + <button type="submit">Sign out</button> 295 + </form> 296 + </div> 297 + </aside> 298 + 299 + <main class="main"> 300 + {{#if flash_success}} 301 + <div class="flash-success">{{flash_success}}</div> 302 + {{/if}} 303 + {{#if flash_error}} 304 + <div class="flash-error">{{flash_error}}</div> 305 + {{/if}} 306 + 307 + <h1 class="page-title">Accounts</h1> 308 + 309 + <form class="search-form" method="GET" action="/admin/search"> 310 + <input type="text" name="q" placeholder="Search by handle or DID..." value="{{query}}" /> 311 + <button type="submit" class="btn btn-primary">Search</button> 312 + </form> 313 + 314 + {{#if accounts}} 315 + <div class="table-container"> 316 + <table> 317 + <thead> 318 + <tr> 319 + <th>Handle</th> 320 + <th>DID</th> 321 + <th>Email</th> 322 + </tr> 323 + </thead> 324 + <tbody> 325 + {{#each accounts}} 326 + <tr> 327 + <td><a href="/admin/accounts/{{this.did}}">{{this.handle}}</a></td> 328 + <td class="did-cell">{{this.did}}</td> 329 + <td>{{this.email}}</td> 330 + </tr> 331 + {{/each}} 332 + </tbody> 333 + </table> 334 + </div> 335 + {{else}} 336 + <div class="empty-state"> 337 + {{#if query}} 338 + No accounts matching "{{query}}" 339 + {{else}} 340 + No accounts found 341 + {{/if}} 342 + </div> 343 + {{/if}} 344 + </main> 345 + </div> 346 + </body> 347 + </html>
+359
html_templates/admin/create_account.hbs
··· 1 + <!DOCTYPE html> 2 + <html lang="en"> 3 + <head> 4 + <meta charset="utf-8"/> 5 + <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, viewport-fit=cover"/> 6 + <meta name="referrer" content="origin-when-cross-origin"/> 7 + <title>Create Account - {{pds_hostname}}</title> 8 + <style> 9 + :root, 10 + :root.light-mode { 11 + --brand-color: rgb(16, 131, 254); 12 + --primary-color: rgb(7, 10, 13); 13 + --secondary-color: rgb(66, 86, 108); 14 + --bg-primary-color: rgb(255, 255, 255); 15 + --bg-secondary-color: rgb(240, 242, 245); 16 + --border-color: rgb(220, 225, 230); 17 + --danger-color: rgb(220, 38, 38); 18 + --success-color: rgb(22, 163, 74); 19 + --warning-color: rgb(234, 179, 8); 20 + --table-stripe: rgba(0, 0, 0, 0.02); 21 + } 22 + 23 + @media (prefers-color-scheme: dark) { 24 + :root { 25 + --brand-color: rgb(16, 131, 254); 26 + --primary-color: rgb(255, 255, 255); 27 + --secondary-color: rgb(133, 152, 173); 28 + --bg-primary-color: rgb(7, 10, 13); 29 + --bg-secondary-color: rgb(13, 18, 23); 30 + --border-color: rgb(40, 45, 55); 31 + --table-stripe: rgba(255, 255, 255, 0.02); 32 + } 33 + } 34 + 35 + :root.dark-mode { 36 + --brand-color: rgb(16, 131, 254); 37 + --primary-color: rgb(255, 255, 255); 38 + --secondary-color: rgb(133, 152, 173); 39 + --bg-primary-color: rgb(7, 10, 13); 40 + --bg-secondary-color: rgb(13, 18, 23); 41 + --border-color: rgb(40, 45, 55); 42 + --table-stripe: rgba(255, 255, 255, 0.02); 43 + } 44 + 45 + * { margin: 0; padding: 0; box-sizing: border-box; } 46 + 47 + body { 48 + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; 49 + background: var(--bg-secondary-color); 50 + color: var(--primary-color); 51 + text-rendering: optimizeLegibility; 52 + -webkit-font-smoothing: antialiased; 53 + } 54 + 55 + .layout { display: flex; min-height: 100vh; } 56 + 57 + .sidebar { 58 + width: 220px; 59 + background: var(--bg-primary-color); 60 + border-right: 1px solid var(--border-color); 61 + padding: 20px 0; 62 + position: fixed; 63 + top: 0; left: 0; bottom: 0; 64 + overflow-y: auto; 65 + display: flex; 66 + flex-direction: column; 67 + } 68 + 69 + .sidebar-title { 70 + font-size: 0.8125rem; 71 + font-weight: 700; 72 + padding: 0 20px; 73 + margin-bottom: 4px; 74 + white-space: nowrap; 75 + overflow: hidden; 76 + text-overflow: ellipsis; 77 + } 78 + 79 + .sidebar-subtitle { 80 + font-size: 0.6875rem; 81 + color: var(--secondary-color); 82 + padding: 0 20px; 83 + margin-bottom: 20px; 84 + } 85 + 86 + .sidebar nav { flex: 1; } 87 + 88 + .sidebar nav a { 89 + display: block; 90 + padding: 8px 20px; 91 + font-size: 0.8125rem; 92 + color: var(--secondary-color); 93 + text-decoration: none; 94 + transition: background 0.1s, color 0.1s; 95 + } 96 + 97 + .sidebar nav a:hover { 98 + background: var(--bg-secondary-color); 99 + color: var(--primary-color); 100 + } 101 + 102 + .sidebar nav a.active { 103 + color: var(--brand-color); 104 + font-weight: 500; 105 + } 106 + 107 + .sidebar-footer { 108 + padding: 16px 20px 0; 109 + border-top: 1px solid var(--border-color); 110 + margin-top: 16px; 111 + } 112 + 113 + .sidebar-footer .session-info { 114 + font-size: 0.75rem; 115 + color: var(--secondary-color); 116 + margin-bottom: 8px; 117 + } 118 + 119 + .sidebar-footer form { display: inline; } 120 + 121 + .sidebar-footer button { 122 + background: none; 123 + border: none; 124 + font-size: 0.75rem; 125 + color: var(--secondary-color); 126 + cursor: pointer; 127 + padding: 0; 128 + text-decoration: underline; 129 + } 130 + 131 + .sidebar-footer button:hover { color: var(--primary-color); } 132 + 133 + .main { 134 + margin-left: 220px; 135 + flex: 1; 136 + padding: 32px; 137 + max-width: 960px; 138 + } 139 + 140 + .page-title { 141 + font-size: 1.5rem; 142 + font-weight: 700; 143 + margin-bottom: 24px; 144 + } 145 + 146 + .flash-success { 147 + background: rgba(22, 163, 74, 0.1); 148 + color: var(--success-color); 149 + border: 1px solid rgba(22, 163, 74, 0.2); 150 + border-radius: 8px; 151 + padding: 10px 14px; 152 + font-size: 0.875rem; 153 + margin-bottom: 20px; 154 + } 155 + 156 + .flash-error { 157 + background: rgba(220, 38, 38, 0.1); 158 + color: var(--danger-color); 159 + border: 1px solid rgba(220, 38, 38, 0.2); 160 + border-radius: 8px; 161 + padding: 10px 14px; 162 + font-size: 0.875rem; 163 + margin-bottom: 20px; 164 + } 165 + 166 + .form-card { 167 + background: var(--bg-primary-color); 168 + border: 1px solid var(--border-color); 169 + border-radius: 10px; 170 + padding: 24px; 171 + max-width: 480px; 172 + } 173 + 174 + .form-group { 175 + margin-bottom: 16px; 176 + } 177 + 178 + .form-group label { 179 + display: block; 180 + font-size: 0.8125rem; 181 + font-weight: 500; 182 + margin-bottom: 6px; 183 + color: var(--primary-color); 184 + } 185 + 186 + .form-group input { 187 + width: 100%; 188 + padding: 10px 12px; 189 + font-size: 0.875rem; 190 + border: 1px solid var(--border-color); 191 + border-radius: 8px; 192 + background: var(--bg-primary-color); 193 + color: var(--primary-color); 194 + outline: none; 195 + transition: border-color 0.15s; 196 + } 197 + 198 + .form-group input:focus { 199 + border-color: var(--brand-color); 200 + } 201 + 202 + .form-group .hint { 203 + font-size: 0.75rem; 204 + color: var(--secondary-color); 205 + margin-top: 4px; 206 + } 207 + 208 + .btn { 209 + display: inline-flex; 210 + align-items: center; 211 + justify-content: center; 212 + padding: 10px 20px; 213 + font-size: 0.875rem; 214 + font-weight: 500; 215 + border: none; 216 + border-radius: 8px; 217 + cursor: pointer; 218 + transition: opacity 0.15s; 219 + text-decoration: none; 220 + } 221 + 222 + .btn:hover { opacity: 0.85; } 223 + 224 + .btn-primary { 225 + background: var(--brand-color); 226 + color: #fff; 227 + } 228 + 229 + .success-card { 230 + background: var(--bg-primary-color); 231 + border: 1px solid var(--border-color); 232 + border-radius: 10px; 233 + padding: 24px; 234 + max-width: 480px; 235 + } 236 + 237 + .success-card h3 { 238 + font-size: 1rem; 239 + font-weight: 600; 240 + color: var(--success-color); 241 + margin-bottom: 16px; 242 + } 243 + 244 + .detail-row { 245 + display: flex; 246 + justify-content: space-between; 247 + padding: 8px 0; 248 + font-size: 0.8125rem; 249 + border-bottom: 1px solid var(--border-color); 250 + } 251 + 252 + .detail-row:last-child { 253 + border-bottom: none; 254 + } 255 + 256 + .detail-row .label { 257 + color: var(--secondary-color); 258 + } 259 + 260 + .detail-row .value { 261 + font-weight: 500; 262 + word-break: break-all; 263 + text-align: right; 264 + max-width: 65%; 265 + } 266 + 267 + .password-highlight { 268 + font-family: 'SF Mono', SFMono-Regular, Menlo, Consolas, monospace; 269 + background: rgba(22, 163, 74, 0.08); 270 + padding: 2px 6px; 271 + border-radius: 4px; 272 + user-select: all; 273 + } 274 + 275 + @media (max-width: 768px) { 276 + .sidebar { display: none; } 277 + .main { margin-left: 0; } 278 + } 279 + </style> 280 + </head> 281 + <body> 282 + <div class="layout"> 283 + <aside class="sidebar"> 284 + <div class="sidebar-title">{{pds_hostname}}</div> 285 + <div class="sidebar-subtitle">Admin Portal</div> 286 + <nav> 287 + <a href="/admin/">Dashboard</a> 288 + <a href="/admin/accounts">Accounts</a> 289 + {{#if can_manage_invites}} 290 + <a href="/admin/invite-codes">Invite Codes</a> 291 + {{/if}} 292 + {{#if can_create_account}} 293 + <a href="/admin/create-account" class="active">Create Account</a> 294 + {{/if}} 295 + </nav> 296 + <div class="sidebar-footer"> 297 + <div class="session-info">Signed in as {{handle}}</div> 298 + <form method="POST" action="/admin/logout"> 299 + <button type="submit">Sign out</button> 300 + </form> 301 + </div> 302 + </aside> 303 + 304 + <main class="main"> 305 + {{#if flash_success}} 306 + <div class="flash-success">{{flash_success}}</div> 307 + {{/if}} 308 + {{#if flash_error}} 309 + <div class="flash-error">{{flash_error}}</div> 310 + {{/if}} 311 + 312 + <h1 class="page-title">Create Account</h1> 313 + 314 + {{#if created}} 315 + <div class="success-card"> 316 + <h3>Account Created Successfully</h3> 317 + <div class="detail-row"> 318 + <span class="label">DID</span> 319 + <span class="value">{{created.did}}</span> 320 + </div> 321 + <div class="detail-row"> 322 + <span class="label">Handle</span> 323 + <span class="value">{{created.handle}}</span> 324 + </div> 325 + <div class="detail-row"> 326 + <span class="label">Email</span> 327 + <span class="value">{{created.email}}</span> 328 + </div> 329 + <div class="detail-row"> 330 + <span class="label">Password</span> 331 + <span class="value"><span class="password-highlight">{{created.password}}</span></span> 332 + </div> 333 + {{#if created.inviteCode}} 334 + <div class="detail-row"> 335 + <span class="label">Invite Code Used</span> 336 + <span class="value">{{created.inviteCode}}</span> 337 + </div> 338 + {{/if}} 339 + </div> 340 + {{else}} 341 + <div class="form-card"> 342 + <form method="POST" action="/admin/create-account"> 343 + <div class="form-group"> 344 + <label for="email">Email</label> 345 + <input type="email" id="email" name="email" placeholder="user@example.com" required /> 346 + </div> 347 + <div class="form-group"> 348 + <label for="handle">Handle</label> 349 + <input type="text" id="handle" name="handle" placeholder="user.example.com" required /> 350 + <div class="hint">Must be a valid handle for this PDS</div> 351 + </div> 352 + <button type="submit" class="btn btn-primary">Create Account</button> 353 + </form> 354 + </div> 355 + {{/if}} 356 + </main> 357 + </div> 358 + </body> 359 + </html>
+323
html_templates/admin/dashboard.hbs
··· 1 + <!DOCTYPE html> 2 + <html lang="en"> 3 + <head> 4 + <meta charset="utf-8"/> 5 + <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, viewport-fit=cover"/> 6 + <meta name="referrer" content="origin-when-cross-origin"/> 7 + <title>Dashboard - {{pds_hostname}}</title> 8 + <style> 9 + :root, 10 + :root.light-mode { 11 + --brand-color: rgb(16, 131, 254); 12 + --primary-color: rgb(7, 10, 13); 13 + --secondary-color: rgb(66, 86, 108); 14 + --bg-primary-color: rgb(255, 255, 255); 15 + --bg-secondary-color: rgb(240, 242, 245); 16 + --border-color: rgb(220, 225, 230); 17 + --danger-color: rgb(220, 38, 38); 18 + --success-color: rgb(22, 163, 74); 19 + --warning-color: rgb(234, 179, 8); 20 + --table-stripe: rgba(0, 0, 0, 0.02); 21 + } 22 + 23 + @media (prefers-color-scheme: dark) { 24 + :root { 25 + --brand-color: rgb(16, 131, 254); 26 + --primary-color: rgb(255, 255, 255); 27 + --secondary-color: rgb(133, 152, 173); 28 + --bg-primary-color: rgb(7, 10, 13); 29 + --bg-secondary-color: rgb(13, 18, 23); 30 + --border-color: rgb(40, 45, 55); 31 + --table-stripe: rgba(255, 255, 255, 0.02); 32 + } 33 + } 34 + 35 + :root.dark-mode { 36 + --brand-color: rgb(16, 131, 254); 37 + --primary-color: rgb(255, 255, 255); 38 + --secondary-color: rgb(133, 152, 173); 39 + --bg-primary-color: rgb(7, 10, 13); 40 + --bg-secondary-color: rgb(13, 18, 23); 41 + --border-color: rgb(40, 45, 55); 42 + --table-stripe: rgba(255, 255, 255, 0.02); 43 + } 44 + 45 + * { margin: 0; padding: 0; box-sizing: border-box; } 46 + 47 + body { 48 + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; 49 + background: var(--bg-secondary-color); 50 + color: var(--primary-color); 51 + text-rendering: optimizeLegibility; 52 + -webkit-font-smoothing: antialiased; 53 + } 54 + 55 + .layout { 56 + display: flex; 57 + min-height: 100vh; 58 + } 59 + 60 + .sidebar { 61 + width: 220px; 62 + background: var(--bg-primary-color); 63 + border-right: 1px solid var(--border-color); 64 + padding: 20px 0; 65 + position: fixed; 66 + top: 0; 67 + left: 0; 68 + bottom: 0; 69 + overflow-y: auto; 70 + display: flex; 71 + flex-direction: column; 72 + } 73 + 74 + .sidebar-title { 75 + font-size: 0.8125rem; 76 + font-weight: 700; 77 + padding: 0 20px; 78 + margin-bottom: 4px; 79 + white-space: nowrap; 80 + overflow: hidden; 81 + text-overflow: ellipsis; 82 + } 83 + 84 + .sidebar-subtitle { 85 + font-size: 0.6875rem; 86 + color: var(--secondary-color); 87 + padding: 0 20px; 88 + margin-bottom: 20px; 89 + } 90 + 91 + .sidebar nav { 92 + flex: 1; 93 + } 94 + 95 + .sidebar nav a { 96 + display: block; 97 + padding: 8px 20px; 98 + font-size: 0.8125rem; 99 + color: var(--secondary-color); 100 + text-decoration: none; 101 + transition: background 0.1s, color 0.1s; 102 + } 103 + 104 + .sidebar nav a:hover { 105 + background: var(--bg-secondary-color); 106 + color: var(--primary-color); 107 + } 108 + 109 + .sidebar nav a.active { 110 + color: var(--brand-color); 111 + font-weight: 500; 112 + } 113 + 114 + .sidebar-footer { 115 + padding: 16px 20px 0; 116 + border-top: 1px solid var(--border-color); 117 + margin-top: 16px; 118 + } 119 + 120 + .sidebar-footer .session-info { 121 + font-size: 0.75rem; 122 + color: var(--secondary-color); 123 + margin-bottom: 8px; 124 + } 125 + 126 + .sidebar-footer form { 127 + display: inline; 128 + } 129 + 130 + .sidebar-footer button { 131 + background: none; 132 + border: none; 133 + font-size: 0.75rem; 134 + color: var(--secondary-color); 135 + cursor: pointer; 136 + padding: 0; 137 + text-decoration: underline; 138 + } 139 + 140 + .sidebar-footer button:hover { 141 + color: var(--primary-color); 142 + } 143 + 144 + .main { 145 + margin-left: 220px; 146 + flex: 1; 147 + padding: 32px; 148 + max-width: 960px; 149 + } 150 + 151 + .page-title { 152 + font-size: 1.5rem; 153 + font-weight: 700; 154 + margin-bottom: 24px; 155 + } 156 + 157 + .flash-success { 158 + background: rgba(22, 163, 74, 0.1); 159 + color: var(--success-color); 160 + border: 1px solid rgba(22, 163, 74, 0.2); 161 + border-radius: 8px; 162 + padding: 10px 14px; 163 + font-size: 0.875rem; 164 + margin-bottom: 20px; 165 + } 166 + 167 + .flash-error { 168 + background: rgba(220, 38, 38, 0.1); 169 + color: var(--danger-color); 170 + border: 1px solid rgba(220, 38, 38, 0.2); 171 + border-radius: 8px; 172 + padding: 10px 14px; 173 + font-size: 0.875rem; 174 + margin-bottom: 20px; 175 + } 176 + 177 + .cards { 178 + display: grid; 179 + grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); 180 + gap: 16px; 181 + margin-bottom: 32px; 182 + } 183 + 184 + .card { 185 + background: var(--bg-primary-color); 186 + border: 1px solid var(--border-color); 187 + border-radius: 10px; 188 + padding: 20px; 189 + } 190 + 191 + .card-label { 192 + font-size: 0.75rem; 193 + font-weight: 500; 194 + color: var(--secondary-color); 195 + text-transform: uppercase; 196 + letter-spacing: 0.5px; 197 + margin-bottom: 6px; 198 + } 199 + 200 + .card-value { 201 + font-size: 1.25rem; 202 + font-weight: 600; 203 + } 204 + 205 + .card-value.success { color: var(--success-color); } 206 + .card-value.danger { color: var(--danger-color); } 207 + 208 + .detail-section { 209 + background: var(--bg-primary-color); 210 + border: 1px solid var(--border-color); 211 + border-radius: 10px; 212 + padding: 20px; 213 + margin-bottom: 16px; 214 + } 215 + 216 + .detail-section h3 { 217 + font-size: 0.875rem; 218 + font-weight: 600; 219 + margin-bottom: 12px; 220 + } 221 + 222 + .detail-row { 223 + display: flex; 224 + justify-content: space-between; 225 + padding: 6px 0; 226 + font-size: 0.8125rem; 227 + border-bottom: 1px solid var(--border-color); 228 + } 229 + 230 + .detail-row:last-child { 231 + border-bottom: none; 232 + } 233 + 234 + .detail-row .label { 235 + color: var(--secondary-color); 236 + } 237 + 238 + .detail-row .value { 239 + font-weight: 500; 240 + word-break: break-all; 241 + text-align: right; 242 + max-width: 60%; 243 + } 244 + 245 + @media (max-width: 768px) { 246 + .sidebar { 247 + display: none; 248 + } 249 + .main { 250 + margin-left: 0; 251 + } 252 + } 253 + </style> 254 + </head> 255 + <body> 256 + <div class="layout"> 257 + <aside class="sidebar"> 258 + <div class="sidebar-title">{{pds_hostname}}</div> 259 + <div class="sidebar-subtitle">Admin Portal</div> 260 + <nav> 261 + <a href="/admin/" class="active">Dashboard</a> 262 + <a href="/admin/accounts">Accounts</a> 263 + {{#if can_manage_invites}} 264 + <a href="/admin/invite-codes">Invite Codes</a> 265 + {{/if}} 266 + {{#if can_create_account}} 267 + <a href="/admin/create-account">Create Account</a> 268 + {{/if}} 269 + </nav> 270 + <div class="sidebar-footer"> 271 + <div class="session-info">Signed in as {{handle}}</div> 272 + <form method="POST" action="/admin/logout"> 273 + <button type="submit">Sign out</button> 274 + </form> 275 + </div> 276 + </aside> 277 + 278 + <main class="main"> 279 + {{#if flash_success}} 280 + <div class="flash-success">{{flash_success}}</div> 281 + {{/if}} 282 + {{#if flash_error}} 283 + <div class="flash-error">{{flash_error}}</div> 284 + {{/if}} 285 + 286 + <h1 class="page-title">Dashboard</h1> 287 + 288 + <div class="cards"> 289 + <div class="card"> 290 + <div class="card-label">PDS Version</div> 291 + <div class="card-value">{{version}}</div> 292 + </div> 293 + <div class="card"> 294 + <div class="card-label">Total Accounts</div> 295 + <div class="card-value">{{account_count}}</div> 296 + </div> 297 + <div class="card"> 298 + <div class="card-label">Invite Code Required</div> 299 + <div class="card-value">{{#if invite_code_required}}Yes{{else}}No{{/if}}</div> 300 + </div> 301 + </div> 302 + 303 + <div class="detail-section"> 304 + <h3>Server Information</h3> 305 + <div class="detail-row"> 306 + <span class="label">Server DID</span> 307 + <span class="value">{{server_did}}</span> 308 + </div> 309 + <div class="detail-row"> 310 + <span class="label">Available Domains</span> 311 + <span class="value">{{available_domains}}</span> 312 + </div> 313 + {{#if contact_email}} 314 + <div class="detail-row"> 315 + <span class="label">Contact Email</span> 316 + <span class="value">{{contact_email}}</span> 317 + </div> 318 + {{/if}} 319 + </div> 320 + </main> 321 + </div> 322 + </body> 323 + </html>
+241
html_templates/admin/error.hbs
··· 1 + <!DOCTYPE html> 2 + <html lang="en"> 3 + <head> 4 + <meta charset="utf-8"/> 5 + <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, viewport-fit=cover"/> 6 + <meta name="referrer" content="origin-when-cross-origin"/> 7 + <title>Error - {{pds_hostname}}</title> 8 + <style> 9 + :root, 10 + :root.light-mode { 11 + --brand-color: rgb(16, 131, 254); 12 + --primary-color: rgb(7, 10, 13); 13 + --secondary-color: rgb(66, 86, 108); 14 + --bg-primary-color: rgb(255, 255, 255); 15 + --bg-secondary-color: rgb(240, 242, 245); 16 + --border-color: rgb(220, 225, 230); 17 + --danger-color: rgb(220, 38, 38); 18 + --success-color: rgb(22, 163, 74); 19 + } 20 + 21 + @media (prefers-color-scheme: dark) { 22 + :root { 23 + --brand-color: rgb(16, 131, 254); 24 + --primary-color: rgb(255, 255, 255); 25 + --secondary-color: rgb(133, 152, 173); 26 + --bg-primary-color: rgb(7, 10, 13); 27 + --bg-secondary-color: rgb(13, 18, 23); 28 + --border-color: rgb(40, 45, 55); 29 + } 30 + } 31 + 32 + :root.dark-mode { 33 + --brand-color: rgb(16, 131, 254); 34 + --primary-color: rgb(255, 255, 255); 35 + --secondary-color: rgb(133, 152, 173); 36 + --bg-primary-color: rgb(7, 10, 13); 37 + --bg-secondary-color: rgb(13, 18, 23); 38 + --border-color: rgb(40, 45, 55); 39 + } 40 + 41 + * { margin: 0; padding: 0; box-sizing: border-box; } 42 + 43 + body { 44 + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; 45 + background: var(--bg-secondary-color); 46 + color: var(--primary-color); 47 + text-rendering: optimizeLegibility; 48 + -webkit-font-smoothing: antialiased; 49 + min-height: 100vh; 50 + } 51 + 52 + /* When logged in, use sidebar layout */ 53 + .layout { display: flex; min-height: 100vh; } 54 + 55 + .sidebar { 56 + width: 220px; 57 + background: var(--bg-primary-color); 58 + border-right: 1px solid var(--border-color); 59 + padding: 20px 0; 60 + position: fixed; 61 + top: 0; left: 0; bottom: 0; 62 + overflow-y: auto; 63 + display: flex; 64 + flex-direction: column; 65 + } 66 + 67 + .sidebar-title { 68 + font-size: 0.8125rem; 69 + font-weight: 700; 70 + padding: 0 20px; 71 + margin-bottom: 4px; 72 + white-space: nowrap; 73 + overflow: hidden; 74 + text-overflow: ellipsis; 75 + } 76 + 77 + .sidebar-subtitle { 78 + font-size: 0.6875rem; 79 + color: var(--secondary-color); 80 + padding: 0 20px; 81 + margin-bottom: 20px; 82 + } 83 + 84 + .sidebar nav { flex: 1; } 85 + 86 + .sidebar nav a { 87 + display: block; 88 + padding: 8px 20px; 89 + font-size: 0.8125rem; 90 + color: var(--secondary-color); 91 + text-decoration: none; 92 + transition: background 0.1s, color 0.1s; 93 + } 94 + 95 + .sidebar nav a:hover { 96 + background: var(--bg-secondary-color); 97 + color: var(--primary-color); 98 + } 99 + 100 + .sidebar-footer { 101 + padding: 16px 20px 0; 102 + border-top: 1px solid var(--border-color); 103 + margin-top: 16px; 104 + } 105 + 106 + .sidebar-footer .session-info { 107 + font-size: 0.75rem; 108 + color: var(--secondary-color); 109 + margin-bottom: 8px; 110 + } 111 + 112 + .sidebar-footer form { display: inline; } 113 + 114 + .sidebar-footer button { 115 + background: none; 116 + border: none; 117 + font-size: 0.75rem; 118 + color: var(--secondary-color); 119 + cursor: pointer; 120 + padding: 0; 121 + text-decoration: underline; 122 + } 123 + 124 + .sidebar-footer button:hover { color: var(--primary-color); } 125 + 126 + .main { 127 + margin-left: 220px; 128 + flex: 1; 129 + padding: 32px; 130 + max-width: 960px; 131 + } 132 + 133 + /* Standalone centered layout (when not logged in) */ 134 + .centered { 135 + display: flex; 136 + align-items: center; 137 + justify-content: center; 138 + min-height: 100vh; 139 + } 140 + 141 + .error-card { 142 + background: var(--bg-primary-color); 143 + border: 1px solid var(--border-color); 144 + border-radius: 12px; 145 + padding: 40px; 146 + text-align: center; 147 + max-width: 480px; 148 + width: 100%; 149 + margin: 20px; 150 + } 151 + 152 + .error-icon { 153 + font-size: 2.5rem; 154 + margin-bottom: 16px; 155 + color: var(--danger-color); 156 + } 157 + 158 + .error-title { 159 + font-size: 1.25rem; 160 + font-weight: 700; 161 + margin-bottom: 8px; 162 + } 163 + 164 + .error-message { 165 + font-size: 0.875rem; 166 + color: var(--secondary-color); 167 + margin-bottom: 24px; 168 + line-height: 1.5; 169 + } 170 + 171 + .error-link { 172 + display: inline-flex; 173 + align-items: center; 174 + justify-content: center; 175 + padding: 10px 20px; 176 + font-size: 0.875rem; 177 + font-weight: 500; 178 + border: none; 179 + border-radius: 8px; 180 + cursor: pointer; 181 + text-decoration: none; 182 + background: var(--brand-color); 183 + color: #fff; 184 + transition: opacity 0.15s; 185 + } 186 + 187 + .error-link:hover { opacity: 0.85; } 188 + 189 + @media (max-width: 768px) { 190 + .sidebar { display: none; } 191 + .main { margin-left: 0; } 192 + } 193 + </style> 194 + </head> 195 + <body> 196 + {{#if handle}} 197 + {{!-- Logged-in user: show sidebar layout --}} 198 + <div class="layout"> 199 + <aside class="sidebar"> 200 + <div class="sidebar-title">{{pds_hostname}}</div> 201 + <div class="sidebar-subtitle">Admin Portal</div> 202 + <nav> 203 + <a href="/admin/">Dashboard</a> 204 + <a href="/admin/accounts">Accounts</a> 205 + {{#if can_manage_invites}} 206 + <a href="/admin/invite-codes">Invite Codes</a> 207 + {{/if}} 208 + {{#if can_create_account}} 209 + <a href="/admin/create-account">Create Account</a> 210 + {{/if}} 211 + </nav> 212 + <div class="sidebar-footer"> 213 + <div class="session-info">Signed in as {{handle}}</div> 214 + <form method="POST" action="/admin/logout"> 215 + <button type="submit">Sign out</button> 216 + </form> 217 + </div> 218 + </aside> 219 + 220 + <main class="main"> 221 + <div class="error-card" style="text-align:center; margin: 60px auto;"> 222 + <div class="error-icon">!</div> 223 + <div class="error-title">{{error_title}}</div> 224 + <div class="error-message">{{error_message}}</div> 225 + <a href="/admin/" class="error-link">Back to Dashboard</a> 226 + </div> 227 + </main> 228 + </div> 229 + {{else}} 230 + {{!-- Not logged in: standalone centered layout --}} 231 + <div class="centered"> 232 + <div class="error-card"> 233 + <div class="error-icon">!</div> 234 + <div class="error-title">{{error_title}}</div> 235 + <div class="error-message">{{error_message}}</div> 236 + <a href="/admin/login" class="error-link">Go to Login</a> 237 + </div> 238 + </div> 239 + {{/if}} 240 + </body> 241 + </html>
+430
html_templates/admin/invite_codes.hbs
··· 1 + <!DOCTYPE html> 2 + <html lang="en"> 3 + <head> 4 + <meta charset="utf-8"/> 5 + <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, viewport-fit=cover"/> 6 + <meta name="referrer" content="origin-when-cross-origin"/> 7 + <title>Invite Codes - {{pds_hostname}}</title> 8 + <style> 9 + :root, 10 + :root.light-mode { 11 + --brand-color: rgb(16, 131, 254); 12 + --primary-color: rgb(7, 10, 13); 13 + --secondary-color: rgb(66, 86, 108); 14 + --bg-primary-color: rgb(255, 255, 255); 15 + --bg-secondary-color: rgb(240, 242, 245); 16 + --border-color: rgb(220, 225, 230); 17 + --danger-color: rgb(220, 38, 38); 18 + --success-color: rgb(22, 163, 74); 19 + --warning-color: rgb(234, 179, 8); 20 + --table-stripe: rgba(0, 0, 0, 0.02); 21 + } 22 + 23 + @media (prefers-color-scheme: dark) { 24 + :root { 25 + --brand-color: rgb(16, 131, 254); 26 + --primary-color: rgb(255, 255, 255); 27 + --secondary-color: rgb(133, 152, 173); 28 + --bg-primary-color: rgb(7, 10, 13); 29 + --bg-secondary-color: rgb(13, 18, 23); 30 + --border-color: rgb(40, 45, 55); 31 + --table-stripe: rgba(255, 255, 255, 0.02); 32 + } 33 + } 34 + 35 + :root.dark-mode { 36 + --brand-color: rgb(16, 131, 254); 37 + --primary-color: rgb(255, 255, 255); 38 + --secondary-color: rgb(133, 152, 173); 39 + --bg-primary-color: rgb(7, 10, 13); 40 + --bg-secondary-color: rgb(13, 18, 23); 41 + --border-color: rgb(40, 45, 55); 42 + --table-stripe: rgba(255, 255, 255, 0.02); 43 + } 44 + 45 + * { margin: 0; padding: 0; box-sizing: border-box; } 46 + 47 + body { 48 + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; 49 + background: var(--bg-secondary-color); 50 + color: var(--primary-color); 51 + text-rendering: optimizeLegibility; 52 + -webkit-font-smoothing: antialiased; 53 + } 54 + 55 + .layout { display: flex; min-height: 100vh; } 56 + 57 + .sidebar { 58 + width: 220px; 59 + background: var(--bg-primary-color); 60 + border-right: 1px solid var(--border-color); 61 + padding: 20px 0; 62 + position: fixed; 63 + top: 0; left: 0; bottom: 0; 64 + overflow-y: auto; 65 + display: flex; 66 + flex-direction: column; 67 + } 68 + 69 + .sidebar-title { 70 + font-size: 0.8125rem; 71 + font-weight: 700; 72 + padding: 0 20px; 73 + margin-bottom: 4px; 74 + white-space: nowrap; 75 + overflow: hidden; 76 + text-overflow: ellipsis; 77 + } 78 + 79 + .sidebar-subtitle { 80 + font-size: 0.6875rem; 81 + color: var(--secondary-color); 82 + padding: 0 20px; 83 + margin-bottom: 20px; 84 + } 85 + 86 + .sidebar nav { flex: 1; } 87 + 88 + .sidebar nav a { 89 + display: block; 90 + padding: 8px 20px; 91 + font-size: 0.8125rem; 92 + color: var(--secondary-color); 93 + text-decoration: none; 94 + transition: background 0.1s, color 0.1s; 95 + } 96 + 97 + .sidebar nav a:hover { 98 + background: var(--bg-secondary-color); 99 + color: var(--primary-color); 100 + } 101 + 102 + .sidebar nav a.active { 103 + color: var(--brand-color); 104 + font-weight: 500; 105 + } 106 + 107 + .sidebar-footer { 108 + padding: 16px 20px 0; 109 + border-top: 1px solid var(--border-color); 110 + margin-top: 16px; 111 + } 112 + 113 + .sidebar-footer .session-info { 114 + font-size: 0.75rem; 115 + color: var(--secondary-color); 116 + margin-bottom: 8px; 117 + } 118 + 119 + .sidebar-footer form { display: inline; } 120 + 121 + .sidebar-footer button { 122 + background: none; 123 + border: none; 124 + font-size: 0.75rem; 125 + color: var(--secondary-color); 126 + cursor: pointer; 127 + padding: 0; 128 + text-decoration: underline; 129 + } 130 + 131 + .sidebar-footer button:hover { color: var(--primary-color); } 132 + 133 + .main { 134 + margin-left: 220px; 135 + flex: 1; 136 + padding: 32px; 137 + max-width: 960px; 138 + } 139 + 140 + .page-title { 141 + font-size: 1.5rem; 142 + font-weight: 700; 143 + margin-bottom: 24px; 144 + } 145 + 146 + .flash-success { 147 + background: rgba(22, 163, 74, 0.1); 148 + color: var(--success-color); 149 + border: 1px solid rgba(22, 163, 74, 0.2); 150 + border-radius: 8px; 151 + padding: 10px 14px; 152 + font-size: 0.875rem; 153 + margin-bottom: 20px; 154 + } 155 + 156 + .flash-error { 157 + background: rgba(220, 38, 38, 0.1); 158 + color: var(--danger-color); 159 + border: 1px solid rgba(220, 38, 38, 0.2); 160 + border-radius: 8px; 161 + padding: 10px 14px; 162 + font-size: 0.875rem; 163 + margin-bottom: 20px; 164 + } 165 + 166 + .create-form { 167 + display: flex; 168 + gap: 8px; 169 + align-items: flex-end; 170 + margin-bottom: 24px; 171 + } 172 + 173 + .create-form .form-group { 174 + display: flex; 175 + flex-direction: column; 176 + gap: 4px; 177 + } 178 + 179 + .create-form label { 180 + font-size: 0.75rem; 181 + font-weight: 500; 182 + color: var(--secondary-color); 183 + } 184 + 185 + .create-form input[type="number"] { 186 + padding: 10px 12px; 187 + font-size: 0.875rem; 188 + border: 1px solid var(--border-color); 189 + border-radius: 8px; 190 + background: var(--bg-primary-color); 191 + color: var(--primary-color); 192 + outline: none; 193 + width: 120px; 194 + } 195 + 196 + .create-form input[type="number"]:focus { 197 + border-color: var(--brand-color); 198 + } 199 + 200 + .btn { 201 + display: inline-flex; 202 + align-items: center; 203 + justify-content: center; 204 + padding: 10px 20px; 205 + font-size: 0.875rem; 206 + font-weight: 500; 207 + border: none; 208 + border-radius: 8px; 209 + cursor: pointer; 210 + transition: opacity 0.15s; 211 + text-decoration: none; 212 + } 213 + 214 + .btn:hover { opacity: 0.85; } 215 + 216 + .btn-primary { 217 + background: var(--brand-color); 218 + color: #fff; 219 + } 220 + 221 + .btn-small { 222 + padding: 6px 12px; 223 + font-size: 0.75rem; 224 + } 225 + 226 + .btn-outline-danger { 227 + background: transparent; 228 + color: var(--danger-color); 229 + border: 1px solid var(--danger-color); 230 + } 231 + 232 + .code-box { 233 + background: rgba(22, 163, 74, 0.08); 234 + border: 1px solid rgba(22, 163, 74, 0.2); 235 + border-radius: 10px; 236 + padding: 16px 20px; 237 + margin-bottom: 24px; 238 + } 239 + 240 + .code-box .code-label { 241 + font-size: 0.75rem; 242 + font-weight: 600; 243 + color: var(--success-color); 244 + margin-bottom: 6px; 245 + } 246 + 247 + .code-box .code-value { 248 + font-family: 'SF Mono', SFMono-Regular, Menlo, Consolas, monospace; 249 + font-size: 1rem; 250 + font-weight: 600; 251 + user-select: all; 252 + } 253 + 254 + .table-container { 255 + background: var(--bg-primary-color); 256 + border: 1px solid var(--border-color); 257 + border-radius: 10px; 258 + overflow: hidden; 259 + } 260 + 261 + table { 262 + width: 100%; 263 + border-collapse: collapse; 264 + } 265 + 266 + thead th { 267 + text-align: left; 268 + padding: 12px 16px; 269 + font-size: 0.75rem; 270 + font-weight: 600; 271 + color: var(--secondary-color); 272 + text-transform: uppercase; 273 + letter-spacing: 0.5px; 274 + border-bottom: 1px solid var(--border-color); 275 + } 276 + 277 + tbody tr { 278 + border-bottom: 1px solid var(--border-color); 279 + } 280 + 281 + tbody tr:last-child { 282 + border-bottom: none; 283 + } 284 + 285 + tbody tr:nth-child(even) { 286 + background: var(--table-stripe); 287 + } 288 + 289 + tbody td { 290 + padding: 10px 16px; 291 + font-size: 0.8125rem; 292 + } 293 + 294 + .code-cell { 295 + font-family: 'SF Mono', SFMono-Regular, Menlo, Consolas, monospace; 296 + font-size: 0.75rem; 297 + } 298 + 299 + .badge { 300 + display: inline-block; 301 + padding: 2px 8px; 302 + border-radius: 4px; 303 + font-size: 0.75rem; 304 + font-weight: 500; 305 + } 306 + 307 + .badge-success { 308 + background: rgba(22, 163, 74, 0.1); 309 + color: var(--success-color); 310 + } 311 + 312 + .badge-danger { 313 + background: rgba(220, 38, 38, 0.1); 314 + color: var(--danger-color); 315 + } 316 + 317 + .empty-state { 318 + text-align: center; 319 + padding: 40px 20px; 320 + color: var(--secondary-color); 321 + font-size: 0.875rem; 322 + } 323 + 324 + @media (max-width: 768px) { 325 + .sidebar { display: none; } 326 + .main { margin-left: 0; } 327 + } 328 + </style> 329 + </head> 330 + <body> 331 + <div class="layout"> 332 + <aside class="sidebar"> 333 + <div class="sidebar-title">{{pds_hostname}}</div> 334 + <div class="sidebar-subtitle">Admin Portal</div> 335 + <nav> 336 + <a href="/admin/">Dashboard</a> 337 + <a href="/admin/accounts">Accounts</a> 338 + {{#if can_manage_invites}} 339 + <a href="/admin/invite-codes" class="active">Invite Codes</a> 340 + {{/if}} 341 + {{#if can_create_account}} 342 + <a href="/admin/create-account">Create Account</a> 343 + {{/if}} 344 + </nav> 345 + <div class="sidebar-footer"> 346 + <div class="session-info">Signed in as {{handle}}</div> 347 + <form method="POST" action="/admin/logout"> 348 + <button type="submit">Sign out</button> 349 + </form> 350 + </div> 351 + </aside> 352 + 353 + <main class="main"> 354 + {{#if flash_success}} 355 + <div class="flash-success">{{flash_success}}</div> 356 + {{/if}} 357 + {{#if flash_error}} 358 + <div class="flash-error">{{flash_error}}</div> 359 + {{/if}} 360 + 361 + <h1 class="page-title">Invite Codes</h1> 362 + 363 + {{#if can_create_invite}} 364 + <form class="create-form" method="POST" action="/admin/invite-codes/create"> 365 + <div class="form-group"> 366 + <label for="use_count">Max Uses</label> 367 + <input type="number" id="use_count" name="use_count" value="1" min="1" max="100" /> 368 + </div> 369 + <button type="submit" class="btn btn-primary">Create Invite Code</button> 370 + </form> 371 + {{/if}} 372 + 373 + {{#if new_code}} 374 + <div class="code-box"> 375 + <div class="code-label">New Invite Code Created</div> 376 + <div class="code-value">{{new_code}}</div> 377 + </div> 378 + {{/if}} 379 + 380 + {{#if codes}} 381 + <div class="table-container"> 382 + <table> 383 + <thead> 384 + <tr> 385 + <th>Code</th> 386 + <th>Available / Used</th> 387 + <th>Status</th> 388 + <th>Created By</th> 389 + <th>Created At</th> 390 + {{#if can_manage_invites}} 391 + <th></th> 392 + {{/if}} 393 + </tr> 394 + </thead> 395 + <tbody> 396 + {{#each codes}} 397 + <tr> 398 + <td class="code-cell">{{this.code}}</td> 399 + <td>{{this.available}} / {{this.uses}}</td> 400 + <td> 401 + {{#if this.disabled}} 402 + <span class="badge badge-danger">Disabled</span> 403 + {{else}} 404 + <span class="badge badge-success">Active</span> 405 + {{/if}} 406 + </td> 407 + <td>{{this.createdBy}}</td> 408 + <td>{{this.createdAt}}</td> 409 + {{#if ../can_manage_invites}} 410 + <td> 411 + {{#unless this.disabled}} 412 + <form method="POST" action="/admin/invite-codes/disable" style="display:inline;"> 413 + <input type="hidden" name="code" value="{{this.code}}" /> 414 + <button type="submit" class="btn btn-small btn-outline-danger">Disable</button> 415 + </form> 416 + {{/unless}} 417 + </td> 418 + {{/if}} 419 + </tr> 420 + {{/each}} 421 + </tbody> 422 + </table> 423 + </div> 424 + {{else}} 425 + <div class="empty-state">No invite codes found</div> 426 + {{/if}} 427 + </main> 428 + </div> 429 + </body> 430 + </html>
+158
html_templates/admin/login.hbs
··· 1 + <!DOCTYPE html> 2 + <html lang="en"> 3 + <head> 4 + <meta charset="utf-8"/> 5 + <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, viewport-fit=cover"/> 6 + <meta name="referrer" content="origin-when-cross-origin"/> 7 + <title>Admin Login - {{pds_hostname}}</title> 8 + <style> 9 + :root, 10 + :root.light-mode { 11 + --brand-color: rgb(16, 131, 254); 12 + --primary-color: rgb(7, 10, 13); 13 + --secondary-color: rgb(66, 86, 108); 14 + --bg-primary-color: rgb(255, 255, 255); 15 + --bg-secondary-color: rgb(240, 242, 245); 16 + --border-color: rgb(220, 225, 230); 17 + --danger-color: rgb(220, 38, 38); 18 + --success-color: rgb(22, 163, 74); 19 + } 20 + 21 + @media (prefers-color-scheme: dark) { 22 + :root { 23 + --brand-color: rgb(16, 131, 254); 24 + --primary-color: rgb(255, 255, 255); 25 + --secondary-color: rgb(133, 152, 173); 26 + --bg-primary-color: rgb(7, 10, 13); 27 + --bg-secondary-color: rgb(13, 18, 23); 28 + --border-color: rgb(40, 45, 55); 29 + } 30 + } 31 + 32 + :root.dark-mode { 33 + --brand-color: rgb(16, 131, 254); 34 + --primary-color: rgb(255, 255, 255); 35 + --secondary-color: rgb(133, 152, 173); 36 + --bg-primary-color: rgb(7, 10, 13); 37 + --bg-secondary-color: rgb(13, 18, 23); 38 + --border-color: rgb(40, 45, 55); 39 + } 40 + 41 + * { margin: 0; padding: 0; box-sizing: border-box; } 42 + 43 + body { 44 + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; 45 + background: var(--bg-secondary-color); 46 + color: var(--primary-color); 47 + text-rendering: optimizeLegibility; 48 + -webkit-font-smoothing: antialiased; 49 + min-height: 100vh; 50 + display: flex; 51 + align-items: center; 52 + justify-content: center; 53 + } 54 + 55 + .login-card { 56 + background: var(--bg-primary-color); 57 + border: 1px solid var(--border-color); 58 + border-radius: 12px; 59 + padding: 40px; 60 + width: 100%; 61 + max-width: 400px; 62 + margin: 20px; 63 + } 64 + 65 + .login-title { 66 + font-size: 1.5rem; 67 + font-weight: 700; 68 + text-align: center; 69 + margin-bottom: 4px; 70 + } 71 + 72 + .login-subtitle { 73 + font-size: 0.875rem; 74 + color: var(--secondary-color); 75 + text-align: center; 76 + margin-bottom: 32px; 77 + } 78 + 79 + .form-group { 80 + margin-bottom: 20px; 81 + } 82 + 83 + .form-group label { 84 + display: block; 85 + font-size: 0.875rem; 86 + font-weight: 500; 87 + margin-bottom: 6px; 88 + color: var(--primary-color); 89 + } 90 + 91 + .form-group input { 92 + width: 100%; 93 + padding: 10px 12px; 94 + font-size: 0.875rem; 95 + border: 1px solid var(--border-color); 96 + border-radius: 8px; 97 + background: var(--bg-primary-color); 98 + color: var(--primary-color); 99 + outline: none; 100 + transition: border-color 0.15s; 101 + } 102 + 103 + .form-group input:focus { 104 + border-color: var(--brand-color); 105 + } 106 + 107 + .btn { 108 + display: inline-flex; 109 + align-items: center; 110 + justify-content: center; 111 + padding: 10px 20px; 112 + font-size: 0.875rem; 113 + font-weight: 500; 114 + border: none; 115 + border-radius: 8px; 116 + cursor: pointer; 117 + transition: opacity 0.15s; 118 + text-decoration: none; 119 + } 120 + 121 + .btn:hover { opacity: 0.85; } 122 + 123 + .btn-primary { 124 + background: var(--brand-color); 125 + color: #fff; 126 + width: 100%; 127 + } 128 + 129 + .error-msg { 130 + background: rgba(220, 38, 38, 0.1); 131 + color: var(--danger-color); 132 + border: 1px solid rgba(220, 38, 38, 0.2); 133 + border-radius: 8px; 134 + padding: 10px 14px; 135 + font-size: 0.875rem; 136 + margin-bottom: 20px; 137 + } 138 + </style> 139 + </head> 140 + <body> 141 + <div class="login-card"> 142 + <div class="login-title">{{pds_hostname}}</div> 143 + <div class="login-subtitle">Admin Portal</div> 144 + 145 + {{#if error}} 146 + <div class="error-msg">{{error}}</div> 147 + {{/if}} 148 + 149 + <form method="POST" action="/admin/login"> 150 + <div class="form-group"> 151 + <label for="handle">Handle</label> 152 + <input type="text" id="handle" name="handle" placeholder="you.bsky.social" required autofocus /> 153 + </div> 154 + <button type="submit" class="btn btn-primary">Login with OAuth</button> 155 + </form> 156 + </div> 157 + </body> 158 + </html>
+8
migrations/20260228000000_admin_sessions.sql
··· 1 + CREATE TABLE admin_sessions ( 2 + session_id VARCHAR(36) PRIMARY KEY, 3 + did VARCHAR NOT NULL, 4 + handle VARCHAR NOT NULL, 5 + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, 6 + expires_at TIMESTAMP NOT NULL 7 + ); 8 + CREATE INDEX idx_admin_sessions_expires_at ON admin_sessions(expires_at);
+106
src/admin/middleware.rs
··· 1 + use axum::{ 2 + extract::{Request, State}, 3 + http::StatusCode, 4 + middleware::Next, 5 + response::{IntoResponse, Redirect, Response}, 6 + }; 7 + use axum_extra::extract::cookie::SignedCookieJar; 8 + 9 + use crate::AppState; 10 + 11 + use super::rbac::RbacConfig; 12 + use super::session; 13 + 14 + /// Admin session data injected into request extensions. 15 + #[derive(Debug, Clone)] 16 + pub struct AdminSession { 17 + pub did: String, 18 + pub handle: String, 19 + pub roles: Vec<String>, 20 + } 21 + 22 + /// Pre-computed permission flags for template rendering and quick checks. 23 + #[derive(Debug, Clone)] 24 + pub struct AdminPermissions { 25 + pub can_view_accounts: bool, 26 + pub can_manage_takedowns: bool, 27 + pub can_delete_account: bool, 28 + pub can_reset_password: bool, 29 + pub can_create_account: bool, 30 + pub can_manage_invites: bool, 31 + pub can_create_invite: bool, 32 + pub can_send_email: bool, 33 + } 34 + 35 + impl AdminPermissions { 36 + pub fn compute(rbac: &RbacConfig, did: &str) -> Self { 37 + Self { 38 + can_view_accounts: rbac 39 + .can_access_endpoint(did, "com.atproto.admin.getAccountInfo") 40 + || rbac.can_access_endpoint(did, "com.atproto.admin.getAccountInfos"), 41 + can_manage_takedowns: rbac 42 + .can_access_endpoint(did, "com.atproto.admin.updateSubjectStatus"), 43 + can_delete_account: rbac 44 + .can_access_endpoint(did, "com.atproto.admin.deleteAccount"), 45 + can_reset_password: rbac 46 + .can_access_endpoint(did, "com.atproto.admin.updateAccountPassword"), 47 + can_create_account: rbac 48 + .can_access_endpoint(did, "com.atproto.server.createAccount"), 49 + can_manage_invites: rbac 50 + .can_access_endpoint(did, "com.atproto.admin.getInviteCodes"), 51 + can_create_invite: rbac 52 + .can_access_endpoint(did, "com.atproto.server.createInviteCode"), 53 + can_send_email: rbac.can_access_endpoint(did, "com.atproto.admin.sendEmail"), 54 + } 55 + } 56 + } 57 + 58 + /// Middleware that checks for a valid admin session cookie. 59 + /// If valid, injects AdminSession and AdminPermissions into request extensions. 60 + /// If invalid or missing, redirects to /admin/login. 61 + pub async fn admin_auth_middleware( 62 + State(state): State<AppState>, 63 + jar: SignedCookieJar, 64 + mut req: Request, 65 + next: Next, 66 + ) -> Response { 67 + let rbac = match &state.admin_rbac_config { 68 + Some(rbac) => rbac, 69 + None => return StatusCode::NOT_FOUND.into_response(), 70 + }; 71 + 72 + // Extract session ID from signed cookie 73 + let session_id = match jar.get("__gatekeeper_admin_session") { 74 + Some(cookie) => cookie.value().to_string(), 75 + None => return Redirect::to("/admin/login").into_response(), 76 + }; 77 + 78 + // Look up session in database 79 + let session_row = match session::get_session(&state.pds_gatekeeper_pool, &session_id).await { 80 + Ok(Some(row)) => row, 81 + Ok(None) => return Redirect::to("/admin/login").into_response(), 82 + Err(e) => { 83 + tracing::error!("Failed to look up admin session: {}", e); 84 + return Redirect::to("/admin/login").into_response(); 85 + } 86 + }; 87 + 88 + // Verify the DID is still a valid member 89 + if !rbac.is_member(&session_row.did) { 90 + return Redirect::to("/admin/login").into_response(); 91 + } 92 + 93 + let roles = rbac.get_member_roles(&session_row.did); 94 + let permissions = AdminPermissions::compute(rbac, &session_row.did); 95 + 96 + let admin_session = AdminSession { 97 + did: session_row.did, 98 + handle: session_row.handle, 99 + roles, 100 + }; 101 + 102 + req.extensions_mut().insert(admin_session); 103 + req.extensions_mut().insert(permissions); 104 + 105 + next.run(req).await 106 + }
+69
src/admin/mod.rs
··· 1 + pub mod middleware; 2 + pub mod oauth; 3 + pub mod pds_proxy; 4 + pub mod rbac; 5 + pub mod routes; 6 + pub mod session; 7 + 8 + use axum::{Router, middleware as ax_middleware, routing::get, routing::post}; 9 + 10 + use crate::AppState; 11 + 12 + /// Build the admin sub-router. 13 + /// Public routes (login, OAuth callback, client-metadata) are not behind auth middleware. 14 + /// All other admin routes require a valid session. 15 + pub fn router(state: AppState) -> Router<AppState> { 16 + // Routes that do NOT require authentication 17 + let public_routes = Router::new() 18 + .route("/login", get(oauth::get_login).post(oauth::post_login)) 19 + .route("/oauth/callback", get(oauth::oauth_callback)) 20 + .route("/client-metadata.json", get(oauth::client_metadata_json)); 21 + 22 + // Routes that DO require authentication (via admin_auth middleware) 23 + let protected_routes = Router::new() 24 + .route("/", get(routes::dashboard)) 25 + .route("/accounts", get(routes::accounts_list)) 26 + .route("/accounts/{did}", get(routes::account_detail)) 27 + .route( 28 + "/accounts/{did}/takedown", 29 + post(routes::takedown_account), 30 + ) 31 + .route( 32 + "/accounts/{did}/untakedown", 33 + post(routes::untakedown_account), 34 + ) 35 + .route( 36 + "/accounts/{did}/delete", 37 + post(routes::delete_account), 38 + ) 39 + .route( 40 + "/accounts/{did}/reset-password", 41 + post(routes::reset_password), 42 + ) 43 + .route( 44 + "/accounts/{did}/disable-invites", 45 + post(routes::disable_account_invites), 46 + ) 47 + .route( 48 + "/accounts/{did}/enable-invites", 49 + post(routes::enable_account_invites), 50 + ) 51 + .route("/invite-codes", get(routes::invite_codes_list)) 52 + .route("/invite-codes/create", post(routes::create_invite_code)) 53 + .route( 54 + "/invite-codes/disable", 55 + post(routes::disable_invite_codes), 56 + ) 57 + .route( 58 + "/create-account", 59 + get(routes::get_create_account).post(routes::post_create_account), 60 + ) 61 + .route("/search", get(routes::search_accounts)) 62 + .route("/logout", post(routes::logout)) 63 + .layer(ax_middleware::from_fn_with_state( 64 + state.clone(), 65 + middleware::admin_auth_middleware, 66 + )); 67 + 68 + Router::new().merge(public_routes).merge(protected_routes) 69 + }
+301
src/admin/oauth.rs
··· 1 + use axum::{ 2 + extract::{Query, State}, 3 + http::StatusCode, 4 + response::{Html, IntoResponse, Redirect, Response}, 5 + }; 6 + use axum_extra::extract::cookie::{Cookie, SameSite, SignedCookieJar}; 7 + use base64::Engine as _; 8 + use jacquard_identity::JacquardResolver; 9 + use jacquard_oauth::{ 10 + atproto::{AtprotoClientMetadata, GrantType}, 11 + authstore::MemoryAuthStore, 12 + client::OAuthClient, 13 + keyset::Keyset, 14 + session::ClientData, 15 + types::{AuthorizeOptions, CallbackParams}, 16 + }; 17 + use jose_jwk::Jwk; 18 + use serde::Deserialize; 19 + 20 + use crate::AppState; 21 + 22 + use super::session; 23 + 24 + /// Type alias for the concrete OAuthClient we use. 25 + pub type AdminOAuthClient = OAuthClient<JacquardResolver, MemoryAuthStore>; 26 + 27 + /// Initialize the OAuth client for admin portal authentication. 28 + pub fn init_oauth_client(pds_hostname: &str) -> Result<AdminOAuthClient, anyhow::Error> { 29 + // Generate ES256 keypair 30 + let secret_key = p256::SecretKey::random(&mut p256::elliptic_curve::rand_core::OsRng); 31 + let public_key = secret_key.public_key(); 32 + 33 + // Build JWK JSON manually with both public and private components 34 + let public_jwk_str = public_key.to_jwk_string(); 35 + let mut jwk: serde_json::Value = serde_json::from_str(&public_jwk_str)?; 36 + 37 + // Add the private key component 'd' 38 + let secret_scalar = secret_key.to_bytes(); 39 + let d_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(secret_scalar.as_slice()); 40 + let jwk_obj = jwk 41 + .as_object_mut() 42 + .ok_or_else(|| anyhow::anyhow!("JWK is not an object"))?; 43 + jwk_obj.insert("d".to_string(), serde_json::Value::String(d_b64)); 44 + 45 + // Add kid and alg 46 + let kid = uuid::Uuid::new_v4().to_string(); 47 + jwk_obj.insert("kid".to_string(), serde_json::Value::String(kid)); 48 + jwk_obj.insert( 49 + "alg".to_string(), 50 + serde_json::Value::String("ES256".to_string()), 51 + ); 52 + jwk_obj.insert( 53 + "use".to_string(), 54 + serde_json::Value::String("sig".to_string()), 55 + ); 56 + 57 + // Parse into jose-jwk type for Keyset 58 + let jose_jwk: Jwk = serde_json::from_value(jwk)?; 59 + let keyset = Keyset::try_from(vec![jose_jwk])?; 60 + 61 + // Build client metadata 62 + let client_id = format!("https://{}/admin/client-metadata.json", pds_hostname) 63 + .parse() 64 + .map_err(|_: url::ParseError| anyhow::anyhow!("Invalid client_id URL"))?; 65 + let redirect_uri = format!("https://{}/admin/oauth/callback", pds_hostname) 66 + .parse() 67 + .map_err(|_: url::ParseError| anyhow::anyhow!("Invalid redirect_uri URL"))?; 68 + let client_uri = format!("https://{}/admin/", pds_hostname) 69 + .parse() 70 + .map_err(|_: url::ParseError| anyhow::anyhow!("Invalid client_uri URL"))?; 71 + 72 + let config = AtprotoClientMetadata::new( 73 + client_id, 74 + Some(client_uri), 75 + vec![redirect_uri], 76 + vec![GrantType::AuthorizationCode], 77 + vec![ 78 + jacquard_oauth::scopes::Scope::parse("atproto").expect("valid scope"), 79 + ], 80 + None, 81 + ); 82 + 83 + let client_data = ClientData::new(Some(keyset), config); 84 + let store = MemoryAuthStore::new(); 85 + let client = OAuthClient::new(store, client_data); 86 + 87 + Ok(client) 88 + } 89 + 90 + /// GET /admin/client-metadata.json — Serves the OAuth client metadata. 91 + pub async fn client_metadata_json(State(state): State<AppState>) -> Response { 92 + let oauth_client: &AdminOAuthClient = match &state.admin_oauth_client { 93 + Some(client) => client, 94 + None => return StatusCode::NOT_FOUND.into_response(), 95 + }; 96 + 97 + let pds_hostname = &state.app_config.pds_hostname; 98 + let client_id = format!("https://{}/admin/client-metadata.json", pds_hostname); 99 + let redirect_uri = format!("https://{}/admin/oauth/callback", pds_hostname); 100 + let client_uri = format!("https://{}/admin/", pds_hostname); 101 + 102 + let jwks = oauth_client.jwks(); 103 + 104 + let metadata = serde_json::json!({ 105 + "client_id": client_id, 106 + "client_uri": client_uri, 107 + "redirect_uris": [redirect_uri], 108 + "grant_types": ["authorization_code"], 109 + "response_types": ["code"], 110 + "scope": "atproto", 111 + "token_endpoint_auth_method": "private_key_jwt", 112 + "token_endpoint_auth_signing_alg": "ES256", 113 + "application_type": "web", 114 + "dpop_bound_access_tokens": true, 115 + "jwks": jwks, 116 + }); 117 + 118 + ( 119 + StatusCode::OK, 120 + [(axum::http::header::CONTENT_TYPE, "application/json")], 121 + serde_json::to_string_pretty(&metadata).unwrap_or_default(), 122 + ) 123 + .into_response() 124 + } 125 + 126 + /// GET /admin/login — Renders the login page. 127 + pub async fn get_login( 128 + State(state): State<AppState>, 129 + Query(params): Query<LoginQueryParams>, 130 + ) -> Response { 131 + let mut data = serde_json::json!({ 132 + "pds_hostname": state.app_config.pds_hostname, 133 + }); 134 + 135 + if let Some(error) = params.error { 136 + data["error"] = serde_json::Value::String(error); 137 + } 138 + 139 + use axum_template::TemplateEngine; 140 + match state.template_engine.render("admin/login.hbs", data) 141 + { 142 + Ok(html) => Html(html).into_response(), 143 + Err(e) => { 144 + tracing::error!("Failed to render login template: {}", e); 145 + StatusCode::INTERNAL_SERVER_ERROR.into_response() 146 + } 147 + } 148 + } 149 + 150 + #[derive(Debug, Deserialize)] 151 + pub struct LoginQueryParams { 152 + pub error: Option<String>, 153 + } 154 + 155 + #[derive(Debug, Deserialize)] 156 + pub struct LoginForm { 157 + pub handle: String, 158 + } 159 + 160 + /// POST /admin/login — Initiates the OAuth flow. 161 + pub async fn post_login( 162 + State(state): State<AppState>, 163 + axum::extract::Form(form): axum::extract::Form<LoginForm>, 164 + ) -> Response { 165 + let oauth_client: &AdminOAuthClient = match &state.admin_oauth_client { 166 + Some(client) => client, 167 + None => return StatusCode::NOT_FOUND.into_response(), 168 + }; 169 + 170 + let pds_hostname = &state.app_config.pds_hostname; 171 + let redirect_uri: url::Url = 172 + match format!("https://{}/admin/oauth/callback", pds_hostname).parse() { 173 + Ok(u) => u, 174 + Err(_) => { 175 + return Redirect::to("/admin/login?error=Invalid+server+configuration") 176 + .into_response() 177 + } 178 + }; 179 + 180 + let options = AuthorizeOptions { 181 + redirect_uri: Some(redirect_uri), 182 + scopes: vec![ 183 + jacquard_oauth::scopes::Scope::parse("atproto").expect("valid scope"), 184 + jacquard_oauth::scopes::Scope::parse("transition:generic").expect("valid scope"), 185 + ], 186 + prompt: None, 187 + state: None, 188 + }; 189 + 190 + match oauth_client.start_auth(&form.handle, options).await { 191 + Ok(auth_url) => Redirect::to(&auth_url).into_response(), 192 + Err(e) => { 193 + tracing::error!("OAuth start_auth failed: {}", e); 194 + let msg = format!("Login failed: {}", e); 195 + let error_msg = urlencoding::encode(&msg); 196 + Redirect::to(&format!("/admin/login?error={}", error_msg)).into_response() 197 + } 198 + } 199 + } 200 + 201 + #[derive(Debug, Deserialize)] 202 + pub struct OAuthCallbackParams { 203 + pub code: String, 204 + pub state: Option<String>, 205 + pub iss: Option<String>, 206 + } 207 + 208 + /// GET /admin/oauth/callback — Handles the OAuth callback. 209 + pub async fn oauth_callback( 210 + State(state): State<AppState>, 211 + Query(params): Query<OAuthCallbackParams>, 212 + jar: SignedCookieJar, 213 + ) -> Response { 214 + let oauth_client: &AdminOAuthClient = match &state.admin_oauth_client { 215 + Some(client) => client, 216 + None => return StatusCode::NOT_FOUND.into_response(), 217 + }; 218 + 219 + let rbac = match &state.admin_rbac_config { 220 + Some(rbac) => rbac, 221 + None => return StatusCode::NOT_FOUND.into_response(), 222 + }; 223 + 224 + let callback_params = CallbackParams { 225 + code: params.code.as_str().into(), 226 + state: params.state.as_deref().map(Into::into), 227 + iss: params.iss.as_deref().map(Into::into), 228 + }; 229 + 230 + // Exchange authorization code for session 231 + let oauth_session = match oauth_client.callback(callback_params).await { 232 + Ok(session) => session, 233 + Err(e) => { 234 + tracing::error!("OAuth callback failed: {}", e); 235 + let msg = format!("Authentication failed: {}", e); 236 + let error_msg = urlencoding::encode(&msg); 237 + return Redirect::to(&format!("/admin/login?error={}", error_msg)).into_response(); 238 + } 239 + }; 240 + 241 + // Extract DID and handle from the OAuth session 242 + let (did, handle) = oauth_session.session_info().await; 243 + let did_str = did.to_string(); 244 + let handle_str = handle.to_string(); 245 + 246 + // Check if this DID is a member in the RBAC config 247 + if !rbac.is_member(&did_str) { 248 + tracing::warn!("Access denied for DID {} (not in RBAC config)", did_str); 249 + return render_error( 250 + &state, 251 + "Access Denied", 252 + &format!( 253 + "Your identity ({}) is not authorized to access the admin portal. Contact your PDS administrator.", 254 + handle_str 255 + ), 256 + ); 257 + } 258 + 259 + // Create admin session 260 + let ttl_hours = state.app_config.admin_session_ttl_hours; 261 + let session_id = match session::create_session( 262 + &state.pds_gatekeeper_pool, 263 + &did_str, 264 + &handle_str, 265 + ttl_hours, 266 + ) 267 + .await 268 + { 269 + Ok(id) => id, 270 + Err(e) => { 271 + tracing::error!("Failed to create admin session: {}", e); 272 + return Redirect::to("/admin/login?error=Session+creation+failed").into_response(); 273 + } 274 + }; 275 + 276 + // Set signed cookie 277 + let mut cookie = Cookie::new("__gatekeeper_admin_session", session_id); 278 + cookie.set_http_only(true); 279 + cookie.set_secure(true); 280 + cookie.set_same_site(SameSite::Lax); 281 + cookie.set_path("/admin/"); 282 + 283 + let updated_jar = jar.add(cookie); 284 + 285 + (updated_jar, Redirect::to("/admin/")).into_response() 286 + } 287 + 288 + fn render_error(state: &AppState, title: &str, message: &str) -> Response { 289 + let data = serde_json::json!({ 290 + "error_title": title, 291 + "error_message": message, 292 + "pds_hostname": state.app_config.pds_hostname, 293 + }); 294 + 295 + use axum_template::TemplateEngine; 296 + match state.template_engine.render("admin/error.hbs", data) 297 + { 298 + Ok(html) => Html(html).into_response(), 299 + Err(_) => (StatusCode::FORBIDDEN, format!("{}: {}", title, message)).into_response(), 300 + } 301 + }
+252
src/admin/pds_proxy.rs
··· 1 + use serde::de::DeserializeOwned; 2 + use serde::Serialize; 3 + use std::fmt; 4 + 5 + #[derive(Debug)] 6 + pub enum AdminProxyError { 7 + RequestFailed(String), 8 + PdsError { 9 + status: u16, 10 + error: String, 11 + message: String, 12 + }, 13 + ParseError(String), 14 + } 15 + 16 + impl fmt::Display for AdminProxyError { 17 + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 18 + match self { 19 + AdminProxyError::RequestFailed(msg) => write!(f, "Request failed: {msg}"), 20 + AdminProxyError::PdsError { 21 + status, 22 + error, 23 + message, 24 + } => write!(f, "PDS error ({status}): {error} - {message}"), 25 + AdminProxyError::ParseError(msg) => write!(f, "Parse error: {msg}"), 26 + } 27 + } 28 + } 29 + 30 + /// Make an authenticated GET request to a PDS XRPC endpoint. 31 + pub async fn admin_xrpc_get<R: DeserializeOwned>( 32 + pds_base_url: &str, 33 + admin_password: &str, 34 + endpoint: &str, 35 + query_params: &[(&str, &str)], 36 + ) -> Result<R, AdminProxyError> { 37 + let url = format!( 38 + "{}/xrpc/{}", 39 + pds_base_url.trim_end_matches('/'), 40 + endpoint 41 + ); 42 + let client = reqwest::Client::new(); 43 + let resp = client 44 + .get(&url) 45 + .query(query_params) 46 + .basic_auth("admin", Some(admin_password)) 47 + .send() 48 + .await 49 + .map_err(|e| AdminProxyError::RequestFailed(e.to_string()))?; 50 + 51 + if !resp.status().is_success() { 52 + let status = resp.status().as_u16(); 53 + let body = resp.text().await.unwrap_or_default(); 54 + if let Ok(err_json) = serde_json::from_str::<serde_json::Value>(&body) { 55 + return Err(AdminProxyError::PdsError { 56 + status, 57 + error: err_json["error"] 58 + .as_str() 59 + .unwrap_or("Unknown") 60 + .to_string(), 61 + message: err_json["message"] 62 + .as_str() 63 + .unwrap_or(&body) 64 + .to_string(), 65 + }); 66 + } 67 + return Err(AdminProxyError::PdsError { 68 + status, 69 + error: "Unknown".to_string(), 70 + message: body, 71 + }); 72 + } 73 + 74 + resp.json::<R>() 75 + .await 76 + .map_err(|e| AdminProxyError::ParseError(e.to_string())) 77 + } 78 + 79 + /// Make an authenticated POST request to a PDS XRPC endpoint. 80 + pub async fn admin_xrpc_post<T: Serialize, R: DeserializeOwned>( 81 + pds_base_url: &str, 82 + admin_password: &str, 83 + endpoint: &str, 84 + body: &T, 85 + ) -> Result<R, AdminProxyError> { 86 + let url = format!( 87 + "{}/xrpc/{}", 88 + pds_base_url.trim_end_matches('/'), 89 + endpoint 90 + ); 91 + let client = reqwest::Client::new(); 92 + let resp = client 93 + .post(&url) 94 + .json(body) 95 + .basic_auth("admin", Some(admin_password)) 96 + .send() 97 + .await 98 + .map_err(|e| AdminProxyError::RequestFailed(e.to_string()))?; 99 + 100 + if !resp.status().is_success() { 101 + let status = resp.status().as_u16(); 102 + let body = resp.text().await.unwrap_or_default(); 103 + if let Ok(err_json) = serde_json::from_str::<serde_json::Value>(&body) { 104 + return Err(AdminProxyError::PdsError { 105 + status, 106 + error: err_json["error"] 107 + .as_str() 108 + .unwrap_or("Unknown") 109 + .to_string(), 110 + message: err_json["message"] 111 + .as_str() 112 + .unwrap_or(&body) 113 + .to_string(), 114 + }); 115 + } 116 + return Err(AdminProxyError::PdsError { 117 + status, 118 + error: "Unknown".to_string(), 119 + message: body, 120 + }); 121 + } 122 + 123 + resp.json::<R>() 124 + .await 125 + .map_err(|e| AdminProxyError::ParseError(e.to_string())) 126 + } 127 + 128 + /// Make an authenticated POST request that returns no meaningful body (just success/failure). 129 + pub async fn admin_xrpc_post_no_response<T: Serialize>( 130 + pds_base_url: &str, 131 + admin_password: &str, 132 + endpoint: &str, 133 + body: &T, 134 + ) -> Result<(), AdminProxyError> { 135 + let url = format!( 136 + "{}/xrpc/{}", 137 + pds_base_url.trim_end_matches('/'), 138 + endpoint 139 + ); 140 + let client = reqwest::Client::new(); 141 + let resp = client 142 + .post(&url) 143 + .json(body) 144 + .basic_auth("admin", Some(admin_password)) 145 + .send() 146 + .await 147 + .map_err(|e| AdminProxyError::RequestFailed(e.to_string()))?; 148 + 149 + if !resp.status().is_success() { 150 + let status = resp.status().as_u16(); 151 + let body = resp.text().await.unwrap_or_default(); 152 + if let Ok(err_json) = serde_json::from_str::<serde_json::Value>(&body) { 153 + return Err(AdminProxyError::PdsError { 154 + status, 155 + error: err_json["error"] 156 + .as_str() 157 + .unwrap_or("Unknown") 158 + .to_string(), 159 + message: err_json["message"] 160 + .as_str() 161 + .unwrap_or(&body) 162 + .to_string(), 163 + }); 164 + } 165 + return Err(AdminProxyError::PdsError { 166 + status, 167 + error: "Unknown".to_string(), 168 + message: body, 169 + }); 170 + } 171 + 172 + Ok(()) 173 + } 174 + 175 + /// Make an unauthenticated GET request that returns text (e.g., _health). 176 + pub async fn get_text( 177 + pds_base_url: &str, 178 + endpoint: &str, 179 + ) -> Result<String, AdminProxyError> { 180 + let url = format!( 181 + "{}/{}", 182 + pds_base_url.trim_end_matches('/'), 183 + endpoint 184 + ); 185 + let client = reqwest::Client::new(); 186 + let resp = client 187 + .get(&url) 188 + .send() 189 + .await 190 + .map_err(|e| AdminProxyError::RequestFailed(e.to_string()))?; 191 + 192 + if !resp.status().is_success() { 193 + let status = resp.status().as_u16(); 194 + let body = resp.text().await.unwrap_or_default(); 195 + return Err(AdminProxyError::PdsError { 196 + status, 197 + error: "Unknown".to_string(), 198 + message: body, 199 + }); 200 + } 201 + 202 + resp.text() 203 + .await 204 + .map_err(|e| AdminProxyError::ParseError(e.to_string())) 205 + } 206 + 207 + /// Make an unauthenticated GET request with JSON response parsing. 208 + pub async fn public_xrpc_get<R: DeserializeOwned>( 209 + pds_base_url: &str, 210 + endpoint: &str, 211 + query_params: &[(&str, &str)], 212 + ) -> Result<R, AdminProxyError> { 213 + let url = format!( 214 + "{}/xrpc/{}", 215 + pds_base_url.trim_end_matches('/'), 216 + endpoint 217 + ); 218 + let client = reqwest::Client::new(); 219 + let resp = client 220 + .get(&url) 221 + .query(query_params) 222 + .send() 223 + .await 224 + .map_err(|e| AdminProxyError::RequestFailed(e.to_string()))?; 225 + 226 + if !resp.status().is_success() { 227 + let status = resp.status().as_u16(); 228 + let body = resp.text().await.unwrap_or_default(); 229 + if let Ok(err_json) = serde_json::from_str::<serde_json::Value>(&body) { 230 + return Err(AdminProxyError::PdsError { 231 + status, 232 + error: err_json["error"] 233 + .as_str() 234 + .unwrap_or("Unknown") 235 + .to_string(), 236 + message: err_json["message"] 237 + .as_str() 238 + .unwrap_or(&body) 239 + .to_string(), 240 + }); 241 + } 242 + return Err(AdminProxyError::PdsError { 243 + status, 244 + error: "Unknown".to_string(), 245 + message: body, 246 + }); 247 + } 248 + 249 + resp.json::<R>() 250 + .await 251 + .map_err(|e| AdminProxyError::ParseError(e.to_string())) 252 + }
+263
src/admin/rbac.rs
··· 1 + use serde::Deserialize; 2 + use std::collections::HashMap; 3 + use std::path::Path; 4 + 5 + #[derive(Debug, Clone, Deserialize)] 6 + pub struct RbacConfig { 7 + pub roles: HashMap<String, RoleDefinition>, 8 + pub members: Vec<MemberDefinition>, 9 + } 10 + 11 + #[derive(Debug, Clone, Deserialize)] 12 + pub struct RoleDefinition { 13 + pub description: String, 14 + pub endpoints: Vec<String>, 15 + } 16 + 17 + #[derive(Debug, Clone, Deserialize)] 18 + pub struct MemberDefinition { 19 + pub did: String, 20 + pub roles: Vec<String>, 21 + } 22 + 23 + impl RbacConfig { 24 + /// Load RBAC configuration from a YAML file. 25 + pub fn load_from_file(path: impl AsRef<Path>) -> Result<Self, anyhow::Error> { 26 + let contents = std::fs::read_to_string(path)?; 27 + let config: RbacConfig = serde_yaml::from_str(&contents)?; 28 + config.validate()?; 29 + Ok(config) 30 + } 31 + 32 + /// Validate that all member roles reference defined roles. 33 + fn validate(&self) -> Result<(), anyhow::Error> { 34 + for member in &self.members { 35 + for role in &member.roles { 36 + if !self.roles.contains_key(role) { 37 + return Err(anyhow::anyhow!( 38 + "Member {} references undefined role: {}", 39 + member.did, 40 + role 41 + )); 42 + } 43 + } 44 + } 45 + Ok(()) 46 + } 47 + 48 + /// Check whether a DID is a configured member. 49 + pub fn is_member(&self, did: &str) -> bool { 50 + self.members.iter().any(|m| m.did == did) 51 + } 52 + 53 + /// Get the role names assigned to a DID. 54 + pub fn get_member_roles(&self, did: &str) -> Vec<String> { 55 + self.members 56 + .iter() 57 + .find(|m| m.did == did) 58 + .map(|m| m.roles.clone()) 59 + .unwrap_or_default() 60 + } 61 + 62 + /// Get all endpoint patterns that a DID is allowed to access (aggregated from all roles). 63 + pub fn get_allowed_endpoints(&self, did: &str) -> Vec<String> { 64 + let roles = self.get_member_roles(did); 65 + let mut endpoints = Vec::new(); 66 + for role_name in &roles { 67 + if let Some(role) = self.roles.get(role_name) { 68 + endpoints.extend(role.endpoints.clone()); 69 + } 70 + } 71 + endpoints 72 + } 73 + 74 + /// Check whether a DID can access a specific endpoint. 75 + /// Supports wildcard matching: `com.atproto.admin.*` matches `com.atproto.admin.getAccountInfo`. 76 + pub fn can_access_endpoint(&self, did: &str, endpoint: &str) -> bool { 77 + let allowed = self.get_allowed_endpoints(did); 78 + for pattern in &allowed { 79 + if matches_endpoint_pattern(pattern, endpoint) { 80 + return true; 81 + } 82 + } 83 + false 84 + } 85 + } 86 + 87 + /// Match an endpoint against a pattern. Supports trailing `*` wildcard. 88 + /// e.g. `com.atproto.admin.*` matches `com.atproto.admin.getAccountInfo` 89 + fn matches_endpoint_pattern(pattern: &str, endpoint: &str) -> bool { 90 + if pattern == endpoint { 91 + return true; 92 + } 93 + if let Some(prefix) = pattern.strip_suffix('*') { 94 + return endpoint.starts_with(prefix); 95 + } 96 + false 97 + } 98 + 99 + #[cfg(test)] 100 + mod tests { 101 + use super::*; 102 + 103 + fn test_config() -> RbacConfig { 104 + let yaml = r#" 105 + roles: 106 + pds-admin: 107 + description: "Full admin" 108 + endpoints: 109 + - "com.atproto.admin.*" 110 + - "com.atproto.server.createInviteCode" 111 + - "com.atproto.server.createAccount" 112 + moderator: 113 + description: "Content moderation" 114 + endpoints: 115 + - "com.atproto.admin.getAccountInfo" 116 + - "com.atproto.admin.getAccountInfos" 117 + - "com.atproto.admin.getSubjectStatus" 118 + - "com.atproto.admin.updateSubjectStatus" 119 + - "com.atproto.admin.searchAccounts" 120 + - "com.atproto.admin.getInviteCodes" 121 + invite-manager: 122 + description: "Invite management" 123 + endpoints: 124 + - "com.atproto.admin.getInviteCodes" 125 + - "com.atproto.admin.disableInviteCodes" 126 + - "com.atproto.server.createInviteCode" 127 + 128 + members: 129 + - did: "did:plc:admin123" 130 + roles: 131 + - pds-admin 132 + - did: "did:plc:mod456" 133 + roles: 134 + - moderator 135 + - did: "did:plc:both789" 136 + roles: 137 + - moderator 138 + - invite-manager 139 + "#; 140 + serde_yaml::from_str(yaml).unwrap() 141 + } 142 + 143 + #[test] 144 + fn test_is_member() { 145 + let config = test_config(); 146 + assert!(config.is_member("did:plc:admin123")); 147 + assert!(config.is_member("did:plc:mod456")); 148 + assert!(!config.is_member("did:plc:unknown")); 149 + } 150 + 151 + #[test] 152 + fn test_get_member_roles() { 153 + let config = test_config(); 154 + assert_eq!(config.get_member_roles("did:plc:admin123"), vec!["pds-admin"]); 155 + assert_eq!( 156 + config.get_member_roles("did:plc:both789"), 157 + vec!["moderator", "invite-manager"] 158 + ); 159 + assert!(config.get_member_roles("did:plc:unknown").is_empty()); 160 + } 161 + 162 + #[test] 163 + fn test_wildcard_matching() { 164 + assert!(matches_endpoint_pattern( 165 + "com.atproto.admin.*", 166 + "com.atproto.admin.getAccountInfo" 167 + )); 168 + assert!(matches_endpoint_pattern( 169 + "com.atproto.admin.*", 170 + "com.atproto.admin.deleteAccount" 171 + )); 172 + assert!(!matches_endpoint_pattern( 173 + "com.atproto.admin.*", 174 + "com.atproto.server.createAccount" 175 + )); 176 + } 177 + 178 + #[test] 179 + fn test_exact_matching() { 180 + assert!(matches_endpoint_pattern( 181 + "com.atproto.server.createInviteCode", 182 + "com.atproto.server.createInviteCode" 183 + )); 184 + assert!(!matches_endpoint_pattern( 185 + "com.atproto.server.createInviteCode", 186 + "com.atproto.server.createAccount" 187 + )); 188 + } 189 + 190 + #[test] 191 + fn test_admin_can_access_all_admin_endpoints() { 192 + let config = test_config(); 193 + assert!(config.can_access_endpoint("did:plc:admin123", "com.atproto.admin.getAccountInfo")); 194 + assert!(config.can_access_endpoint("did:plc:admin123", "com.atproto.admin.deleteAccount")); 195 + assert!(config.can_access_endpoint( 196 + "did:plc:admin123", 197 + "com.atproto.server.createInviteCode" 198 + )); 199 + assert!(config.can_access_endpoint("did:plc:admin123", "com.atproto.server.createAccount")); 200 + } 201 + 202 + #[test] 203 + fn test_moderator_limited_access() { 204 + let config = test_config(); 205 + assert!(config.can_access_endpoint("did:plc:mod456", "com.atproto.admin.getAccountInfo")); 206 + assert!(config.can_access_endpoint( 207 + "did:plc:mod456", 208 + "com.atproto.admin.updateSubjectStatus" 209 + )); 210 + assert!(!config.can_access_endpoint("did:plc:mod456", "com.atproto.admin.deleteAccount")); 211 + assert!(!config.can_access_endpoint( 212 + "did:plc:mod456", 213 + "com.atproto.server.createInviteCode" 214 + )); 215 + } 216 + 217 + #[test] 218 + fn test_combined_roles() { 219 + let config = test_config(); 220 + // Has moderator + invite-manager 221 + assert!(config.can_access_endpoint("did:plc:both789", "com.atproto.admin.getAccountInfo")); 222 + assert!(config.can_access_endpoint("did:plc:both789", "com.atproto.admin.getInviteCodes")); 223 + assert!(config.can_access_endpoint( 224 + "did:plc:both789", 225 + "com.atproto.server.createInviteCode" 226 + )); 227 + assert!(config.can_access_endpoint( 228 + "did:plc:both789", 229 + "com.atproto.admin.disableInviteCodes" 230 + )); 231 + // But not delete or create account 232 + assert!(!config.can_access_endpoint("did:plc:both789", "com.atproto.admin.deleteAccount")); 233 + assert!(!config.can_access_endpoint( 234 + "did:plc:both789", 235 + "com.atproto.server.createAccount" 236 + )); 237 + } 238 + 239 + #[test] 240 + fn test_non_member_no_access() { 241 + let config = test_config(); 242 + assert!(!config.can_access_endpoint( 243 + "did:plc:unknown", 244 + "com.atproto.admin.getAccountInfo" 245 + )); 246 + } 247 + 248 + #[test] 249 + fn test_validate_rejects_undefined_role() { 250 + let yaml = r#" 251 + roles: 252 + admin: 253 + description: "Admin" 254 + endpoints: ["com.atproto.admin.*"] 255 + members: 256 + - did: "did:plc:test" 257 + roles: 258 + - nonexistent 259 + "#; 260 + let config: RbacConfig = serde_yaml::from_str(yaml).unwrap(); 261 + assert!(config.validate().is_err()); 262 + } 263 + }
+1071
src/admin/routes.rs
··· 1 + use axum::{ 2 + extract::{Extension, Path, Query, State}, 3 + http::StatusCode, 4 + response::{Html, IntoResponse, Redirect, Response}, 5 + }; 6 + use axum_extra::extract::cookie::{Cookie, SignedCookieJar}; 7 + use serde::{Deserialize, Serialize}; 8 + 9 + use crate::AppState; 10 + 11 + use super::middleware::{AdminPermissions, AdminSession}; 12 + use super::pds_proxy; 13 + use super::session; 14 + 15 + // ─── Response types from PDS API ───────────────────────────────────────────── 16 + 17 + #[derive(Debug, Deserialize, Serialize)] 18 + pub struct HealthResponse { 19 + pub version: Option<String>, 20 + } 21 + 22 + #[derive(Debug, Deserialize, Serialize)] 23 + #[serde(rename_all = "camelCase")] 24 + pub struct DescribeServerResponse { 25 + pub did: Option<String>, 26 + #[serde(default)] 27 + pub available_user_domains: Vec<String>, 28 + pub invite_code_required: Option<bool>, 29 + pub phone_verification_required: Option<bool>, 30 + } 31 + 32 + #[derive(Debug, Deserialize, Serialize)] 33 + pub struct ListReposResponse { 34 + #[serde(default)] 35 + pub repos: Vec<RepoInfo>, 36 + pub cursor: Option<String>, 37 + } 38 + 39 + #[derive(Debug, Deserialize, Serialize)] 40 + pub struct RepoInfo { 41 + pub did: String, 42 + pub head: Option<String>, 43 + } 44 + 45 + #[derive(Debug, Deserialize, Serialize)] 46 + #[serde(rename_all = "camelCase")] 47 + pub struct AccountInfo { 48 + pub did: String, 49 + pub handle: String, 50 + pub email: Option<String>, 51 + pub indexed_at: Option<String>, 52 + pub invited_by: Option<InviteCodeRef>, 53 + #[serde(default)] 54 + pub invites: Vec<InviteCodeInfo>, 55 + pub invites_disabled: Option<bool>, 56 + pub email_confirmed_at: Option<String>, 57 + pub deactivated_at: Option<String>, 58 + #[serde(default)] 59 + pub related_records: Vec<serde_json::Value>, 60 + pub invite_note: Option<String>, 61 + } 62 + 63 + #[derive(Debug, Deserialize, Serialize)] 64 + pub struct InviteCodeRef { 65 + pub code: Option<String>, 66 + } 67 + 68 + #[derive(Debug, Deserialize, Serialize)] 69 + #[serde(rename_all = "camelCase")] 70 + pub struct GetAccountInfosResponse { 71 + #[serde(default)] 72 + pub infos: Vec<AccountInfo>, 73 + } 74 + 75 + #[derive(Debug, Deserialize, Serialize)] 76 + #[serde(rename_all = "camelCase")] 77 + pub struct SubjectStatusResponse { 78 + pub subject: Option<serde_json::Value>, 79 + pub takedown: Option<StatusAttr>, 80 + } 81 + 82 + #[derive(Debug, Deserialize, Serialize)] 83 + pub struct StatusAttr { 84 + pub applied: bool, 85 + pub r#ref: Option<String>, 86 + } 87 + 88 + #[derive(Debug, Deserialize, Serialize)] 89 + #[serde(rename_all = "camelCase")] 90 + pub struct InviteCodeInfo { 91 + pub code: String, 92 + pub available: Option<i64>, 93 + pub disabled: Option<bool>, 94 + pub for_account: Option<String>, 95 + pub created_by: Option<String>, 96 + pub created_at: Option<String>, 97 + #[serde(default)] 98 + pub uses: Vec<InviteCodeUse>, 99 + } 100 + 101 + #[derive(Debug, Deserialize, Serialize)] 102 + #[serde(rename_all = "camelCase")] 103 + pub struct InviteCodeUse { 104 + pub used_by: String, 105 + pub used_at: Option<String>, 106 + } 107 + 108 + #[derive(Debug, Deserialize, Serialize)] 109 + pub struct GetInviteCodesResponse { 110 + #[serde(default)] 111 + pub codes: Vec<InviteCodeInfo>, 112 + pub cursor: Option<String>, 113 + } 114 + 115 + #[derive(Debug, Deserialize, Serialize)] 116 + pub struct CreateInviteCodeResponse { 117 + pub code: String, 118 + } 119 + 120 + #[derive(Debug, Deserialize, Serialize)] 121 + #[serde(rename_all = "camelCase")] 122 + pub struct SearchAccountsResponse { 123 + #[serde(default)] 124 + pub accounts: Vec<AccountInfo>, 125 + pub cursor: Option<String>, 126 + } 127 + 128 + #[derive(Debug, Deserialize, Serialize)] 129 + #[serde(rename_all = "camelCase")] 130 + pub struct CreateAccountResponse { 131 + pub did: String, 132 + pub handle: String, 133 + pub access_jwt: Option<String>, 134 + pub refresh_jwt: Option<String>, 135 + } 136 + 137 + // ─── Query parameter types ─────────────────────────────────────────────────── 138 + 139 + #[derive(Debug, Deserialize)] 140 + pub struct FlashParams { 141 + pub flash_success: Option<String>, 142 + pub flash_error: Option<String>, 143 + } 144 + 145 + #[derive(Debug, Deserialize)] 146 + pub struct SearchParams { 147 + pub q: Option<String>, 148 + pub flash_success: Option<String>, 149 + pub flash_error: Option<String>, 150 + } 151 + 152 + // ─── Form types ────────────────────────────────────────────────────────────── 153 + 154 + #[derive(Debug, Deserialize)] 155 + pub struct CreateInviteForm { 156 + pub use_count: Option<i64>, 157 + } 158 + 159 + #[derive(Debug, Deserialize)] 160 + pub struct DisableInviteCodesForm { 161 + pub codes: String, // comma-separated 162 + } 163 + 164 + #[derive(Debug, Deserialize)] 165 + pub struct CreateAccountForm { 166 + pub email: String, 167 + pub handle: String, 168 + } 169 + 170 + // ─── Helper functions ──────────────────────────────────────────────────────── 171 + 172 + fn admin_password(state: &AppState) -> &str { 173 + state 174 + .app_config 175 + .pds_admin_password 176 + .as_deref() 177 + .unwrap_or("") 178 + } 179 + 180 + fn pds_url(state: &AppState) -> &str { 181 + &state.app_config.pds_base_url 182 + } 183 + 184 + fn render_template(state: &AppState, template: &str, data: serde_json::Value) -> Response { 185 + use axum_template::TemplateEngine; 186 + match state.template_engine.render(template, data) { 187 + Ok(html) => Html(html).into_response(), 188 + Err(e) => { 189 + tracing::error!("Template render error for {}: {}", template, e); 190 + StatusCode::INTERNAL_SERVER_ERROR.into_response() 191 + } 192 + } 193 + } 194 + 195 + fn inject_nav_data( 196 + data: &mut serde_json::Value, 197 + session: &AdminSession, 198 + permissions: &AdminPermissions, 199 + ) { 200 + let obj = data.as_object_mut().unwrap(); 201 + obj.insert("admin_handle".into(), session.handle.clone().into()); 202 + obj.insert("admin_did".into(), session.did.clone().into()); 203 + obj.insert( 204 + "can_view_accounts".into(), 205 + permissions.can_view_accounts.into(), 206 + ); 207 + obj.insert( 208 + "can_manage_takedowns".into(), 209 + permissions.can_manage_takedowns.into(), 210 + ); 211 + obj.insert( 212 + "can_delete_account".into(), 213 + permissions.can_delete_account.into(), 214 + ); 215 + obj.insert( 216 + "can_reset_password".into(), 217 + permissions.can_reset_password.into(), 218 + ); 219 + obj.insert( 220 + "can_create_account".into(), 221 + permissions.can_create_account.into(), 222 + ); 223 + obj.insert( 224 + "can_manage_invites".into(), 225 + permissions.can_manage_invites.into(), 226 + ); 227 + obj.insert( 228 + "can_create_invite".into(), 229 + permissions.can_create_invite.into(), 230 + ); 231 + obj.insert( 232 + "can_send_email".into(), 233 + permissions.can_send_email.into(), 234 + ); 235 + } 236 + 237 + fn flash_redirect(base_path: &str, success: Option<&str>, error: Option<&str>) -> Response { 238 + let mut url = base_path.to_string(); 239 + let mut sep = '?'; 240 + if let Some(msg) = success { 241 + url.push_str(&format!("{}flash_success={}", sep, urlencoding::encode(msg))); 242 + sep = '&'; 243 + } 244 + if let Some(msg) = error { 245 + url.push_str(&format!("{}flash_error={}", sep, urlencoding::encode(msg))); 246 + } 247 + Redirect::to(&url).into_response() 248 + } 249 + 250 + fn generate_random_password() -> String { 251 + use rand::Rng; 252 + let chars = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"; 253 + let mut rng = rand::rng(); 254 + (0..24) 255 + .map(|_| chars[rng.random_range(0..chars.len())] as char) 256 + .collect() 257 + } 258 + 259 + // ─── Route handlers ────────────────────────────────────────────────────────── 260 + 261 + /// GET /admin/ — Dashboard 262 + pub async fn dashboard( 263 + State(state): State<AppState>, 264 + Extension(session): Extension<AdminSession>, 265 + Extension(permissions): Extension<AdminPermissions>, 266 + Query(flash): Query<FlashParams>, 267 + ) -> Response { 268 + let pds = pds_url(&state); 269 + 270 + // Fetch health, server description, and repo count in parallel 271 + let health_fut = pds_proxy::get_text(pds, "xrpc/_health"); 272 + let desc_fut = 273 + pds_proxy::public_xrpc_get::<DescribeServerResponse>(pds, "com.atproto.server.describeServer", &[]); 274 + let repos_fut = 275 + pds_proxy::public_xrpc_get::<ListReposResponse>(pds, "com.atproto.sync.listRepos", &[("limit", "1")]); 276 + 277 + let (health_res, desc_res, _repos_res) = tokio::join!(health_fut, desc_fut, repos_fut); 278 + 279 + let version = health_res 280 + .ok() 281 + .and_then(|t| { 282 + serde_json::from_str::<HealthResponse>(&t) 283 + .ok() 284 + .and_then(|h| h.version) 285 + }) 286 + .unwrap_or_else(|| "Unknown".to_string()); 287 + 288 + let desc = desc_res.ok(); 289 + 290 + // For account count, we fetch all repos 291 + let account_count_fut = 292 + pds_proxy::public_xrpc_get::<ListReposResponse>(pds, "com.atproto.sync.listRepos", &[("limit", "1000")]); 293 + let account_count = account_count_fut 294 + .await 295 + .map(|r| r.repos.len()) 296 + .unwrap_or(0); 297 + 298 + let mut data = serde_json::json!({ 299 + "version": version, 300 + "account_count": account_count, 301 + "server_did": desc.as_ref().and_then(|d| d.did.clone()).unwrap_or_default(), 302 + "available_domains": desc.as_ref().map(|d| d.available_user_domains.clone()).unwrap_or_default(), 303 + "invite_code_required": desc.as_ref().and_then(|d| d.invite_code_required).unwrap_or(false), 304 + "pds_hostname": state.app_config.pds_hostname, 305 + "active_page": "dashboard", 306 + }); 307 + 308 + if let Some(msg) = flash.flash_success { 309 + data["flash_success"] = msg.into(); 310 + } 311 + if let Some(msg) = flash.flash_error { 312 + data["flash_error"] = msg.into(); 313 + } 314 + 315 + inject_nav_data(&mut data, &session, &permissions); 316 + 317 + render_template(&state, "admin/dashboard.hbs", data) 318 + } 319 + 320 + /// GET /admin/accounts — Account list 321 + pub async fn accounts_list( 322 + State(state): State<AppState>, 323 + Extension(session): Extension<AdminSession>, 324 + Extension(permissions): Extension<AdminPermissions>, 325 + Query(flash): Query<FlashParams>, 326 + ) -> Response { 327 + if !permissions.can_view_accounts { 328 + return flash_redirect("/admin/", None, Some("Access denied")); 329 + } 330 + 331 + let pds = pds_url(&state); 332 + let password = admin_password(&state); 333 + 334 + // Get all repos first 335 + let repos = match pds_proxy::public_xrpc_get::<ListReposResponse>( 336 + pds, 337 + "com.atproto.sync.listRepos", 338 + &[("limit", "1000")], 339 + ) 340 + .await 341 + { 342 + Ok(r) => r, 343 + Err(e) => { 344 + tracing::error!("Failed to list repos: {}", e); 345 + return flash_redirect("/admin/", None, Some(&format!("Failed to list accounts: {}", e))); 346 + } 347 + }; 348 + 349 + let dids: Vec<String> = repos.repos.iter().map(|r| r.did.clone()).collect(); 350 + 351 + let accounts = if !dids.is_empty() { 352 + // Build query params for getAccountInfos 353 + let did_params: Vec<(&str, &str)> = dids.iter().map(|d| ("dids", d.as_str())).collect(); 354 + match pds_proxy::admin_xrpc_get::<GetAccountInfosResponse>( 355 + pds, 356 + password, 357 + "com.atproto.admin.getAccountInfos", 358 + &did_params, 359 + ) 360 + .await 361 + { 362 + Ok(res) => res.infos, 363 + Err(e) => { 364 + tracing::error!("Failed to get account infos: {}", e); 365 + vec![] 366 + } 367 + } 368 + } else { 369 + vec![] 370 + }; 371 + 372 + let mut data = serde_json::json!({ 373 + "accounts": accounts, 374 + "account_count": accounts.len(), 375 + "pds_hostname": state.app_config.pds_hostname, 376 + "active_page": "accounts", 377 + }); 378 + 379 + if let Some(msg) = flash.flash_success { 380 + data["flash_success"] = msg.into(); 381 + } 382 + if let Some(msg) = flash.flash_error { 383 + data["flash_error"] = msg.into(); 384 + } 385 + 386 + inject_nav_data(&mut data, &session, &permissions); 387 + 388 + render_template(&state, "admin/accounts.hbs", data) 389 + } 390 + 391 + /// GET /admin/accounts/:did — Account detail 392 + pub async fn account_detail( 393 + State(state): State<AppState>, 394 + Extension(session): Extension<AdminSession>, 395 + Extension(permissions): Extension<AdminPermissions>, 396 + Path(did): Path<String>, 397 + Query(flash): Query<FlashParams>, 398 + ) -> Response { 399 + if !permissions.can_view_accounts { 400 + return flash_redirect("/admin/", None, Some("Access denied")); 401 + } 402 + 403 + let pds = pds_url(&state); 404 + let password = admin_password(&state); 405 + 406 + let did_param: Vec<(&str, &str)> = vec![("did", did.as_str())]; 407 + let account_fut = pds_proxy::admin_xrpc_get::<AccountInfo>( 408 + pds, 409 + password, 410 + "com.atproto.admin.getAccountInfo", 411 + &did_param, 412 + ); 413 + 414 + let did_param2: Vec<(&str, &str)> = vec![("did", did.as_str())]; 415 + let status_fut = pds_proxy::admin_xrpc_get::<SubjectStatusResponse>( 416 + pds, 417 + password, 418 + "com.atproto.admin.getSubjectStatus", 419 + &did_param2, 420 + ); 421 + 422 + let (account_res, status_res) = tokio::join!(account_fut, status_fut); 423 + 424 + let account = match account_res { 425 + Ok(a) => a, 426 + Err(e) => { 427 + tracing::error!("Failed to get account info for {}: {}", did, e); 428 + return flash_redirect( 429 + "/admin/accounts", 430 + None, 431 + Some(&format!("Failed to get account: {}", e)), 432 + ); 433 + } 434 + }; 435 + 436 + let takedown = status_res 437 + .ok() 438 + .and_then(|s| s.takedown) 439 + .map(|t| t.applied) 440 + .unwrap_or(false); 441 + 442 + let mut data = serde_json::json!({ 443 + "account": account, 444 + "is_taken_down": takedown, 445 + "pds_hostname": state.app_config.pds_hostname, 446 + "active_page": "accounts", 447 + }); 448 + 449 + if let Some(msg) = flash.flash_success { 450 + data["flash_success"] = msg.into(); 451 + } 452 + if let Some(msg) = flash.flash_error { 453 + data["flash_error"] = msg.into(); 454 + } 455 + 456 + inject_nav_data(&mut data, &session, &permissions); 457 + 458 + render_template(&state, "admin/account_detail.hbs", data) 459 + } 460 + 461 + /// POST /admin/accounts/:did/takedown 462 + pub async fn takedown_account( 463 + State(state): State<AppState>, 464 + Extension(session): Extension<AdminSession>, 465 + Extension(_permissions): Extension<AdminPermissions>, 466 + Path(did): Path<String>, 467 + ) -> Response { 468 + let rbac = match &state.admin_rbac_config { 469 + Some(r) => r, 470 + None => return StatusCode::NOT_FOUND.into_response(), 471 + }; 472 + 473 + if !rbac.can_access_endpoint(&session.did, "com.atproto.admin.updateSubjectStatus") { 474 + return flash_redirect( 475 + &format!("/admin/accounts/{}", did), 476 + None, 477 + Some("Access denied: cannot manage takedowns"), 478 + ); 479 + } 480 + 481 + let body = serde_json::json!({ 482 + "subject": { 483 + "$type": "com.atproto.admin.defs#repoRef", 484 + "did": did, 485 + }, 486 + "takedown": { 487 + "applied": true, 488 + "ref": chrono::Utc::now().timestamp().to_string(), 489 + }, 490 + }); 491 + 492 + match pds_proxy::admin_xrpc_post_no_response( 493 + pds_url(&state), 494 + admin_password(&state), 495 + "com.atproto.admin.updateSubjectStatus", 496 + &body, 497 + ) 498 + .await 499 + { 500 + Ok(()) => flash_redirect( 501 + &format!("/admin/accounts/{}", did), 502 + Some("Account taken down successfully"), 503 + None, 504 + ), 505 + Err(e) => flash_redirect( 506 + &format!("/admin/accounts/{}", did), 507 + None, 508 + Some(&format!("Takedown failed: {}", e)), 509 + ), 510 + } 511 + } 512 + 513 + /// POST /admin/accounts/:did/untakedown 514 + pub async fn untakedown_account( 515 + State(state): State<AppState>, 516 + Extension(session): Extension<AdminSession>, 517 + Extension(_permissions): Extension<AdminPermissions>, 518 + Path(did): Path<String>, 519 + ) -> Response { 520 + let rbac = match &state.admin_rbac_config { 521 + Some(r) => r, 522 + None => return StatusCode::NOT_FOUND.into_response(), 523 + }; 524 + 525 + if !rbac.can_access_endpoint(&session.did, "com.atproto.admin.updateSubjectStatus") { 526 + return flash_redirect( 527 + &format!("/admin/accounts/{}", did), 528 + None, 529 + Some("Access denied"), 530 + ); 531 + } 532 + 533 + let body = serde_json::json!({ 534 + "subject": { 535 + "$type": "com.atproto.admin.defs#repoRef", 536 + "did": did, 537 + }, 538 + "takedown": { 539 + "applied": false, 540 + }, 541 + }); 542 + 543 + match pds_proxy::admin_xrpc_post_no_response( 544 + pds_url(&state), 545 + admin_password(&state), 546 + "com.atproto.admin.updateSubjectStatus", 547 + &body, 548 + ) 549 + .await 550 + { 551 + Ok(()) => flash_redirect( 552 + &format!("/admin/accounts/{}", did), 553 + Some("Takedown removed successfully"), 554 + None, 555 + ), 556 + Err(e) => flash_redirect( 557 + &format!("/admin/accounts/{}", did), 558 + None, 559 + Some(&format!("Failed to remove takedown: {}", e)), 560 + ), 561 + } 562 + } 563 + 564 + /// POST /admin/accounts/:did/delete 565 + pub async fn delete_account( 566 + State(state): State<AppState>, 567 + Extension(session): Extension<AdminSession>, 568 + Extension(_permissions): Extension<AdminPermissions>, 569 + Path(did): Path<String>, 570 + ) -> Response { 571 + let rbac = match &state.admin_rbac_config { 572 + Some(r) => r, 573 + None => return StatusCode::NOT_FOUND.into_response(), 574 + }; 575 + 576 + if !rbac.can_access_endpoint(&session.did, "com.atproto.admin.deleteAccount") { 577 + return flash_redirect( 578 + &format!("/admin/accounts/{}", did), 579 + None, 580 + Some("Access denied: cannot delete accounts"), 581 + ); 582 + } 583 + 584 + let body = serde_json::json!({ "did": did }); 585 + 586 + match pds_proxy::admin_xrpc_post_no_response( 587 + pds_url(&state), 588 + admin_password(&state), 589 + "com.atproto.admin.deleteAccount", 590 + &body, 591 + ) 592 + .await 593 + { 594 + Ok(()) => flash_redirect( 595 + "/admin/accounts", 596 + Some(&format!("Account {} deleted", did)), 597 + None, 598 + ), 599 + Err(e) => flash_redirect( 600 + &format!("/admin/accounts/{}", did), 601 + None, 602 + Some(&format!("Delete failed: {}", e)), 603 + ), 604 + } 605 + } 606 + 607 + /// POST /admin/accounts/:did/reset-password 608 + pub async fn reset_password( 609 + State(state): State<AppState>, 610 + Extension(session): Extension<AdminSession>, 611 + Extension(_permissions): Extension<AdminPermissions>, 612 + Path(did): Path<String>, 613 + Query(_flash): Query<FlashParams>, 614 + ) -> Response { 615 + let rbac = match &state.admin_rbac_config { 616 + Some(r) => r, 617 + None => return StatusCode::NOT_FOUND.into_response(), 618 + }; 619 + 620 + if !rbac.can_access_endpoint(&session.did, "com.atproto.admin.updateAccountPassword") { 621 + return flash_redirect( 622 + &format!("/admin/accounts/{}", did), 623 + None, 624 + Some("Access denied: cannot reset passwords"), 625 + ); 626 + } 627 + 628 + let new_password = generate_random_password(); 629 + let body = serde_json::json!({ 630 + "did": did, 631 + "password": new_password, 632 + }); 633 + 634 + match pds_proxy::admin_xrpc_post_no_response( 635 + pds_url(&state), 636 + admin_password(&state), 637 + "com.atproto.admin.updateAccountPassword", 638 + &body, 639 + ) 640 + .await 641 + { 642 + Ok(()) => { 643 + // Redirect with the new password as a flash param 644 + let encoded = urlencoding::encode(&new_password); 645 + Redirect::to(&format!( 646 + "/admin/accounts/{}?flash_success=Password+reset+successfully&new_password={}", 647 + did, encoded 648 + )) 649 + .into_response() 650 + } 651 + Err(e) => flash_redirect( 652 + &format!("/admin/accounts/{}", did), 653 + None, 654 + Some(&format!("Password reset failed: {}", e)), 655 + ), 656 + } 657 + } 658 + 659 + /// POST /admin/accounts/:did/disable-invites 660 + pub async fn disable_account_invites( 661 + State(state): State<AppState>, 662 + Extension(session): Extension<AdminSession>, 663 + Extension(_permissions): Extension<AdminPermissions>, 664 + Path(did): Path<String>, 665 + ) -> Response { 666 + let rbac = match &state.admin_rbac_config { 667 + Some(r) => r, 668 + None => return StatusCode::NOT_FOUND.into_response(), 669 + }; 670 + 671 + if !rbac.can_access_endpoint(&session.did, "com.atproto.admin.disableAccountInvites") { 672 + return flash_redirect( 673 + &format!("/admin/accounts/{}", did), 674 + None, 675 + Some("Access denied"), 676 + ); 677 + } 678 + 679 + let body = serde_json::json!({ "account": did }); 680 + 681 + match pds_proxy::admin_xrpc_post_no_response( 682 + pds_url(&state), 683 + admin_password(&state), 684 + "com.atproto.admin.disableAccountInvites", 685 + &body, 686 + ) 687 + .await 688 + { 689 + Ok(()) => flash_redirect( 690 + &format!("/admin/accounts/{}", did), 691 + Some("Invites disabled"), 692 + None, 693 + ), 694 + Err(e) => flash_redirect( 695 + &format!("/admin/accounts/{}", did), 696 + None, 697 + Some(&format!("Failed: {}", e)), 698 + ), 699 + } 700 + } 701 + 702 + /// POST /admin/accounts/:did/enable-invites 703 + pub async fn enable_account_invites( 704 + State(state): State<AppState>, 705 + Extension(session): Extension<AdminSession>, 706 + Extension(_permissions): Extension<AdminPermissions>, 707 + Path(did): Path<String>, 708 + ) -> Response { 709 + let rbac = match &state.admin_rbac_config { 710 + Some(r) => r, 711 + None => return StatusCode::NOT_FOUND.into_response(), 712 + }; 713 + 714 + if !rbac.can_access_endpoint(&session.did, "com.atproto.admin.enableAccountInvites") { 715 + return flash_redirect( 716 + &format!("/admin/accounts/{}", did), 717 + None, 718 + Some("Access denied"), 719 + ); 720 + } 721 + 722 + let body = serde_json::json!({ "account": did }); 723 + 724 + match pds_proxy::admin_xrpc_post_no_response( 725 + pds_url(&state), 726 + admin_password(&state), 727 + "com.atproto.admin.enableAccountInvites", 728 + &body, 729 + ) 730 + .await 731 + { 732 + Ok(()) => flash_redirect( 733 + &format!("/admin/accounts/{}", did), 734 + Some("Invites enabled"), 735 + None, 736 + ), 737 + Err(e) => flash_redirect( 738 + &format!("/admin/accounts/{}", did), 739 + None, 740 + Some(&format!("Failed: {}", e)), 741 + ), 742 + } 743 + } 744 + 745 + /// GET /admin/invite-codes — List invite codes 746 + pub async fn invite_codes_list( 747 + State(state): State<AppState>, 748 + Extension(session): Extension<AdminSession>, 749 + Extension(permissions): Extension<AdminPermissions>, 750 + Query(flash): Query<FlashParams>, 751 + ) -> Response { 752 + let rbac = match &state.admin_rbac_config { 753 + Some(r) => r, 754 + None => return StatusCode::NOT_FOUND.into_response(), 755 + }; 756 + 757 + if !rbac.can_access_endpoint(&session.did, "com.atproto.admin.getInviteCodes") { 758 + return flash_redirect("/admin/", None, Some("Access denied")); 759 + } 760 + 761 + let codes = match pds_proxy::admin_xrpc_get::<GetInviteCodesResponse>( 762 + pds_url(&state), 763 + admin_password(&state), 764 + "com.atproto.admin.getInviteCodes", 765 + &[("limit", "100"), ("sort", "recent")], 766 + ) 767 + .await 768 + { 769 + Ok(res) => res.codes, 770 + Err(e) => { 771 + tracing::error!("Failed to get invite codes: {}", e); 772 + vec![] 773 + } 774 + }; 775 + 776 + let mut data = serde_json::json!({ 777 + "codes": codes, 778 + "pds_hostname": state.app_config.pds_hostname, 779 + "active_page": "invite_codes", 780 + }); 781 + 782 + if let Some(msg) = flash.flash_success { 783 + data["flash_success"] = msg.into(); 784 + } 785 + if let Some(msg) = flash.flash_error { 786 + data["flash_error"] = msg.into(); 787 + } 788 + 789 + inject_nav_data(&mut data, &session, &permissions); 790 + 791 + render_template(&state, "admin/invite_codes.hbs", data) 792 + } 793 + 794 + /// POST /admin/invite-codes/create 795 + pub async fn create_invite_code( 796 + State(state): State<AppState>, 797 + Extension(session): Extension<AdminSession>, 798 + Extension(_permissions): Extension<AdminPermissions>, 799 + axum::extract::Form(form): axum::extract::Form<CreateInviteForm>, 800 + ) -> Response { 801 + let rbac = match &state.admin_rbac_config { 802 + Some(r) => r, 803 + None => return StatusCode::NOT_FOUND.into_response(), 804 + }; 805 + 806 + if !rbac.can_access_endpoint(&session.did, "com.atproto.server.createInviteCode") { 807 + return flash_redirect("/admin/invite-codes", None, Some("Access denied")); 808 + } 809 + 810 + let use_count = form.use_count.unwrap_or(1).max(1); 811 + let body = serde_json::json!({ "useCount": use_count }); 812 + 813 + match pds_proxy::admin_xrpc_post::<_, CreateInviteCodeResponse>( 814 + pds_url(&state), 815 + admin_password(&state), 816 + "com.atproto.server.createInviteCode", 817 + &body, 818 + ) 819 + .await 820 + { 821 + Ok(res) => flash_redirect( 822 + "/admin/invite-codes", 823 + Some(&format!("Invite code created: {}", res.code)), 824 + None, 825 + ), 826 + Err(e) => flash_redirect( 827 + "/admin/invite-codes", 828 + None, 829 + Some(&format!("Failed to create invite code: {}", e)), 830 + ), 831 + } 832 + } 833 + 834 + /// POST /admin/invite-codes/disable 835 + pub async fn disable_invite_codes( 836 + State(state): State<AppState>, 837 + Extension(session): Extension<AdminSession>, 838 + Extension(_permissions): Extension<AdminPermissions>, 839 + axum::extract::Form(form): axum::extract::Form<DisableInviteCodesForm>, 840 + ) -> Response { 841 + let rbac = match &state.admin_rbac_config { 842 + Some(r) => r, 843 + None => return StatusCode::NOT_FOUND.into_response(), 844 + }; 845 + 846 + if !rbac.can_access_endpoint(&session.did, "com.atproto.admin.disableInviteCodes") { 847 + return flash_redirect("/admin/invite-codes", None, Some("Access denied")); 848 + } 849 + 850 + let codes: Vec<String> = form 851 + .codes 852 + .split(',') 853 + .map(|s| s.trim().to_string()) 854 + .filter(|s| !s.is_empty()) 855 + .collect(); 856 + 857 + let body = serde_json::json!({ 858 + "codes": codes, 859 + "accounts": [], 860 + }); 861 + 862 + match pds_proxy::admin_xrpc_post_no_response( 863 + pds_url(&state), 864 + admin_password(&state), 865 + "com.atproto.admin.disableInviteCodes", 866 + &body, 867 + ) 868 + .await 869 + { 870 + Ok(()) => flash_redirect( 871 + "/admin/invite-codes", 872 + Some("Invite codes disabled"), 873 + None, 874 + ), 875 + Err(e) => flash_redirect( 876 + "/admin/invite-codes", 877 + None, 878 + Some(&format!("Failed: {}", e)), 879 + ), 880 + } 881 + } 882 + 883 + /// GET /admin/create-account — Form 884 + pub async fn get_create_account( 885 + State(state): State<AppState>, 886 + Extension(session): Extension<AdminSession>, 887 + Extension(permissions): Extension<AdminPermissions>, 888 + Query(flash): Query<FlashParams>, 889 + ) -> Response { 890 + let rbac = match &state.admin_rbac_config { 891 + Some(r) => r, 892 + None => return StatusCode::NOT_FOUND.into_response(), 893 + }; 894 + 895 + if !rbac.can_access_endpoint(&session.did, "com.atproto.server.createAccount") { 896 + return flash_redirect("/admin/", None, Some("Access denied")); 897 + } 898 + 899 + let mut data = serde_json::json!({ 900 + "pds_hostname": state.app_config.pds_hostname, 901 + "active_page": "create_account", 902 + }); 903 + 904 + if let Some(msg) = flash.flash_success { 905 + data["flash_success"] = msg.into(); 906 + } 907 + if let Some(msg) = flash.flash_error { 908 + data["flash_error"] = msg.into(); 909 + } 910 + 911 + inject_nav_data(&mut data, &session, &permissions); 912 + 913 + render_template(&state, "admin/create_account.hbs", data) 914 + } 915 + 916 + /// POST /admin/create-account — Create account 917 + pub async fn post_create_account( 918 + State(state): State<AppState>, 919 + Extension(session): Extension<AdminSession>, 920 + Extension(permissions): Extension<AdminPermissions>, 921 + axum::extract::Form(form): axum::extract::Form<CreateAccountForm>, 922 + ) -> Response { 923 + let rbac = match &state.admin_rbac_config { 924 + Some(r) => r, 925 + None => return StatusCode::NOT_FOUND.into_response(), 926 + }; 927 + 928 + if !rbac.can_access_endpoint(&session.did, "com.atproto.server.createAccount") { 929 + return flash_redirect("/admin/create-account", None, Some("Access denied")); 930 + } 931 + 932 + let pds = pds_url(&state); 933 + let password_str = admin_password(&state); 934 + 935 + // Step 1: Create invite code 936 + let invite_body = serde_json::json!({ "useCount": 1 }); 937 + let invite_res = match pds_proxy::admin_xrpc_post::<_, CreateInviteCodeResponse>( 938 + pds, 939 + password_str, 940 + "com.atproto.server.createInviteCode", 941 + &invite_body, 942 + ) 943 + .await 944 + { 945 + Ok(res) => res, 946 + Err(e) => { 947 + return flash_redirect( 948 + "/admin/create-account", 949 + None, 950 + Some(&format!("Failed to create invite code: {}", e)), 951 + ); 952 + } 953 + }; 954 + 955 + // Step 2: Create account 956 + let account_password = generate_random_password(); 957 + let account_body = serde_json::json!({ 958 + "email": form.email, 959 + "handle": form.handle, 960 + "password": account_password, 961 + "inviteCode": invite_res.code, 962 + }); 963 + 964 + match pds_proxy::admin_xrpc_post::<_, CreateAccountResponse>( 965 + pds, 966 + password_str, 967 + "com.atproto.server.createAccount", 968 + &account_body, 969 + ) 970 + .await 971 + { 972 + Ok(res) => { 973 + let mut data = serde_json::json!({ 974 + "pds_hostname": state.app_config.pds_hostname, 975 + "active_page": "create_account", 976 + "created": true, 977 + "created_did": res.did, 978 + "created_handle": res.handle, 979 + "created_email": form.email, 980 + "created_password": account_password, 981 + "created_invite_code": invite_res.code, 982 + }); 983 + 984 + inject_nav_data(&mut data, &session, &permissions); 985 + 986 + render_template(&state, "admin/create_account.hbs", data) 987 + } 988 + Err(e) => flash_redirect( 989 + "/admin/create-account", 990 + None, 991 + Some(&format!("Failed to create account: {}", e)), 992 + ), 993 + } 994 + } 995 + 996 + /// GET /admin/search — Search accounts 997 + pub async fn search_accounts( 998 + State(state): State<AppState>, 999 + Extension(session): Extension<AdminSession>, 1000 + Extension(permissions): Extension<AdminPermissions>, 1001 + Query(params): Query<SearchParams>, 1002 + ) -> Response { 1003 + let rbac = match &state.admin_rbac_config { 1004 + Some(r) => r, 1005 + None => return StatusCode::NOT_FOUND.into_response(), 1006 + }; 1007 + 1008 + if !rbac.can_access_endpoint(&session.did, "com.atproto.admin.searchAccounts") { 1009 + return flash_redirect("/admin/", None, Some("Access denied")); 1010 + } 1011 + 1012 + let query = params.q.unwrap_or_default(); 1013 + 1014 + let accounts = if !query.is_empty() { 1015 + match pds_proxy::admin_xrpc_get::<SearchAccountsResponse>( 1016 + pds_url(&state), 1017 + admin_password(&state), 1018 + "com.atproto.admin.searchAccounts", 1019 + &[("query", &query)], 1020 + ) 1021 + .await 1022 + { 1023 + Ok(res) => res.accounts, 1024 + Err(e) => { 1025 + tracing::error!("Search failed: {}", e); 1026 + vec![] 1027 + } 1028 + } 1029 + } else { 1030 + vec![] 1031 + }; 1032 + 1033 + let mut data = serde_json::json!({ 1034 + "accounts": accounts, 1035 + "account_count": accounts.len(), 1036 + "search_query": query, 1037 + "pds_hostname": state.app_config.pds_hostname, 1038 + "active_page": "accounts", 1039 + }); 1040 + 1041 + if let Some(msg) = params.flash_success { 1042 + data["flash_success"] = msg.into(); 1043 + } 1044 + if let Some(msg) = params.flash_error { 1045 + data["flash_error"] = msg.into(); 1046 + } 1047 + 1048 + inject_nav_data(&mut data, &session, &permissions); 1049 + 1050 + render_template(&state, "admin/accounts.hbs", data) 1051 + } 1052 + 1053 + /// POST /admin/logout — Clear session and redirect to login 1054 + pub async fn logout( 1055 + State(state): State<AppState>, 1056 + jar: SignedCookieJar, 1057 + ) -> Response { 1058 + if let Some(cookie) = jar.get("__gatekeeper_admin_session") { 1059 + let session_id = cookie.value().to_string(); 1060 + let _ = session::delete_session(&state.pds_gatekeeper_pool, &session_id).await; 1061 + } 1062 + 1063 + let mut removal = Cookie::build("__gatekeeper_admin_session") 1064 + .path("/admin/") 1065 + .build(); 1066 + removal.make_removal(); 1067 + 1068 + let updated_jar = jar.remove(removal); 1069 + 1070 + (updated_jar, Redirect::to("/admin/login")).into_response() 1071 + }
+79
src/admin/session.rs
··· 1 + use anyhow::Result; 2 + use chrono::Utc; 3 + use sqlx::SqlitePool; 4 + use uuid::Uuid; 5 + 6 + #[derive(Debug, Clone, sqlx::FromRow)] 7 + pub struct AdminSessionRow { 8 + pub session_id: String, 9 + pub did: String, 10 + pub handle: String, 11 + pub created_at: String, 12 + pub expires_at: String, 13 + } 14 + 15 + /// Creates a new admin session and returns the generated session_id. 16 + pub async fn create_session( 17 + pool: &SqlitePool, 18 + did: &str, 19 + handle: &str, 20 + ttl_hours: u64, 21 + ) -> Result<String> { 22 + let session_id = Uuid::new_v4().to_string(); 23 + let now = Utc::now(); 24 + let created_at = now.to_rfc3339(); 25 + let expires_at = (now + chrono::Duration::hours(ttl_hours as i64)).to_rfc3339(); 26 + 27 + sqlx::query( 28 + "INSERT INTO admin_sessions (session_id, did, handle, created_at, expires_at) VALUES (?, ?, ?, ?, ?)", 29 + ) 30 + .bind(&session_id) 31 + .bind(did) 32 + .bind(handle) 33 + .bind(&created_at) 34 + .bind(&expires_at) 35 + .execute(pool) 36 + .await?; 37 + 38 + Ok(session_id) 39 + } 40 + 41 + /// Looks up a session by ID. Returns None if the session does not exist or has expired. 42 + pub async fn get_session( 43 + pool: &SqlitePool, 44 + session_id: &str, 45 + ) -> Result<Option<AdminSessionRow>> { 46 + let now = Utc::now().to_rfc3339(); 47 + 48 + let row = sqlx::query_as::<_, AdminSessionRow>( 49 + "SELECT session_id, did, handle, created_at, expires_at FROM admin_sessions WHERE session_id = ? AND expires_at > ?", 50 + ) 51 + .bind(session_id) 52 + .bind(&now) 53 + .fetch_optional(pool) 54 + .await?; 55 + 56 + Ok(row) 57 + } 58 + 59 + /// Deletes a session by ID. 60 + pub async fn delete_session(pool: &SqlitePool, session_id: &str) -> Result<()> { 61 + sqlx::query("DELETE FROM admin_sessions WHERE session_id = ?") 62 + .bind(session_id) 63 + .execute(pool) 64 + .await?; 65 + 66 + Ok(()) 67 + } 68 + 69 + /// Deletes all expired sessions and returns the number of rows removed. 70 + pub async fn cleanup_expired_sessions(pool: &SqlitePool) -> Result<u64> { 71 + let now = Utc::now().to_rfc3339(); 72 + 73 + let result = sqlx::query("DELETE FROM admin_sessions WHERE expires_at <= ?") 74 + .bind(&now) 75 + .execute(pool) 76 + .await?; 77 + 78 + Ok(result.rows_affected()) 79 + }
+94 -1
src/main.rs
··· 37 37 use tracing::log; 38 38 use tracing_subscriber::{EnvFilter, fmt, prelude::*}; 39 39 40 + mod admin; 40 41 mod auth; 41 42 mod gate; 42 43 pub mod helpers; ··· 70 71 pds_service_did: Did<'static>, 71 72 gate_jwe_key: Vec<u8>, 72 73 captcha_success_redirects: Vec<String>, 74 + // Admin portal config 75 + pub pds_admin_password: Option<String>, 76 + pub pds_hostname: String, 77 + pub admin_session_ttl_hours: u64, 73 78 } 74 79 75 80 impl AppConfig { ··· 129 134 } 130 135 }; 131 136 137 + let pds_hostname = env::var("PDS_HOSTNAME").unwrap_or_else(|_| "localhost".to_string()); 138 + 139 + let pds_admin_password = env::var("PDS_ADMIN_PASSWORD").ok(); 140 + 141 + let admin_session_ttl_hours = env::var("GATEKEEPER_ADMIN_SESSION_TTL_HOURS") 142 + .ok() 143 + .and_then(|v| v.parse().ok()) 144 + .unwrap_or(24u64); 145 + 132 146 AppConfig { 133 147 pds_base_url, 134 148 mailer_from, ··· 142 156 .expect("PDS_SERVICE_DID is not a valid did or could not infer from PDS_HOSTNAME"), 143 157 gate_jwe_key, 144 158 captcha_success_redirects, 159 + pds_admin_password, 160 + pds_hostname, 161 + admin_session_ttl_hours, 145 162 } 146 163 } 147 164 } ··· 156 173 resolver: Arc<PublicResolver>, 157 174 handle_cache: auth::HandleCache, 158 175 app_config: AppConfig, 176 + // Admin portal 177 + admin_rbac_config: Option<Arc<admin::rbac::RbacConfig>>, 178 + admin_oauth_client: Option<Arc<admin::oauth::AdminOAuthClient>>, 179 + cookie_key: axum_extra::extract::cookie::Key, 180 + } 181 + 182 + impl axum::extract::FromRef<AppState> for axum_extra::extract::cookie::Key { 183 + fn from_ref(state: &AppState) -> Self { 184 + state.cookie_key.clone() 185 + } 159 186 } 160 187 161 188 async fn root_handler() -> impl axum::response::IntoResponse { ··· 273 300 let mut resolver = PublicResolver::default(); 274 301 resolver = resolver.with_plc_source(plc_source.clone()); 275 302 303 + let app_config = AppConfig::new(); 304 + 305 + // Admin portal setup (opt-in via GATEKEEPER_ADMIN_RBAC_CONFIG) 306 + let admin_rbac_config = env::var("GATEKEEPER_ADMIN_RBAC_CONFIG") 307 + .ok() 308 + .map(|path| { 309 + let config = admin::rbac::RbacConfig::load_from_file(&path) 310 + .unwrap_or_else(|e| panic!("Failed to load RBAC config from {}: {}", path, e)); 311 + log::info!("Loaded admin RBAC config from {} ({} members)", path, config.members.len()); 312 + Arc::new(config) 313 + }); 314 + 315 + let admin_oauth_client = if admin_rbac_config.is_some() { 316 + match admin::oauth::init_oauth_client(&app_config.pds_hostname) { 317 + Ok(client) => { 318 + log::info!("Admin OAuth client initialized for {}", app_config.pds_hostname); 319 + Some(Arc::new(client)) 320 + } 321 + Err(e) => { 322 + log::error!("Failed to initialize admin OAuth client: {}. Admin portal will be disabled.", e); 323 + None 324 + } 325 + } 326 + } else { 327 + None 328 + }; 329 + 330 + // Cookie signing key for admin sessions 331 + let cookie_key = env::var("GATEKEEPER_ADMIN_COOKIE_SECRET") 332 + .ok() 333 + .and_then(|hex_str| hex::decode(hex_str).ok()) 334 + .unwrap_or_else(|| app_config.gate_jwe_key.clone()); 335 + let cookie_key = { 336 + // Key::from requires at least 64 bytes; derive by repeating if needed 337 + let mut key_bytes = cookie_key.clone(); 338 + while key_bytes.len() < 64 { 339 + key_bytes.extend_from_slice(&cookie_key); 340 + } 341 + axum_extra::extract::cookie::Key::from(&key_bytes[..64]) 342 + }; 343 + 276 344 let state = AppState { 277 345 account_pool, 278 346 pds_gatekeeper_pool, ··· 281 349 template_engine: Engine::from(hbs), 282 350 resolver: Arc::new(resolver), 283 351 handle_cache: auth::HandleCache::new(), 284 - app_config: AppConfig::new(), 352 + app_config, 353 + admin_rbac_config, 354 + admin_oauth_client, 355 + cookie_key, 285 356 }; 286 357 287 358 // Rate limiting ··· 384 455 get(get_gate).post(post_gate.layer(GovernorLayer::new(captcha_governor_conf))), 385 456 ); 386 457 } 458 + 459 + // Mount admin portal if RBAC config is loaded 460 + if state.admin_rbac_config.is_some() { 461 + let admin_router = admin::router(state.clone()); 462 + app = app.nest("/admin", admin_router); 463 + log::info!("Admin portal mounted at /admin/"); 464 + } 465 + 466 + // Background cleanup for admin sessions 467 + let cleanup_pool = state.pds_gatekeeper_pool.clone(); 468 + let admin_enabled = state.admin_rbac_config.is_some(); 469 + tokio::spawn(async move { 470 + let mut interval = tokio::time::interval(Duration::from_secs(300)); 471 + loop { 472 + interval.tick().await; 473 + if admin_enabled { 474 + if let Err(e) = admin::session::cleanup_expired_sessions(&cleanup_pool).await { 475 + tracing::error!("Failed to cleanup expired admin sessions: {}", e); 476 + } 477 + } 478 + } 479 + }); 387 480 388 481 let app = app 389 482 .layer(CompressionLayer::new())