API documentation: OpenAPI 3.1 generated from the code, page in the UI
ci / go (push) Successful in 3m35s
ci / package (push) Successful in 2m29s
ci / install-test (debian:13) (push) Successful in 1m11s
ci / install-test (debian:12) (push) Successful in 1m22s
ci / e2e (push) Failing after 12m13s

F-API-3 (owner: follow OpenAPI 3.1).

- GET /api/v1/openapi.json (admins) and `sharestead -openapi` produce an
  OpenAPI 3.1.0 document: JSON Schema 2020-12 generated by reflection from
  the request and response types the handlers use (requests and the
  former map responses are named types now), enums for fixed values,
  nullable as type [x, "null"], session cookie + CSRF header as security
  schemes, RFC 9457 problem details for every error status, operation per
  route with area, summary, description and required scope.
- Tests: every registered route must have documentation (and vice versa),
  $refs resolve, operation IDs are unique.
- CI: the document is linted with Redocly CLI (pinned dev dependency),
  rule set recommended-strict; one documented exception (auth/status
  always answers 200).
- UI: "API" page — how to authenticate with a curl example, download of
  openapi.json, search, operations grouped by area with parameters,
  request/response field tables and example bodies, "Try it" for GET.

Verified on CT 151: 39 paths / 47 operations, 74 schemas, 401 without a
session; lint passes locally.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nico.stoerzbachandClaude Opus 5.5 committed 2026-11-29 08:36:51 +01:00
1 parent 8c7c6244a3
commit 6bd7bca30e
26 files changed
+973 -27

No files matched your search

+5
View File
@@ -35,6 +35,11 @@ jobs:
run: go vet ./...
- name: tests (race detector)
run: go test -race -cover ./...
- name: API description (OpenAPI 3.1) — generate and lint
run: |
mkdir -p dist
go run ./cmd/sharestead -openapi > dist/openapi.json
cd web && npm run lint:api
- name: fuzz (short)
run: make fuzz-short
- name: known vulnerabilities
+6
View File
@@ -0,0 +1,6 @@
# Deliberate exceptions to the OpenAPI lint rules.
dist/openapi.json:
operation-4xx-response:
# GET /api/v1/auth/status always answers 200 (logged in or not), so a
# login page can ask without an error.
- '#/paths/~1api~1v1~1auth~1status/get/responses'
+14
View File
@@ -3,6 +3,8 @@ package main
import (
"context"
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"log/slog"
@@ -41,8 +43,20 @@ func main() {
adminGroup := flag.String("admin-group", "sharestead-admins", "members of this group may use the admin UI")
dataDir := flag.String("data-dir", "/var/lib/sharestead", "directory for app data (TLS certificate, database)")
showVersion := flag.Bool("version", false, "print the version and exit")
printAPI := flag.Bool("openapi", false, "print the API description (OpenAPI 3.1, JSON) and exit")
flag.Parse()
if *printAPI {
doc := server.New(":0", tls.Certificate{}, server.Deps{}, slog.New(slog.DiscardHandler)).OpenAPI()
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(doc); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
if *showVersion {
fmt.Println("sharestead", version.String())
return
+1 -1
View File
@@ -263,7 +263,7 @@ One share model, several ways to reach it. Each protocol is a module and can be
|---|---|---|---|
| F-API-1 | Everything the UI does is available through a versioned REST API (`/api/v1`); the UI uses only this API | M | MVP |
| F-API-2 | **Every endpoint requires authentication**, deny by default, scope-based permissions | M | MVP |
| F-API-3 | **API documentation in the web UI** (OpenAPI, examples, "try it"), bundled offline | M | MVP |
| F-API-3 | **API documentation in the web UI** (OpenAPI, examples, "try it"), bundled offline. **OpenAPI 3.1** generated from the handlers' request/response types (JSON Schema 2020-12), RFC 9457 errors, security schemes; every route must be documented (test) and the document passes `redocly lint` (recommended-strict) in CI; `sharestead -openapi` prints it. *Owner: follow OpenAPI 3.1, 2026-11-29* | M | MVP |
| F-API-4 | **API keys:** admins create keys with name, scopes, expiry, optional IP allowlist; shown once, stored hashed; list with last use; revoke/rotate | M | v1 (permission model prepared in MVP) |
| F-API-5 | API calls with keys are audit-logged with the key name; per-key rate limits | M | v1 |
+5 -5
View File
@@ -81,7 +81,7 @@ func (a *api) listAccounts(w http.ResponseWriter, r *http.Request) {
accountProblem(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"users": users, "groups": groups, "admin_group": a.accounts.AdminGroup})
writeJSON(w, http.StatusOK, accountsList{Users: users, Groups: groups, AdminGroup: a.accounts.AdminGroup})
}
// createUserRequest is the body of createUser.
@@ -103,7 +103,7 @@ func (a *api) createUser(w http.ResponseWriter, r *http.Request) {
accountProblem(w, err)
return
}
out := map[string]any{"home": false}
var out userCreated
withHome := in.Home != nil && *in.Home
if in.Home == nil {
withHome = true
@@ -120,15 +120,15 @@ func (a *api) createUser(w http.ResponseWriter, r *http.Request) {
a.record(r, "Personal folder created for "+in.Name, nil)
if in.HomeLimit != nil && a.quotas != nil {
if err := a.quotas.SetHomeLimit(r.Context(), sessionFrom(r).User, in.Name, in.HomeLimit); err != nil {
out["home_error"] = "the limit couldn’t be set: " + err.Error() + " — set it on the user's page."
out.HomeError = "the limit couldn’t be set: " + err.Error() + " — set it on the user's page."
}
} else {
a.assignHomeDefault(r, in.Name)
}
}
out["home"] = created
out.Home = created
if herr != nil {
out["home_error"] = herr.Error() + " — the user was created; create the folder on the user's page."
out.HomeError = herr.Error() + " — the user was created; create the folder on the user's page."
}
}
writeJSON(w, http.StatusCreated, out)
+3 -3
View File
@@ -278,15 +278,15 @@ func (a *api) listShares(w http.ResponseWriter, _ *http.Request) {
if a.editor != nil && a.editor.AllowedRoots != nil {
roots = a.editor.AllowedRoots
}
writeJSON(w, http.StatusOK, map[string]any{"shares": items, "allowed_roots": roots})
writeJSON(w, http.StatusOK, sharesList{Shares: items, AllowedRoots: roots})
}
// status tells the UI whether this browser is logged in. It answers 200 in
// both cases, so loading the login page produces no 401 in the browser console.
func (a *api) status(w http.ResponseWriter, r *http.Request) {
if s := a.session(r); s != nil {
writeJSON(w, http.StatusOK, map[string]any{"logged_in": true, "session": sessionInfo{User: s.User, Admin: s.Admin, CSRF: s.CSRF}})
writeJSON(w, http.StatusOK, authStatus{LoggedIn: true, Session: &sessionInfo{User: s.User, Admin: s.Admin, CSRF: s.CSRF}})
return
}
writeJSON(w, http.StatusOK, map[string]any{"logged_in": false})
writeJSON(w, http.StatusOK, authStatus{})
}
+2 -2
View File
@@ -34,7 +34,7 @@ func folderProblem(w http.ResponseWriter, err error) {
func (a *api) listFolder(w http.ResponseWriter, r *http.Request) {
p := r.URL.Query().Get("path")
if p == "" {
writeJSON(w, http.StatusOK, map[string]any{"roots": a.folders.RootList()})
writeJSON(w, http.StatusOK, folderRoots{Roots: a.folders.RootList()})
return
}
l, err := a.folders.List(p)
@@ -74,7 +74,7 @@ func (a *api) createFolder(w http.ResponseWriter, r *http.Request) {
folderProblem(w, err)
return
}
writeJSON(w, http.StatusCreated, map[string]string{"path": p})
writeJSON(w, http.StatusCreated, folderCreated{Path: p})
}
// deleteFolderRequest is the body of deleteFolder.
+1 -1
View File
@@ -13,7 +13,7 @@ func (a *api) registerHealth() {
}
func (a *api) listProblems(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"problems": a.health.Check(r.Context())})
writeJSON(w, http.StatusOK, problemsList{Problems: a.health.Check(r.Context())})
}
// fixProblem runs a safe one-click fix offered by a problem.
+3 -4
View File
@@ -29,7 +29,7 @@ func (a *api) getHomes(w http.ResponseWriter, r *http.Request) {
editProblem(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"homes": st, "default_limit": settings.HomeDefault})
writeJSON(w, http.StatusOK, homesInfo{Homes: st, DefaultLimit: settings.HomeDefault})
}
// setHomesRequest is the body of setHomes.
@@ -59,8 +59,7 @@ func (a *api) setHomes(w http.ResponseWriter, r *http.Request) {
editProblem(w, err)
return
}
resp := toResponse(res)
writeJSON(w, http.StatusOK, map[string]any{"files": resp.Files, "versions": resp.Versions, "entry": resp.Entry, "created": created})
writeJSON(w, http.StatusOK, homesChanged{editResponse: toResponse(res), Created: created})
}
func (a *api) createHome(w http.ResponseWriter, r *http.Request) {
@@ -77,7 +76,7 @@ func (a *api) createHome(w http.ResponseWriter, r *http.Request) {
case err != nil:
accountProblem(w, err)
default:
writeJSON(w, http.StatusOK, map[string]any{"created": created})
writeJSON(w, http.StatusOK, homeCreated{Created: created})
}
}
+3 -6
View File
@@ -43,16 +43,13 @@ func (a *api) getMe(w http.ResponseWriter, r *http.Request) {
problem(w, http.StatusInternalServerError, "config_unreadable", "Your shares couldn’t be read", err.Error(), nil)
return
}
out := map[string]any{
"user": me.Name, "full_name": me.FullName, "uid": me.UID, "groups": me.Groups, "admin": me.Admin, "samba": me.Samba,
"shares": shares,
}
out := myAccount{User: me.Name, FullName: me.FullName, UID: me.UID, Groups: me.Groups, Admin: me.Admin, Samba: me.Samba, Shares: shares}
if a.quotas != nil {
if rep, err := a.quotas.Report(r.Context()); err == nil {
out["scanned_at"], out["warn_percent"] = rep.ScannedAt, rep.WarnPercent
out.ScannedAt, out.WarnPercent = rep.ScannedAt, rep.WarnPercent
for _, u := range rep.Users {
if u.Name == me.Name {
out["storage"] = u
out.Storage = &u
}
}
}
+296
View File
@@ -0,0 +1,296 @@
package server
import (
"net/http"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sharestead/internal/app/accounts"
"sharestead/internal/app/folders"
apphealth "sharestead/internal/app/health"
"sharestead/internal/app/quotas"
"sharestead/internal/app/updates"
"sharestead/internal/domain/quota"
"sharestead/internal/domain/share"
"sharestead/internal/format/diff"
"sharestead/internal/version"
)
// opDoc documents one route. Every registered route needs one (test).
type opDoc struct {
Tag, Summary, Description string
Request any // body type; nil: no body
Response any // success body type; nil: 204 No Content
OneOf []any // success body is one of these (instead of Response)
Status int // success status; default 200 (204 without a body)
Query []queryParam
Confirm bool // may answer 403 confirm_password (password needed again)
Edit bool // config change: ?dry_run=1 previews, 409 on conflicts
}
type queryParam struct{ Name, Description string }
var dryRunParam = queryParam{"dry_run", "1: only preview the change (diff of the config files); nothing is written"}
// apiDocs describes every route: summary, request and response types.
var apiDocs = map[string]opDoc{
"POST /api/v1/auth/login": {Tag: "Auth", Summary: "Log in", Description: "Checks user name and password (PAM). Admins get the admin UI; other users their own page if self-service is on. Sets the session cookie. Repeated failures are delayed (429).", Request: loginRequest{}, Response: sessionInfo{}},
"POST /api/v1/auth/logout": {Tag: "Auth", Summary: "Log out"},
"GET /api/v1/auth/session": {Tag: "Auth", Summary: "Current session", Response: sessionInfo{}},
"GET /api/v1/auth/status": {Tag: "Auth", Summary: "Whether this browser is logged in", Description: "Always 200, so a login page can ask without an error.", Response: authStatus{}},
"POST /api/v1/auth/confirm": {Tag: "Auth", Summary: "Confirm the password again", Description: "Needed before dangerous actions when the password wasn't entered in the last minutes (they answer 403 confirm_password).", Request: confirmRequest{}},
"GET /api/v1/me": {Tag: "Self-service", Summary: "My account", Description: "The logged-in user's shares (with the level and why), storage and limits. Nothing about other users.", Response: myAccount{}},
"PUT /api/v1/me/password": {Tag: "Self-service", Summary: "Change my password", Description: "Needs the current password. Sets it for Samba and Linux at once.", Request: setMyPasswordRequest{}},
"GET /api/v1/shares": {Tag: "Shares", Summary: "List shares", Description: "All shares from smb.conf and the NFS export tables, with access, disk usage and problems.", Response: sharesList{}},
"POST /api/v1/shares": {Tag: "Shares", Summary: "Create a share", Description: "Optionally creates the folder with its own group. Writes smb.conf and/or an export table.", Request: createShareRequest{}, Response: editResponse{}, Edit: true},
"PUT /api/v1/shares/{name}/access": {Tag: "Shares", Summary: "Change who may do what", Request: setShareAccessRequest{}, Response: editResponse{}, Edit: true},
"PUT /api/v1/shares/{name}/nfs": {Tag: "Shares", Summary: "Change NFS access", Description: "An empty client list stops NFS for this share.", Request: setShareNFSRequest{}, Response: editResponse{}, Edit: true},
"PUT /api/v1/shares/{name}/options": {Tag: "Shares", Summary: "Change share options", Request: setShareOptionsRequest{}, Response: editResponse{}, Edit: true},
"DELETE /api/v1/shares/{name}": {Tag: "Shares", Summary: "Remove a share", Description: "Stops sharing; the folder and files stay.", Request: deleteShareRequest{}, Response: editResponse{}, Edit: true},
"GET /api/v1/settings/samba": {Tag: "Settings", Summary: "Server-wide Samba settings", Response: share.GlobalValues{}},
"PUT /api/v1/settings/samba": {Tag: "Settings", Summary: "Change server-wide Samba settings", Request: setSambaSettingsRequest{}, Response: editResponse{}, Edit: true},
"GET /api/v1/settings/app": {Tag: "Settings", Summary: "Sharestead's own settings", Response: appSettings{}},
"PUT /api/v1/settings/app": {Tag: "Settings", Summary: "Change Sharestead's own settings", Description: "Switching self-service off ends all user sessions.", Request: setAppSettingsRequest{}, Response: appSettingsChanged{}},
"GET /api/v1/changes": {Tag: "Changes", Summary: "Change history", Description: "Every change made here or by hand in a managed file, newest first, with the lines changed.", Response: changesList{}},
"POST /api/v1/changes/{id}/undo": {Tag: "Changes", Summary: "Undo a change", Description: "Writes the old lines back (a new entry); refused if later changes touched them.", Response: editResponse{}, Edit: true},
"GET /api/v1/users": {Tag: "Users & groups", Summary: "List users and groups", Description: "People (UID range from login.defs) and their groups; system accounts are hidden.", Response: accountsList{}},
"POST /api/v1/users": {Tag: "Users & groups", Summary: "Create a user", Description: "Linux account without login shell plus Samba account, one password for both. Creates the personal folder when personal folders are on.", Request: createUserRequest{}, Response: userCreated{}, Status: http.StatusCreated},
"PATCH /api/v1/users/{name}": {Tag: "Users & groups", Summary: "Change a user", Description: "Display name, groups, enabled/disabled. Granting or removing admin rights needs a recent password.", Request: accounts.UserChanges{}, Confirm: true},
"PUT /api/v1/users/{name}/password": {Tag: "Users & groups", Summary: "Set a user's password", Request: setPasswordRequest{}},
"DELETE /api/v1/users/{name}": {Tag: "Users & groups", Summary: "Delete a user", Description: "Files stay.", Confirm: true},
"POST /api/v1/groups": {Tag: "Users & groups", Summary: "Create a group", Request: createGroupRequest{}},
"PUT /api/v1/groups/{name}/members": {Tag: "Users & groups", Summary: "Set a group's members", Description: "For the admin group this needs a recent password.", Request: setMembersRequest{}, Confirm: true},
"DELETE /api/v1/groups/{name}": {Tag: "Users & groups", Summary: "Delete a group"},
"GET /api/v1/storage": {Tag: "Storage", Summary: "Storage usage and limits", Description: "Last measurement per user and share, with limits and states.", Response: quotas.Report{}},
"POST /api/v1/storage/scan": {Tag: "Storage", Summary: "Measure now", Description: "Starts a measurement in the background.", Status: http.StatusAccepted},
"PUT /api/v1/users/{name}/limit": {Tag: "Storage", Summary: "Set a user's limit across all shares", Description: "0 removes it. Soft limit: over it, shares become read-only for the user over SMB.", Request: setLimitRequest{}},
"GET /api/v1/homes": {Tag: "Personal folders", Summary: "Personal folder settings", Response: homesInfo{}},
"PUT /api/v1/homes": {Tag: "Personal folders", Summary: "Switch personal folders on or off", Description: "On: <folder>/<user>, private to the user; optionally creates folders for all users. Off keeps the folders.", Request: setHomesRequest{}, Response: homesChanged{}, Edit: true},
"PUT /api/v1/homes/limit": {Tag: "Personal folders", Summary: "Limit for new personal folders", Description: "New folders get it as their own limit; existing users keep theirs.", Request: setHomeDefaultRequest{}},
"POST /api/v1/users/{name}/home": {Tag: "Personal folders", Summary: "Create a user's personal folder", Response: homeCreated{}},
"PUT /api/v1/users/{name}/home-limit": {Tag: "Personal folders", Summary: "Set a user's personal folder limit", Description: "null copies the current default; 0 means no limit.", Request: setHomeLimitRequest{}},
"GET /api/v1/folders": {Tag: "Folders", Summary: "Browse folders", Description: "Without path: the storage folders Sharestead may use. With path: its content.", OneOf: []any{folderRoots{}, folders.Listing{}}, Query: []queryParam{{"path", "absolute folder inside the storage folders"}}},
"GET /api/v1/folders/stats": {Tag: "Folders", Summary: "Size and file count of a folder", Response: folders.Stats{}, Query: []queryParam{{"path", "absolute folder inside the storage folders"}}},
"POST /api/v1/folders": {Tag: "Folders", Summary: "Create a folder", Request: createFolderRequest{}, Response: folderCreated{}, Status: http.StatusCreated},
"DELETE /api/v1/folders": {Tag: "Folders", Summary: "Delete a folder and its files", Description: "Needs the folder name typed as confirmation and a recent password. Refused for share folders.", Request: deleteFolderRequest{}, Confirm: true},
"GET /api/v1/services": {Tag: "Services", Summary: "Services and their state", Response: servicesList{}},
"PUT /api/v1/services/{id}": {Tag: "Services", Summary: "Switch a service on or off", Description: "Needs a recent password.", Request: setServiceRequest{}, Confirm: true},
"POST /api/v1/services/{id}/restart": {Tag: "Services", Summary: "Restart a service"},
"GET /api/v1/clients": {Tag: "Services", Summary: "Connected devices", Description: "SMB sessions and NFSv4 clients.", Response: clientsList{}},
"GET /api/v1/problems": {Tag: "Problems", Summary: "Current problems", Description: "Each says what is wrong, what is affected, the cause and what to do.", Response: problemsList{}},
"POST /api/v1/problems/fix": {Tag: "Problems", Summary: "Apply a one-click fix", Request: fixProblemRequest{}},
"GET /api/v1/updates": {Tag: "Updates", Summary: "Pending system updates", Description: "From a simulated upgrade; nothing is installed.", Response: updates.Status{}, Query: []queryParam{{"fresh", "1: check again now instead of the cached result"}}},
"GET /api/v1/openapi.json": {Tag: "API", Summary: "This API description (OpenAPI 3.1)", Response: map[string]any{}},
}
// apiTags describe the areas of the API.
var apiTags = map[string]string{
"Auth": "Log in and out; password confirmation before dangerous actions.",
"Self-service": "A user's own account: shares, storage, password.",
"Shares": "SMB shares and NFS exports: create, access, options, remove.",
"Settings": "Server-wide Samba settings and Sharestead's own settings.",
"Changes": "History of every config change, with undo.",
"Users & groups": "People who log in to the shares, and their groups.",
"Storage": "Usage per user and share, limits across all shares.",
"Personal folders": "One private folder per user, with size limits.",
"Folders": "Browse, create and delete folders in the storage folders.",
"Services": "File sharing and discovery services, connected devices.",
"Problems": "Health checks: what is wrong and what to do.",
"Updates": "Pending system updates.",
"API": "This description.",
}
// Enums for named string types; descriptions for types and fields that
// need one.
var (
apiEnums = map[reflect.Type][]string{
reflect.TypeOf(share.Level("")): {"none", "read", "write"},
reflect.TypeOf(share.PrincipalKind("")): {"user", "group", "guests", "everyone"},
reflect.TypeOf(quota.State("")): {"none", "ok", "warning", "over"},
reflect.TypeOf(apphealth.Severity("")): {"critical", "warning"},
}
apiTypeDocs = map[reflect.Type]string{
reflect.TypeOf(diff.Op{}): "One line of a diff. kind: 32 unchanged, 45 removed, 43 added, 126 lines left out.",
reflect.TypeOf(problemBody{}): "RFC 9457 problem details. code is stable for programs; title and detail are for people and say what to do.",
}
)
// problemBody documents the body problem() writes (RFC 9457).
type problemBody struct {
Type string `json:"type"`
Status int `json:"status"`
Code string `json:"code"`
Title string `json:"title"`
Detail string `json:"detail"`
RetryAfterSeconds int `json:"retry_after_seconds,omitempty"` // with 429
}
var pathParam = regexp.MustCompile(`\{(\w+)\}`)
// OpenAPI returns the API description as an OpenAPI 3.1 document.
func (s *Server) OpenAPI() map[string]any { return openAPI(s.routes) }
func openAPI(routes []Route) map[string]any {
sc := newSchemas(apiEnums, apiTypeDocs)
problemRef := sc.of(problemBody{})
paths := map[string]map[string]any{}
tags := map[string]bool{}
for _, rt := range routes {
d := apiDocs[rt.Method+" "+rt.Pattern]
tags[d.Tag] = true
op := map[string]any{
"operationId": operationID(rt.Method, rt.Pattern),
"summary": d.Summary,
"tags": []string{d.Tag},
"x-sharestead-scope": string(rt.Scope),
}
desc := d.Description
switch rt.Scope {
case ScopeAdmin:
desc = strings.TrimSpace(desc + " Requires an admin session.")
case ScopeSession:
desc = strings.TrimSpace(desc + " Requires a session (any user).")
}
op["description"] = desc
unsafe := rt.Method != http.MethodGet
switch {
case rt.Scope == ScopePublic:
op["security"] = []any{}
case unsafe:
op["security"] = []any{map[string]any{"session": []any{}, "csrf": []any{}}}
default:
op["security"] = []any{map[string]any{"session": []any{}}}
}
var params []any
for _, m := range pathParam.FindAllStringSubmatch(rt.Pattern, -1) {
params = append(params, map[string]any{"name": m[1], "in": "path", "required": true, "schema": map[string]any{"type": "string"}})
}
query := d.Query
if d.Edit {
query = append(query, dryRunParam)
}
for _, q := range query {
params = append(params, map[string]any{"name": q.Name, "in": "query", "required": false, "description": q.Description, "schema": map[string]any{"type": "string"}})
}
if len(params) > 0 {
op["parameters"] = params
}
if d.Request != nil {
op["requestBody"] = map[string]any{"required": true, "content": map[string]any{"application/json": map[string]any{"schema": sc.of(d.Request)}}}
}
responses := map[string]any{}
status := d.Status
switch {
case d.Response != nil || d.OneOf != nil:
if status == 0 {
status = http.StatusOK
}
var schema map[string]any
if d.OneOf != nil {
var alts []any
for _, v := range d.OneOf {
alts = append(alts, sc.of(v))
}
schema = map[string]any{"oneOf": alts}
} else {
schema = sc.of(d.Response)
if _, isMap := d.Response.(map[string]any); isMap {
schema = map[string]any{"type": "object"}
}
}
responses[itoa(status)] = map[string]any{"description": "Success", "content": map[string]any{"application/json": map[string]any{"schema": schema}}}
default:
if status == 0 {
status = http.StatusNoContent
}
responses[itoa(status)] = map[string]any{"description": "Success"}
}
problem := func(code int, text string) {
responses[itoa(code)] = map[string]any{"description": text, "content": map[string]any{"application/problem+json": map[string]any{"schema": problemRef}}}
}
if d.Request != nil || len(query) > 0 {
problem(400, "Invalid input")
}
if rt.Scope != ScopePublic {
problem(401, "Not logged in")
forbidden := "Not allowed: not an admin, missing CSRF token or request from another site"
if rt.Scope == ScopeSession {
forbidden = "Missing CSRF token, request from another site, or self-service switched off"
}
if d.Confirm {
forbidden += ", or the password is needed again (code confirm_password)"
}
problem(403, forbidden)
} else if unsafe {
problem(403, "Request from another site, account not allowed, or self-service switched off")
}
if strings.Contains(rt.Pattern, "{") {
problem(404, "Not found")
}
if d.Edit {
problem(409, "The configuration changed in the meantime, or the change conflicts with later ones")
}
if rt.Pattern == "/api/v1/auth/login" || rt.Pattern == "/api/v1/auth/confirm" || rt.Pattern == "/api/v1/me/password" {
problem(429, "Too many wrong passwords; wait (Retry-After)")
problem(401, "Wrong user name or password")
}
problem(500, "The system couldn't do it; the detail says why and what wasn't changed")
op["responses"] = responses
p := paths[rt.Pattern]
if p == nil {
p = map[string]any{}
paths[rt.Pattern] = p
}
p[strings.ToLower(rt.Method)] = op
}
var tagList []any
names := make([]string, 0, len(tags))
for t := range tags {
names = append(names, t)
}
sort.Strings(names)
for _, t := range names {
tagList = append(tagList, map[string]any{"name": t, "description": apiTags[t]})
}
return map[string]any{
"openapi": "3.1.0",
"info": map[string]any{
"title": "Sharestead API",
"version": version.String(),
"description": "Everything the web UI does goes through this API. Log in with POST /api/v1/auth/login; send the session cookie and, for changes, the CSRF token from the login answer in X-CSRF-Token, plus a same-site Origin header. Errors are RFC 9457 problem details.",
"license": map[string]any{"name": "GPL-3.0-only", "identifier": "GPL-3.0-only"},
},
"servers": []any{map[string]any{"url": "/"}},
"tags": tagList,
"paths": paths,
"components": map[string]any{
"schemas": sc.defs,
"securitySchemes": map[string]any{
"session": map[string]any{"type": "apiKey", "in": "cookie", "name": sessionCookie, "description": "Session cookie from POST /api/v1/auth/login."},
"csrf": map[string]any{"type": "apiKey", "in": "header", "name": "X-CSRF-Token", "description": "CSRF token from the login answer; required for every change."},
},
},
}
}
func operationID(method, pattern string) string {
parts := []string{strings.ToLower(method)}
for _, seg := range strings.Split(strings.TrimPrefix(pattern, "/api/v1/"), "/") {
seg = strings.Trim(seg, "{}")
for _, w := range strings.FieldsFunc(seg, func(r rune) bool { return r == '-' || r == '_' }) {
parts = append(parts, exported(w))
}
}
return strings.Join(parts, "")
}
func itoa(i int) string { return strconv.Itoa(i) }
func (a *api) registerOpenAPI() {
a.handle("GET", "/api/v1/openapi.json", ScopeAdmin, func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, openAPI(a.routes))
})
}
+71
View File
@@ -0,0 +1,71 @@
package server
import (
"encoding/json"
"os"
"strings"
"testing"
)
func TestEveryRouteIsDocumented(t *testing.T) {
routes := newTestServer().Routes()
seen := map[string]bool{}
for _, rt := range routes {
key := rt.Method + " " + rt.Pattern
seen[key] = true
d, ok := apiDocs[key]
if !ok {
t.Errorf("%s has no entry in apiDocs (openapi.go)", key)
continue
}
if d.Tag == "" || d.Summary == "" {
t.Errorf("%s: tag and summary are required", key)
}
if apiTags[d.Tag] == "" {
t.Errorf("%s: tag %q has no description in apiTags", key, d.Tag)
}
}
for key := range apiDocs {
if !seen[key] {
t.Errorf("apiDocs has %s, but no such route is registered", key)
}
}
}
func TestOpenAPIDocument(t *testing.T) {
doc := newTestServer().OpenAPI()
b, err := json.MarshalIndent(doc, "", " ")
if err != nil {
t.Fatal(err)
}
if out := os.Getenv("OPENAPI_OUT"); out != "" {
if err := os.WriteFile(out, b, 0o644); err != nil {
t.Fatal(err)
}
}
s := string(b)
for _, want := range []string{`"openapi": "3.1.0"`, `"/api/v1/users/{name}"`, `"application/problem+json"`, `"enum": [`, `"$ref": "#/components/schemas/Item"`} {
if !strings.Contains(s, want) {
t.Errorf("document lacks %s", want)
}
}
// Every $ref points to a defined schema.
comps := doc["components"].(map[string]any)["schemas"].(map[string]map[string]any)
for _, part := range strings.Split(s, `"$ref": "#/components/schemas/`)[1:] {
name := part[:strings.Index(part, `"`)]
if _, ok := comps[name]; !ok {
t.Errorf("$ref to undefined schema %s", name)
}
}
// Operation IDs are unique.
ids := map[string]bool{}
for _, item := range doc["paths"].(map[string]map[string]any) {
for _, op := range item {
id := op.(map[string]any)["operationId"].(string)
if ids[id] {
t.Errorf("duplicate operationId %s", id)
}
ids[id] = true
}
}
}
+104
View File
@@ -0,0 +1,104 @@
package server
import (
"time"
"sharestead/internal/app/folders"
apphealth "sharestead/internal/app/health"
"sharestead/internal/app/homes"
"sharestead/internal/app/quotas"
svcs "sharestead/internal/app/services"
"sharestead/internal/app/shares"
"sharestead/internal/domain/account"
"sharestead/internal/domain/share"
)
// Response bodies of the API. Named types, so the OpenAPI description is
// generated from the same types the handlers write.
// sharesList is the answer to listShares.
type sharesList struct {
Shares []shares.Item `json:"shares"`
AllowedRoots []string `json:"allowed_roots"` // folders new shares may be in
}
// authStatus tells whether this browser is logged in.
type authStatus struct {
LoggedIn bool `json:"logged_in"`
Session *sessionInfo `json:"session,omitempty"`
}
// problemsList is the answer to listProblems.
type problemsList struct {
Problems []apphealth.Problem `json:"problems"`
}
// servicesList is the answer to listServices.
type servicesList struct {
Services []svcs.Status `json:"services"`
}
// clientsList is the answer to listClients.
type clientsList struct {
Clients []svcs.Client `json:"clients"`
}
// changesList is the answer to listChanges (newest first).
type changesList struct {
Changes []change `json:"changes"`
}
// folderRoots lists the storage folders Sharestead may use.
type folderRoots struct {
Roots []folders.Entry `json:"roots"`
}
// folderCreated is the answer to createFolder.
type folderCreated struct {
Path string `json:"path"`
}
// homesInfo is the answer to getHomes.
type homesInfo struct {
Homes homes.Status `json:"homes"`
DefaultLimit int64 `json:"default_limit"` // bytes a new personal folder gets; 0: none
}
// homesChanged is the answer to setHomes: preview or applied change, and
// the users whose folder was created.
type homesChanged struct {
editResponse
Created []string `json:"created,omitempty"`
}
// homeCreated is the answer to createHome.
type homeCreated struct {
Created bool `json:"created"` // false: the folder existed already
}
// accountsList is the answer to listAccounts.
type accountsList struct {
Users []account.User `json:"users"`
Groups []account.Group `json:"groups"`
AdminGroup string `json:"admin_group"`
}
// userCreated is the answer to createUser.
type userCreated struct {
Home bool `json:"home"` // a personal folder was created
HomeError string `json:"home_error,omitempty"` // the user exists, but the folder or its limit failed
}
// myAccount is the answer to getMe (self-service).
type myAccount struct {
User string `json:"user"`
FullName string `json:"full_name"`
UID int `json:"uid"`
Groups []string `json:"groups"`
Admin bool `json:"admin"`
Samba bool `json:"samba"` // has a share password
Shares []share.MyAccess `json:"shares"`
Storage *quotas.UserUsage `json:"storage,omitempty"`
ScannedAt time.Time `json:"scanned_at,omitzero"`
WarnPercent int `json:"warn_percent,omitempty"`
}
+153
View File
@@ -0,0 +1,153 @@
package server
import (
"reflect"
"strings"
"time"
)
// schemas builds JSON Schema 2020-12 (the dialect of OpenAPI 3.1) from Go
// types: named structs become components with a $ref, json tags give the
// property names, fields without omitempty/omitzero are required, pointers
// may be null, and named string types with known values get an enum.
type schemas struct {
defs map[string]map[string]any
names map[reflect.Type]string
enums map[reflect.Type][]string
docs map[reflect.Type]string
}
func newSchemas(enums map[reflect.Type][]string, docs map[reflect.Type]string) *schemas {
return &schemas{defs: map[string]map[string]any{}, names: map[reflect.Type]string{}, enums: enums, docs: docs}
}
var timeType = reflect.TypeOf(time.Time{})
// of returns the schema of the type of v.
func (s *schemas) of(v any) map[string]any { return s.schema(reflect.TypeOf(v)) }
func (s *schemas) schema(t reflect.Type) map[string]any {
switch {
case t == timeType:
return map[string]any{"type": "string", "format": "date-time"}
case t.Kind() == reflect.Pointer:
inner := s.schema(t.Elem())
if ref, ok := inner["$ref"]; ok {
return map[string]any{"anyOf": []any{map[string]any{"$ref": ref}, map[string]any{"type": "null"}}}
}
if typ, ok := inner["type"].(string); ok {
inner["type"] = []any{typ, "null"}
}
return inner
}
if vals, ok := s.enums[t]; ok {
out := map[string]any{"type": "string", "enum": vals}
if d := s.docs[t]; d != "" {
out["description"] = d
}
return out
}
switch t.Kind() {
case reflect.String:
return map[string]any{"type": "string"}
case reflect.Bool:
return map[string]any{"type": "boolean"}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if t.String() == "time.Duration" {
return map[string]any{"type": "integer", "description": "nanoseconds"}
}
return map[string]any{"type": "integer"}
case reflect.Float32, reflect.Float64:
return map[string]any{"type": "number"}
case reflect.Slice, reflect.Array:
if t.Elem().Kind() == reflect.Uint8 {
return map[string]any{"type": "string", "contentEncoding": "base64"}
}
return map[string]any{"type": "array", "items": s.schema(t.Elem())}
case reflect.Map:
return map[string]any{"type": "object", "additionalProperties": s.schema(t.Elem())}
case reflect.Interface:
return map[string]any{}
case reflect.Struct:
if t.Name() == "" {
return s.object(t)
}
name := s.name(t)
if _, done := s.defs[name]; !done {
s.defs[name] = map[string]any{} // placeholder against recursion
s.defs[name] = s.object(t)
}
return map[string]any{"$ref": "#/components/schemas/" + name}
}
return map[string]any{}
}
// name gives a component name; the package is added when two types share one.
func (s *schemas) name(t reflect.Type) string {
if n, ok := s.names[t]; ok {
return n
}
n := exported(t.Name())
for other, used := range s.names {
if used == n && other != t {
pkg := t.PkgPath()[strings.LastIndex(t.PkgPath(), "/")+1:]
n = exported(pkg) + n
break
}
}
s.names[t] = n
return n
}
func exported(s string) string {
if s == "" {
return s
}
return strings.ToUpper(s[:1]) + s[1:]
}
func (s *schemas) object(t reflect.Type) map[string]any {
props := map[string]any{}
var required []string
s.fields(t, props, &required)
out := map[string]any{"type": "object", "properties": props}
if len(required) > 0 {
out["required"] = required
}
if d := s.docs[t]; d != "" {
out["description"] = d
}
return out
}
func (s *schemas) fields(t reflect.Type, props map[string]any, required *[]string) {
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
tag := f.Tag.Get("json")
if tag == "-" {
continue
}
name, opts, _ := strings.Cut(tag, ",")
if f.Anonymous && name == "" {
ft := f.Type
if ft.Kind() == reflect.Pointer {
ft = ft.Elem()
}
if ft.Kind() == reflect.Struct {
s.fields(ft, props, required) // embedded: fields are promoted
continue
}
}
if !f.IsExported() {
continue
}
if name == "" {
name = f.Name
}
props[name] = s.schema(f.Type)
if !strings.Contains(opts, "omitempty") && !strings.Contains(opts, "omitzero") && f.Type.Kind() != reflect.Pointer {
*required = append(*required, name)
}
}
}
+1
View File
@@ -71,6 +71,7 @@ func New(addr string, cert tls.Certificate, d Deps, log *slog.Logger) *Server {
a.registerHomes()
a.registerMe()
a.registerSettings()
a.registerOpenAPI()
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
problem(w, http.StatusNotFound, "not_found", "No such API endpoint", r.Method+" "+r.URL.Path+" doesn't exist.", nil)
})
+2 -2
View File
@@ -26,7 +26,7 @@ func serviceProblem(w http.ResponseWriter, err error) {
}
func (a *api) listServices(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"services": a.services.List(r.Context())})
writeJSON(w, http.StatusOK, servicesList{Services: a.services.List(r.Context())})
}
// setServiceRequest is the body of setService.
@@ -72,5 +72,5 @@ func (a *api) listClients(w http.ResponseWriter, r *http.Request) {
serviceProblem(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"clients": cs})
writeJSON(w, http.StatusOK, clientsList{Clients: cs})
}
+1 -1
View File
@@ -175,7 +175,7 @@ func (a *api) listChanges(w http.ResponseWriter, r *http.Request) {
}
out = append(out, c)
}
writeJSON(w, http.StatusOK, map[string]any{"changes": out})
writeJSON(w, http.StatusOK, changesList{Changes: out})
}
func (a *api) undoChange(w http.ResponseWriter, r *http.Request) {
+4
View File
@@ -0,0 +1,4 @@
# OpenAPI lint (Redocly CLI): the recommended rules for OpenAPI 3.1, with
# warnings treated as errors. Generated by: sharestead -openapi
extends:
- recommended-strict
+19 -1
View File
@@ -532,7 +532,7 @@ test('accessibility: every page meets WCAG 2.2 AA (axe-core), light and dark', a
found.push(...(await axe(page, 'login')));
await login(page);
await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
const pages = ['', 'problems', 'shares', 'shares/Family', 'new-share', 'folders', 'users', 'users/kim', 'groups', 'services', 'changes', 'system', 'help'];
const pages = ['', 'problems', 'shares', 'shares/Family', 'new-share', 'folders', 'users', 'users/kim', 'groups', 'services', 'changes', 'system', 'help', 'api', 'me'];
for (const theme of ['light', 'dark']) {
if (theme === 'dark') {
if (info.project.name === 'mobile') break;
@@ -564,3 +564,21 @@ test('self-service: admins see “My account”; the global switch is on the Sys
await expect(page.getByRole('switch', { name: 'Users can log in to “My account”' })).toBeChecked();
expect(errors).toEqual([]);
});
test('API page: OpenAPI 3.1 description, grouped, with “Try it” for GET', async ({ page, isMobile }) => {
const errors = watchConsole(page, true);
await login(page);
await openNav(page, 'API', isMobile);
await expect(page.getByRole('heading', { name: 'Using the API' })).toBeVisible();
await expect(page.getByText(/OpenAPI 3\.1/).first()).toBeVisible();
await page.getByLabel('Search endpoints').fill('list shares');
const op = page.locator('details.op').filter({ hasText: 'List shares' });
await op.locator('summary').click();
await expect(op).toContainText('allowed_roots');
await op.getByRole('button', { name: 'Send GET' }).click();
await expect(op.locator('pre.result')).toContainText('"shares"');
const doc = await page.request.get('/api/v1/openapi.json');
expect(doc.ok()).toBe(true);
expect((await doc.json()).openapi).toBe('3.1.0');
expect(errors).toEqual([]);
});
+16
View File
@@ -8,6 +8,7 @@
"devDependencies": {
"@axe-core/playwright": "4.14.1",
"@playwright/test": "1.65.1",
"@redocly/cli": "2.84.0",
"@sveltejs/vite-plugin-svelte": "7.3.2",
"@tsconfig/svelte": "5.0.9",
"svelte": "5.59.2",
@@ -109,6 +110,21 @@
"node": ">=20"
}
},
"node_modules/@redocly/cli": {
"version": "2.84.0",
"resolved": "https://registry.npmjs.org/@redocly/cli/-/cli-2.84.0.tgz",
"integrity": "sha512-0RmjaLv9QrydTLMEKXvQTasLy4uFQRbrAIwjgRhOB1uiI3O3H7AbEmSIyvHh3r7ARx/bm9+uD154jmh+HfBG0Q==",
"dev": true,
"license": "MIT",
"bin": {
"openapi": "bin/cli.js",
"redocly": "bin/cli.js"
},
"engines": {
"node": ">=22.12.0 || >=20.19.0 <21.0.0",
"npm": ">=10"
}
},
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.3.4.tgz",
+3 -1
View File
@@ -7,11 +7,13 @@
"build": "vite build",
"check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
"test": "vitest run",
"e2e": "playwright test"
"e2e": "playwright test",
"lint:api": "cd .. && redocly lint dist/openapi.json --config redocly.yaml --format=stylish"
},
"devDependencies": {
"@axe-core/playwright": "4.14.1",
"@playwright/test": "1.65.1",
"@redocly/cli": "2.84.0",
"@sveltejs/vite-plugin-svelte": "7.3.2",
"@tsconfig/svelte": "5.0.9",
"svelte": "5.59.2",
+4
View File
@@ -8,6 +8,7 @@
import Login from './pages/Login.svelte';
import Help from './pages/Help.svelte';
import MyAccount from './pages/MyAccount.svelte';
import Api from './pages/Api.svelte';
import Logo from './components/Logo.svelte';
import { prefs } from './lib/prefs.svelte';
import Dashboard from './pages/Dashboard.svelte';
@@ -46,6 +47,7 @@
{ page: 'changes', label: 'Changes', icon: '↺' },
{ page: 'system', label: 'System', icon: '⚙' },
{ page: 'help', label: 'Help', icon: '?' },
{ page: 'api', label: 'API', icon: '{}' },
];
const active = $derived(router.route.page);
const title = $derived(nav.find((n) => n.page === active)?.label ?? (active === 'new-share' ? 'New share' : active === 'me' ? 'My account' : ''));
@@ -159,6 +161,8 @@
<Users {accounts} reload={load} />
{:else if active === 'groups'}
<Groups {accounts} reload={load} />
{:else if active === 'api'}
<Api />
{:else if active === 'me'}
<MyAccount />
{:else if active === 'help'}
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, it } from 'vitest';
import { example, fields, typeLabel, type Doc } from './openapi';
const doc: Doc = { components: { schemas: {
User: { type: 'object', properties: { name: { type: 'string' }, uid: { type: 'integer' }, level: { type: 'string', enum: ['none', 'read'] } }, required: ['name'] },
List: { type: 'object', properties: { users: { type: 'array', items: { $ref: '#/components/schemas/User' } }, note: { type: ['string', 'null'] } } },
} } };
describe('openapi helpers', () => {
it('labels types', () => {
expect(typeLabel(doc, { $ref: '#/components/schemas/User' })).toBe('User');
expect(typeLabel(doc, { type: 'array', items: { type: 'string' } })).toBe('array of string');
expect(typeLabel(doc, { type: ['integer', 'null'] })).toBe('integer | null');
});
it('flattens nested fields', () => {
const f = fields(doc, { $ref: '#/components/schemas/List' });
expect(f.map((x) => `${' '.repeat(x.depth)}${x.name}`)).toEqual(['users', ' name', ' uid', ' level', 'note']);
expect(f.find((x) => x.name === 'name')?.required).toBe(true);
});
it('builds examples', () => {
expect(example(doc, { $ref: '#/components/schemas/List' })).toEqual({ users: [{ name: 'string', uid: 0, level: 'none' }], note: 'string' });
});
});
+66
View File
@@ -0,0 +1,66 @@
// Helpers to show an OpenAPI 3.1 document: resolve $refs, list fields,
// build example bodies.
export type Schema = {
$ref?: string; type?: string | string[]; properties?: Record<string, Schema>; required?: string[];
items?: Schema; additionalProperties?: Schema; enum?: string[]; anyOf?: Schema[]; oneOf?: Schema[];
format?: string; description?: string; contentEncoding?: string;
};
export interface Doc { components: { schemas: Record<string, Schema> } }
export function resolve(doc: Doc, s: Schema | undefined): Schema {
if (!s) return {};
if (s.$ref) return resolve(doc, doc.components.schemas[s.$ref.replace('#/components/schemas/', '')]);
return s;
}
/** Short type label, e.g. "string", "array of Share", "integer | null". */
export function typeLabel(doc: Doc, s: Schema | undefined): string {
if (!s) return 'any';
if (s.$ref) return s.$ref.replace('#/components/schemas/', '');
if (s.anyOf) return s.anyOf.map((x) => typeLabel(doc, x)).join(' | ');
if (s.oneOf) return s.oneOf.map((x) => typeLabel(doc, x)).join(' or ');
if (s.enum) return s.enum.map((e) => `"${e}"`).join(' | ');
const t = Array.isArray(s.type) ? s.type.join(' | ') : s.type;
if (t === 'array') return 'array of ' + typeLabel(doc, s.items);
if (t === 'object' && s.additionalProperties) return 'map of ' + typeLabel(doc, s.additionalProperties);
if (s.format) return `${t} (${s.format})`;
return t ?? 'any';
}
export interface Field { name: string; type: string; required: boolean; depth: number; description?: string }
/** Flattens an object schema into rows; nested objects are indented (max depth 3). */
export function fields(doc: Doc, schema: Schema | undefined, depth = 0, seen: string[] = []): Field[] {
const s = resolve(doc, schema);
const out: Field[] = [];
for (const [name, raw] of Object.entries(s.properties ?? {})) {
out.push({ name, type: typeLabel(doc, raw), required: s.required?.includes(name) ?? false, depth, description: resolve(doc, raw).description });
const ref = raw.$ref ?? raw.items?.$ref ?? raw.anyOf?.find((x) => x.$ref)?.$ref;
if (ref && depth < 2 && !seen.includes(ref)) {
const inner = raw.items ? raw.items : raw.anyOf ? raw.anyOf.find((x) => x.$ref) : raw;
out.push(...fields(doc, inner, depth + 1, [...seen, ref]));
}
}
return out;
}
/** Example value built from a schema. */
export function example(doc: Doc, schema: Schema | undefined, depth = 0): unknown {
const s = resolve(doc, schema);
if (depth > 4) return null;
if (s.enum) return s.enum[0];
if (s.anyOf) return example(doc, s.anyOf.find((x) => x.type !== 'null') ?? s.anyOf[0], depth);
if (s.oneOf) return example(doc, s.oneOf[0], depth);
const t = Array.isArray(s.type) ? s.type.find((x) => x !== 'null') : s.type;
switch (t) {
case 'string': return s.format === 'date-time' ? '2026-11-29T12:00:00Z' : 'string';
case 'integer': return 0;
case 'number': return 0;
case 'boolean': return false;
case 'array': return [example(doc, s.items, depth + 1)];
case 'object':
if (s.properties) return Object.fromEntries(Object.entries(s.properties).map(([k, v]) => [k, example(doc, v, depth + 1)]));
return {};
}
return null;
}
+166
View File
@@ -0,0 +1,166 @@
<script lang="ts">
// API documentation for admins, rendered from the server's OpenAPI 3.1
// document (GET /api/v1/openapi.json). "Try it" only for GET requests.
import { onMount } from 'svelte';
import { request } from '../lib/api';
import { toProblem } from '../lib/errors';
import type { Problem } from '../lib/types';
import { example, fields, type Doc, type Schema } from '../lib/openapi';
import PageHeader from '../components/PageHeader.svelte';
import Notice from '../components/Notice.svelte';
type Param = { name: string; in: string; required?: boolean; description?: string };
type Op = {
operationId: string; summary: string; description?: string; tags: string[]; 'x-sharestead-scope': string;
parameters?: Param[]; requestBody?: { content: Record<string, { schema: Schema }> };
responses: Record<string, { description: string; content?: Record<string, { schema: Schema }> }>;
};
type Full = Doc & { info: { version: string; description: string }; tags: { name: string; description?: string }[]; paths: Record<string, Record<string, Op>> };
let doc = $state<Full | null>(null);
let problem = $state<Problem | null>(null);
let query = $state('');
const order = ['get', 'post', 'put', 'patch', 'delete'];
onMount(async () => {
try { doc = await request<Full>('GET', '/api/v1/openapi.json'); } catch (err) { problem = toProblem(err); }
});
const ops = $derived.by(() => {
if (!doc) return [];
const list: { method: string; path: string; op: Op }[] = [];
for (const [path, item] of Object.entries(doc.paths)) for (const [method, op] of Object.entries(item)) list.push({ method, path, op });
const q = query.toLowerCase();
return list
.filter((o) => !q || (o.method + ' ' + o.path + ' ' + o.op.summary + ' ' + (o.op.description ?? '')).toLowerCase().includes(q))
.sort((a, b) => a.path.localeCompare(b.path) || order.indexOf(a.method) - order.indexOf(b.method));
});
const groups = $derived((doc?.tags ?? []).map((t) => ({ ...t, ops: ops.filter((o) => o.op.tags[0] === t.name) })).filter((g) => g.ops.length));
// Try it (GET only)
let tryParams = $state<Record<string, string>>({});
let tryResult = $state<Record<string, string>>({});
async function tryIt(method: string, path: string, op: Op) {
let url = path;
const qs = new URLSearchParams();
for (const p of op.parameters ?? []) {
const v = tryParams[op.operationId + ':' + p.name] ?? '';
if (p.in === 'path') url = url.replace('{' + p.name + '}', encodeURIComponent(v));
else if (v) qs.set(p.name, v);
}
if (qs.size) url += '?' + qs;
try { tryResult[op.operationId] = JSON.stringify(await request('GET', url), null, 2); }
catch (err) { const p = toProblem(err); tryResult[op.operationId] = `${p.status} ${p.title}\n${p.detail}`; }
}
const json = (v: unknown) => JSON.stringify(v, null, 2);
const successOf = (op: Op) => Object.entries(op.responses).filter(([c]) => c.startsWith('2'));
const errorsOf = (op: Op) => Object.entries(op.responses).filter(([c]) => !c.startsWith('2'));
</script>
<PageHeader title="API" description="Everything the web UI does, for scripts and other tools — described in OpenAPI 3.1.">
{#snippet actions()}
<input class="t search" type="search" placeholder="Search endpoints…" aria-label="Search endpoints" bind:value={query} />
<a class="btn" href="/api/v1/openapi.json" download="sharestead-openapi.json">Download openapi.json</a>
{/snippet}
</PageHeader>
<Notice {problem} />
{#if doc}
<div class="card intro">
<h2>Using the API</h2>
<p>{doc.info.description}</p>
<pre class="diff"># log in, keep the cookie, read the CSRF token
curl -sk -c jar -H 'Content-Type: application/json' -H 'Origin: {location.origin}' \
-d '{"{"}"username":"admin","password":"…"{"}"}' {location.origin}/api/v1/auth/login
# read
curl -sk -b jar {location.origin}/api/v1/shares
# change: add -H 'X-CSRF-Token: …' -H 'Origin: {location.origin}'</pre>
<p class="facts">Version {doc.info.version} · OpenAPI 3.1 · open the file in Swagger UI, Postman, Bruno or a client generator.</p>
</div>
{#each groups as g (g.name)}
<section class="card group" aria-labelledby={'tag-' + g.name}>
<h2 id={'tag-' + g.name}>{g.name}</h2>
{#if g.description}<p class="muted small desc">{g.description}</p>{/if}
{#each g.ops as { method, path, op } (op.operationId)}
<details class="op">
<summary>
<span class="method {method}">{method.toUpperCase()}</span>
<span class="mono path">{path}</span>
<span class="sum">{op.summary}</span>
<span class="pill" class:acc={op['x-sharestead-scope'] === 'admin'}>{op['x-sharestead-scope']}</span>
</summary>
<div class="body">
{#if op.description}<p>{op.description}</p>{/if}
{#if op.parameters?.length}
<h3>Parameters</h3>
<table class="fields"><tbody>
{#each op.parameters as p (p.in + p.name)}
<tr><td class="mono">{p.name}</td><td class="muted small">{p.in}{p.required ? ', required' : ''}</td><td class="small">{p.description ?? ''}</td></tr>
{/each}
</tbody></table>
{/if}
{#if op.requestBody}
{@const schema = op.requestBody.content['application/json']?.schema}
<h3>Request body <span class="muted small">application/json</span></h3>
<table class="fields"><tbody>
{#each fields(doc, schema) as f (f.depth + f.name + f.type)}
<tr><td class="mono" style:padding-left={8 + f.depth * 16 + 'px'}>{f.name}{f.required ? '' : '?'}</td><td class="mono small muted">{f.type}</td></tr>
{/each}
</tbody></table>
<pre class="diff">{json(example(doc, schema))}</pre>
{/if}
<h3>Responses</h3>
{#each successOf(op) as [code, r] (code)}
{@const schema = r.content?.['application/json']?.schema}
<p><span class="pill ok">{code}</span> {r.description}</p>
{#if schema}
<table class="fields"><tbody>
{#each fields(doc, schema) as f (f.depth + f.name + f.type)}
<tr><td class="mono" style:padding-left={8 + f.depth * 16 + 'px'}>{f.name}{f.required ? '' : '?'}</td><td class="mono small muted">{f.type}</td></tr>
{/each}
</tbody></table>
{/if}
{/each}
<ul class="errors small">
{#each errorsOf(op) as [code, r] (code)}<li><span class="pill" class:warn={code.startsWith('4')} class:bad={code.startsWith('5')}>{code}</span> {r.description}</li>{/each}
</ul>
<p class="facts">Errors are <span class="mono">application/problem+json</span> (RFC 9457) with code, title and detail.</p>
{#if method === 'get'}
<h3>Try it</h3>
<div class="row wrap">
{#each op.parameters ?? [] as p (p.name)}
<input class="t small-in" placeholder={p.name} aria-label={p.name} bind:value={tryParams[op.operationId + ':' + p.name]} />
{/each}
<button class="btn sm" onclick={() => tryIt(method, path, op)}>Send GET</button>
</div>
{#if tryResult[op.operationId]}<pre class="diff result">{tryResult[op.operationId]}</pre>{/if}
{/if}
</div>
</details>
{/each}
</section>
{/each}
{:else if !problem}
<p class="muted">Loading…</p>
{/if}
<style>
.intro, .group { margin-bottom: 16px; }
.op { border-top: 1px solid var(--line); }
.op summary { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; padding: 10px 4px; cursor: pointer; min-height: 44px; }
.op summary:hover { background: var(--bg); }
.method { font: 700 11px/1 ui-monospace, monospace; padding: 4px 6px; border-radius: 5px; min-width: 58px; text-align: center; background: var(--bg); color: var(--text); border: 1px solid var(--line); }
.method.get { background: var(--accent-soft); color: var(--accent); }
.method.post, .method.put, .method.patch { background: var(--warn-soft); color: var(--warn); }
.method.delete { background: var(--bad-soft); color: var(--bad); }
.path { overflow-wrap: anywhere; }
.sum { flex: 1 1 200px; color: var(--muted); }
.body { padding: 4px 4px 16px; }
h3 { font-size: 13px; margin: 14px 0 6px; }
.fields td { padding: 4px 8px; }
.errors { list-style: none; padding: 0; margin: 10px 0 0; display: grid; gap: 4px; }
.wrap { flex-wrap: wrap; }
.small-in { width: 180px; }
.result { max-height: 360px; margin-top: 8px; }
</style>
+1
View File
@@ -44,6 +44,7 @@
<ul class="small">
<li>Something doesn’t work? The <a href="#/problems">Problems</a> page says what is wrong and what to do.</li>
<li>Every change is listed under <a href="#/changes">Changes</a> and can be undone there.</li>
<li>Scripts and other tools can do everything the UI does: see <a href="#/api">API</a> (OpenAPI 3.1).</li>
<li>The config files stay the source of truth: <span class="mono">/etc/samba/smb.conf</span>, <span class="mono">/etc/exports</span>. Hand edits show up here.</li>
</ul>
</div>