# Feefer API reference

Browse `/docs` or fetch generated OpenAPI 3.1 schemas from `/openapi.json`. `/docs.json` remains the compatibility catalog. This guide describes the architecture update's runtime behavior and contract changes.

## Authentication and permissions

Send `Authorization: Bearer <token>`. Registration/login return the complete prefixed value. Tokens expire after `ACCESS_TOKEN_TTL` (default 30d); each login revokes older tokens, including tokens issued in the same second. Database roles/bans apply on every protected request.

| Role      | Priority | Access                                     |
| --------- | -------- | ------------------------------------------ |
| user      | 0        | Random images                              |
| support   | 1        | User search and images                     |
| moderator | 2        | Same route access as support               |
| admin     | 3        | User/storage administration                |
| owner     | 4        | Admin access with higher mutation priority |

Mutations reject self-edits and require the actor to strictly outrank the target. Role changes also require the actor to outrank the granted role. No API role can grant owner. Search has no target-priority restriction.

## Public and documentation routes

| Method/path         | Response                                                                                             |
| ------------------- | ---------------------------------------------------------------------------------------------------- |
| `GET /`             | `{ "status": 200, "message": "🦊 The API is up!", "docs": "/docs" }`                                 |
| `GET /health`       | Status, liveness message, ISO timestamp, uptimeSeconds, responseTimeMs; no dependency check          |
| `GET /ready`        | `{ "status": 200, "ready": true }`; 503 when database/migrations/storage are unavailable or stopping |
| `GET /docs`         | Searchable HTML reference                                                                            |
| `GET /docs.md`      | This Markdown reference                                                                              |
| `GET /docs.json`    | Compatibility catalog: generatedAt, baseUrls, roles, sections, string examples                       |
| `GET /openapi.json` | OpenAPI 3.1 generated from runtime contracts and schemas                                             |

Health/readiness bypass quotas. Other public routes have global limits. The listener opens only after initial dependency checks pass.

## Registration and login

Both accept JSON:

```json
{ "username": "example_user", "password": "choose-a-long-password" }
```

Usernames are trimmed, case-preserving, match `[a-zA-Z0-9_.-]{3,32}`, and are unique case-sensitively. Passwords must be nonempty strings. Registration creates a user regardless of any requested role and requires the configured ID service.

| Endpoint              | Success                              | Failure                                                                                             |
| --------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------- |
| `POST /auth/register` | 201, public user and accessToken     | 400 input, 409 duplicate name, 500 internal/dependency failure                                      |
| `POST /auth/login`    | 200, public user and new accessToken | 400 input, 401 credentials, 403 banned after password verification, 500 internal/dependency failure |

```json
{
    "user": { "id": "user_id", "username": "example_user", "role": "user", "banned": false },
    "accessToken": "Bearer eyJhbGciOi..."
}
```

Hashes/passwords are never returned. Unknown accounts still perform a bcrypt comparison. There is no refresh/logout endpoint.

## User lookup and lists

`GET /admin/user/search?userId=...` or `?username=...` requires support or higher. At least one identifier is required. userId wins without username fallback. Unknown users return 404. The response contains status, a public summary, and requests (null if counters are absent).

```json
{
    "status": 200,
    "user": { "id": "user_id", "username": "example_user", "role": "user", "banned": false, "createdAt": "2026-01-01T00:00:00.000Z", "updatedAt": "2026-01-01T00:00:00.000Z", "collection": "users" },
    "requests": { "id": "user_id", "auth": 0, "admin": 0, "images": 12, "total": 12, "createdAt": "2026-01-01T00:00:00.000Z", "updatedAt": "2026-01-01T00:00:00.000Z", "collection": "requests" }
}
```

`GET /admin/users` and `GET /admin/users/dashboard` require admin or owner. Both accept limit (integer 1–1000, default 100) and an opaque cursor from the previous response. Both include:

```json
{ "pagination": { "limit": 100, "nextCursor": null } }
```

A non-null nextCursor means another page exists; supply it unchanged. Rows are ordered by creation timestamp and ID. Invalid cursors/sizes return 400. Traversal is not a database snapshot under concurrent writes.

`/admin/users` retains users keyed by username, each value containing `{ "user": <summary>, "requests": <summary-or-null> }`, plus status and pagination. The default is now one bounded page instead of the entire database.

`/admin/users/dashboard` retains flat users rows with public summary fields plus requestsId, auth, admin, images, total, requestsCreatedAt, requestsUpdatedAt, requestsCollection. Missing counters default to zero/null. Summary contains totalUsers, bannedUsers, totalRequests, adminRequests, authRequests, imageRequests across all accounts, including those outside the page. The current authorized admin request can be counted. Page/totals use separate queries.

## User mutations

All require admin or owner, accept JSON, and identify targets with userId or username using search's precedence.

| Endpoint                         | Additional input                             | Success                           |
| -------------------------------- | -------------------------------------------- | --------------------------------- |
| `POST /admin/ban`                | None                                         | Bans the lower-priority target    |
| `POST /admin/user/edit/role`     | role: user, support, moderator, admin, owner | Changes role subject to priority  |
| `POST /admin/user/edit/username` | newUsername: registration rules              | Renames the lower-priority target |

```json
{ "userId": "user_id", "role": "support" }
```

Success is 200 with status, message, and public user (id, username, role, banned). Invalid input, self-edits, or already-banned targets return 400; insufficient priority returns 403; unknown targets return 404; name conflicts return 409. There is no unban endpoint.

## Storage administration

All `/admin/s3/*` routes require admin or owner. Bucket names are 3–63 lowercase letters, digits, dots, or hyphens, beginning/ending with a letter or digit. Object names are nonempty strings up to 1024 characters.

- `GET /admin/s3/test?bucketExists=lunar-api`: returns `{ "status": 200, "bucketExists": true }` or false. Omit the parameter for a route-only smoke test. Legacy GET JSON bodies remain accepted; query parameters are preferred.
- `POST /admin/s3/upload?bucketName=lunar-api&objectName=fox/example.png`: send raw image/\* bytes, maximum 10 MiB. Multipart/JSON uploads are unsupported. Success includes status, message, bucketName, objectName, etag, optional/null versionId. MIME is trusted; images are not decoded. Invalid input returns 400; oversized bodies return 413.
- `DELETE /admin/s3/delete`: send `{ "bucketName": "lunar-api", "objectName": "fox/example.png" }`, or an etag instead of objectName. objectName wins. Etag lookup deletes the first match; an absent match now returns 404. Success includes status, message, bucketName, object. Object-name deletion follows storage's idempotent semantics.

Successful writes invalidate this process's catalogs for the bucket. Other replicas/external changes become visible after expiry.

## Images

Folders: fox, bird, shibe, weiner-dog, slap, hug, kiss, smug, pat.

`GET /images/{folder}/random` requires any authenticated, non-banned user and returns object metadata plus a public URL:

```json
{ "name": "fox/example.png", "etag": "example-etag", "size": 123456, "lastModified": "2026-01-01T00:00:00.000Z", "url": "https://api.feefer.net/i/fox/example.png" }
```

Catalogs refresh after IMAGE_CATALOG_TTL_MS (default 60 seconds). Concurrent misses share a listing; direct objects with compatible filenames are eligible. Empty categories return 503. Externally deleted objects can briefly remain in cached metadata.

IMAGE_CDN_BASE_URL directs returned URLs to a public CDN/storage prefix; otherwise URLs use PUBLIC_BASE_URL/i/{folder}/{filename}. The API proxy remains available.

`GET /i/{folder}/{filename}` returns bytes without authentication or user counters. Filenames allow letters, digits, dots, underscores, hyphens; `..` and nested paths are rejected. Invalid parameters return 400. The proxy fetches from IMAGE_SOURCE_BASE_URL, disables redirects, uses timeouts, enforces 25 MiB while streaming, and sets Cache-Control: public, max-age=3600. Upstream image content types are forwarded; other types become application/octet-stream. Missing objects return 404; other source failures return 502. Failures after streaming begins terminate the connection.

## Errors and counting

JSON errors share one envelope:

```json
{
    "status": 400,
    "code": "VALIDATION_ERROR",
    "message": "Username is required",
    "error": "Username is required",
    "details": [{ "path": "username", "message": "Username is required" }]
}
```

error aliases message. details is optional validation information. Branch on code/status; messages can evolve. Common codes include AUTH_REQUIRED, INVALID_TOKEN, INVALID_CREDENTIALS, USER_BANNED, INSUFFICIENT_ROLE, USER_NOT_FOUND, USERNAME_TAKEN, INVALID_CURSOR, INVALID_JSON, PAYLOAD_TOO_LARGE, RATE_LIMITED, NOT_READY, IMAGE_NOT_FOUND, IMAGE_SOURCE_UNAVAILABLE, INTERNAL_ERROR. Internal messages/stacks are logged, not returned. Database failures during authentication produce server errors rather than invalid-token 401 responses.

Protected routes count authorized attempts before validation/work. Authentication/role rejections do not count. Auth routes and public image delivery do not increment per-user counters.

## Rate limits

| Scope                            | Quota   | Window     |
| -------------------------------- | ------- | ---------- |
| Global except probes             | 1000/IP | 2 minutes  |
| Auth group                       | 50/IP   | 15 minutes |
| Registration                     | 3/IP    | 1 hour     |
| Login/IP                         | 8       | 15 minutes |
| Login/trimmed lowercase username | 5       | 15 minutes |

Limits stack. Successful responses are excluded exactly once from login-specific quotas; global/auth-group quotas and slowdown still apply. X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset describe the last applied limiter; 429 adds Retry-After.

Global slowdown adds 50 ms after 1000 requests/minute, capped at 3 seconds. Auth-group slowdown adds 500 ms after 10 requests/15 minutes, capped at 5 seconds. Login adds 3 seconds after the first request/15 minutes, capped at 30 seconds. Registration adds 5 seconds after the first request/hour, capped at 60 seconds. State is process-local and resets on restart. Replicas need shared storage for a common quota.
