# Architecture

FuzzyShare is one Go module, standard library plus one dependency (goldmark, which renders these docs), built into a single binary: the server, its web UI, the MCP endpoint and the command-line client. The code is split into small packages with one-way dependencies.

## Code map

```
cmd/fuzzy/               the binary: the version variable and the choice between server and client
internal/config/        settings from FUZZY_* variables, the hard limits, size and lifetime parsing and printing
internal/docsite/       the documentation: front matter, Markdown rendering, navigation, search index
internal/filetype/      content-type detection and the file kinds used for previews (pure functions)
internal/store/         everything on disk: files, users, keys, links, the unlock secret, the sweeper
internal/server/        the HTTP application
internal/server/servertest/   throwaway servers for tests in other packages
internal/cli/           the command-line client; talks to a server only over HTTP
web/                    the browser UI, embedded into the binary
docs/                   the documentation pages (Markdown), embedded into the binary
```

### Dependencies

```
cmd/fuzzy ---> internal/server ---> internal/store ---> (nothing internal)
    |              |  |
    |              |  +--------> internal/config
    |              +-----------> internal/filetype
    |              +-----------> web
    +--------> internal/cli      (imports nothing else from this module)
    +--------> internal/config   (to load the settings it hands to the server)
```

Arrows point at what a package imports. `internal/cli` never imports the server: it is tested end to end against `servertest`, but at run time it only speaks HTTP.

### cmd/fuzzy

| File | Responsibility |
|---|---|
| `main.go` | `version` (stamped with `-ldflags "-X main.version=..."`), loads the config and starts the server when the arguments ask for it; everything else goes to `cli` |

### internal/config

| File | Responsibility |
|---|---|
| `config.go` | `Config`, `Load` from the environment, the 14-day and 1 GB hard limits, `ParseTTL`, `FormatTTL`, `FormatSize` |

### internal/filetype

| File | Responsibility |
|---|---|
| `filetype.go` | `Detect` (declared type, then extension, then the first bytes), `KindOf` (html, svg, image, pdf, video, audio, markdown, link, csv, json, text, other), `BaseType` |

### internal/store

`Store` owns the data directory and its locking. Nothing in it knows about HTTP.

| File | Responsibility |
|---|---|
| `store.go` | `Open`, the injectable clock (`Now`, `SetClock`), atomic JSON writes, shared errors |
| `files.go` | File bytes and `Meta`: `OpenFile`, `Put`, `Remove`, `List`, `Usage`, `NewTemp` |
| `users.go` | Accounts: `CreateUser`, `UserByKey`, `UserByID`, `Touch`, `ListUsers`, `DeleteUser` |
| `keys.go` | Named keys: `AddKey`, `RemoveKey`, `RotateKey`, naming rules, migration of old accounts |
| `links.go` | Link records: create, list, revoke, resolve, count reads (`ReadLink`), the link limits |
| `access.go` | The per-link access log: capped append-only JSONL, collapse, totals, cleanup |
| `fingerprint.go` | Key fingerprints (`sha256:` and 16 hex characters) |
| `secret.go` | The secret that signs unlock cookies |
| `sweep.go` | `Sweep` and `SweepLoop`: expired files, dead links, orphans, stale temp files |
| `ids.go` | Hashing, random tokens and account-id validation |

### internal/server

| File | Responsibility |
|---|---|
| `server.go` | `Server`, `New(cfg, st)`, `Handler()` |
| `run.go` | `Run`: open the store, start the sweeper, serve until SIGINT or SIGTERM |
| `routes.go` | The URL table and `method`, which turns a wrong method into a JSON `405` |
| `httputil.go` | Request logging, JSON helpers, the public base address, the client IP |
| `info.go` | `/health`, `/config` and the limits reported to clients |
| `auth.go` | Identity: bearer keys, registration, `/me`, key rotation, the signup rate limit |
| `keys.go` | `/me/keys`: list, create, revoke |
| `admin.go` | Admin-only user listing and removal |
| `files.go` | Upload, download, list and delete of a person's files |
| `links.go` | Creating, listing and revoking links, public/private visibility |
| `share.go` | Reading a link: the preview page route, `/raw` and `/info` |
| `access.go` | Link activity: recording hooks at the read points and `GET /links/{id}/activity` |
| `device.go` | Device and bot labels from the user agent |
| `unlock.go` | Private links: passphrase hashing, rate limit, unlock cookie, key allow-list |
| `serve.go` | Serving file bytes with the right headers for each kind of file |
| `pages.go` | Embedded pages: landing, 404, `llms.txt`, `robots.txt`, `sitemap.xml` |
| `docs_*.go` | The documentation site: routes, page template, the search index and `llms-full.txt` |
| `llms.txt.tmpl` | The agent guide served at `/llms.txt` |
| `mcp.go` | The MCP server: JSON-RPC handling and the tools |

### internal/cli

`App` carries the streams, environment, clock and HTTP client of one run, so tests can swap them. `cli.go` holds dispatch, help and flag parsing; `client.go` the HTTP client; the other files one command group each (`account.go`, `put.go`, `files.go`, `links.go`, `keys.go`, `transfer.go`, `config.go` for the saved login). Every command is documented in the [command reference](cli-reference.md).

### web

`web/` holds the HTML, CSS and JavaScript of the UI (no build step). `embed.go` exports it as `web.FS`; only `*.html`, `*.css`, `*.js`, `*.svg` and the fonts are embedded, so the Go file is never served. `internal/server/pages.go` and `aliases.go` map the addresses to pages.

| Address | Page | Files |
|---|---|---|
| `/` | marketing landing (static, crawlable) | `landing.html`, `landing.css`, `landing.js` |
| `/access`, `/signup` | sign in with an access key; get an access key | `access.html`, `signup.html`, `auth.js`, `pages.css` |
| `/dashboard`, `/dashboard/...` | the app shell; every path gets the same HTML and the browser routes with the History API | `app.html`, `dashboard.css`, the scripts below |
| `/status` | health check page | `status.html`, `status.js` |
| `/s/{token}` | share viewer; unknown pages get `404.html` | `view.html`, `view.js`, `404.html` |
| `/login`, `/app`, `/cli`, `/api`, ... | permanent redirects (a table in `aliases.go`) | |

Pages are served with `https://fuzzyshare.com` replaced by the server's address and a strict CSP (no inline script or style). `boot.js` runs in `<head>` and sends people with a saved access key from `/`, `/access` and `/signup` to `/dashboard`, and people without one from `/dashboard*` to `/access?next=`.

Stylesheets: `theme.css` (design tokens), `base.css`, `components.css` (button, input, card, badge, tabs, table, dialog, states), `dashboard.css`, `landing.css`, `pages.css`. Scripts share `window.Siso`:

| File | Responsibility |
|---|---|
| `core.js` | DOM helper `h`, formatting, requests with the progress bar, icons, the saved key |
| `ui.js` | reusable components (button, field, table, tabs, code block, dialog, empty and error states) |
| `shell.js` | frame (icon rail, sidebar, top bar, user menu, slide-over) and the router |
| `sec-*.js`, `keys.js` | one file per dashboard section; each pushes `{id, path, group, title, icon, render}` onto `FuzzyShare.sections` |
| `links.js`, `paste.js` | the share dialog, access badge and activity dialog; the paste panel |
| `auth.js`, `landing.js`, `status.js`, `view.js` | the public pages and the share viewer |

## Tests

Tests sit next to the code they check. The server's own tests run the real handlers through `httptest` with an injectable clock (`Store.SetClock`), so expiry is tested without waiting. Tests in other packages use `internal/server/servertest`, which starts a real server on a temporary directory and exposes its URL, data directory and clock; the CLI's end-to-end and cross-feature tests (`internal/cli/e2e_test.go`, `integration_test.go`) are built on it.

## Storage

Everything is a plain file under `FUZZY_DIR`. There is no database.

```
users/<uid>.json         profile and its keys (id, name, hash, hint, times)
keys/<sha256(key)>       the uid that key belongs to, one file per key
data/<uid>/<name>        file bytes
meta/<uid>/<name>.json   size, type, upload and expiry times, a per-upload id
share/<sha256(token)>    link record: owner, file version, expiry, access mode, passphrase hash, allow-list, read counts
access/<linkid>.jsonl   capped access log of one link, deleted with the link
secret                   32 random bytes that sign unlock cookies (mode 0600)
tmp/                     uploads and writes in flight
```

- Files are written to `tmp/` and renamed into place, so readers never see a partial file. Metadata is written the same way.
- One `sync.RWMutex` in the store guards reads against commits and sweeps. It is held briefly: bytes are streamed to `tmp/` outside the lock and moved in under it.
- A link id is `l_` plus the first 12 hex characters of the record's file name, so finding a link by id needs no index. Public links keep their token in the record so the URL can be shown again; private links keep only hashes.
- A share record stores the upload id of the file version it points at. Replacing or deleting the file changes the id, which revokes the link without tracking links per file.

## Request flow

1. `logged` (`httputil.go`) wraps the mux and logs the route pattern, never the path, so share tokens stay out of logs.
2. `method` (`routes.go`) dispatches by HTTP method so a wrong method returns a JSON `405`.
3. Handlers call `requireUser` (`auth.go`), which hashes the bearer key and looks it up in `keys/`.
4. File handlers work in the caller's own `data/<uid>/` and `meta/<uid>/`, so one person can never address another's files by name.

## Expiry

Expiry is checked on every read: an expired file is invisible immediately. The sweeper (`Store.SweepLoop`, at startup and then every `FUZZY_SWEEP_INTERVAL`) deletes expired files, share records pointing at nothing, files without metadata, files of removed users, and stale temp files.

## Previews

`filetype.KindOf` maps a content type to a kind. Share links serve a preview page to browsers (`Accept: text/html`) and bytes to everything else. The page renders by building DOM nodes, never by inserting HTML. HTML files are shown in an iframe with `sandbox` and without `allow-same-origin`, and their bytes are served with a CSP that does the same, so an uploaded page runs in an opaque origin.

## Design choices

- **No database.** The data is small, short-lived and keyed by name; the filesystem is enough and a backup is a copy.
- **Keys as identity.** One bearer key per person, hashed at rest, sent on every call. It keeps clients trivial (`curl -H`) and gives agents and people the same model.
- **Hard limits in code.** The 14-day and 1 GB ceilings are constants, so a misconfiguration cannot turn FuzzyShare into long-term storage.
- **Embedded docs.** The pages are Markdown in `docs/`, rendered on the server so every URL is crawlable and works without JavaScript.
- **Embedded UI.** `go:embed` (in `web/embed.go`) keeps deployment to one file. The UI has no build step and no dependencies.
