# Filemanager sync API (v1)

This API is for apps that sync files with the file manager: phone apps,
desktop sync clients, or background services. It covers login with user
consent, listing, a change feed (delta), upload (including resumable
uploads for large files), download with Range, folders, move, delete and
conflict detection.

- Machine-readable spec: [`docs/openapi.json`](openapi.json). A running
  server also serves it at `/api/v1/openapi.json`.
- OAuth metadata: `/.well-known/oauth-authorization-server`.
- Users manage access on **`/apps.html`** ("Connected apps"). There they
  can see every authorised app, device and token, see when each was last
  used, revoke them, and create personal tokens.

A token can never see more than its user can. Every request goes through
the same permission checks as the web UI: per-root read/write rights,
the user's own folder, and admin rights.

## 1. Register your app (once)

An admin registers the app on `/apps.html` under "OAuth clients". You
provide a name and one or more redirect URIs and get back a `client_id`
(`fmc_...`). Clients are **public**: there is no client secret, and PKCE
is mandatory.

These redirect URIs are allowed:

| Kind | Example | Notes |
|---|---|---|
| HTTPS | `https://sync.example.com/callback` | Web services |
| Loopback | `http://127.0.0.1/callback` | Desktop apps. Any port is accepted at runtime (RFC 8252) |
| Private scheme | `com.example.sync:/callback` | Mobile apps |

## 2. Authorisation (authorization code + PKCE)

1. Generate a `code_verifier`: 43–128 characters from `A-Z a-z 0-9 - . _ ~`.
   Then compute `code_challenge = BASE64URL(SHA256(code_verifier))`.
2. Open the following URL in the system browser:

   ```
   GET /oauth/authorize?response_type=code
       &client_id=fmc_...
       &redirect_uri=com.example.sync:/callback
       &scope=files:read%20files:write
       &state=<random>
       &code_challenge=<challenge>&code_challenge_method=S256
       &device_name=Tim's%20Pixel
   ```

   The user sees which app, which device and which permissions are
   requested. They sign in and click **Allow** or **Deny**.
3. The browser is redirected to `redirect_uri?code=...&state=...&iss=...`.
   Check that `state` matches the value you sent. The code is valid for
   10 minutes and works only once. If the user denied access, you get
   `error=access_denied` instead.
4. Exchange the code for tokens:

   ```
   POST /oauth/token   (application/x-www-form-urlencoded or JSON)
   grant_type=authorization_code&client_id=fmc_...&code=...
   &redirect_uri=com.example.sync:/callback&code_verifier=...
   ```

   ```json
   {"access_token":"fma_...","token_type":"Bearer","expires_in":3600,
    "refresh_token":"fmr_...","scope":"files:read files:write","grant_id":"g_..."}
   ```

5. Send `Authorization: Bearer <access_token>` on every API call. An
   access token is valid for 1 hour. Renew it with
   `grant_type=refresh_token&client_id=...&refresh_token=...`.
   **Refresh tokens rotate**: always store the new one. If an old refresh
   token is used again, the whole grant is revoked, because that points to
   a stolen token. A refresh token expires after 90 days without use.
6. Logout: `POST /oauth/revoke` with `token=<refresh or access token>`.

Each authorisation is a separate grant, so each device has its own
tokens, and the user can revoke one device without affecting the others.

**Scopes:** `files:read` lets an app list, read, download and use the
delta feed. `files:write` lets it upload, create folders, move and delete,
and always includes `files:read`.

**Personal tokens** (`fmp_...`) for your own scripts are created on
`/apps.html`. They are used the same way (`Authorization: Bearer`), can
optionally expire, and can be revoked there.

## 3. Paths and roots

`GET /api/v1/roots` returns the roots the user can see. `~` is always the
user's own folder. Other roots are the shared folders the user has rights
to. All paths are virtual and have the form `/<root-id>/<relative path>`,
for example `/~/Photos/2024/a.jpg` or `/team/report.pdf`. The segments
`..` and `.`, backslashes and symlinks that leave the root are refused,
and symlinks are not listed.

Every file or folder (`Entry`) has the following fields:

| Field | Meaning |
|---|---|
| `id` | Stable identity. It stays the same across renames and moves on the same disk |
| `path`, `name`, `type` | `type` is `file` or `folder` |
| `size`, `mtime`, `mtime_ms` | Size and modification time |
| `version` | Opaque. It changes on every change and is also the `ETag` |
| `sha256` | Present when known. Use `GET /files/metadata?path=..&hash=1` to have it computed |

## 4. Sync walkthrough

```text
# First sync of a root
GET /api/v1/delta?root=~                     -> reset=true, entries(change=exists), cursor, has_more
GET /api/v1/delta?root=~&cursor=<c>          -> repeat while has_more
store cursor

# Every time after that (poll, e.g. every 30-60 s or when the app comes to the foreground)
GET /api/v1/delta?root=~&cursor=<c>
  created  -> download (GET /files/content)
  modified -> download if version differs from your local copy
  moved    -> rename locally old_path -> path (children are implied)
  deleted  -> delete locally (folders: including contents)
  repeat while has_more, then store the new cursor
410 cursor_expired -> start over without a cursor and reconcile with local state
```

The feed sees all changes: those made through the API, through the web
UI, and directly on disk. Changes from outside the API become visible
within about 15 seconds (`api.scanIntervalSeconds`). Changes made through
the API show up right away.

Pushing local changes:

```text
new file   : PUT /files/content?path=/~/a.txt&mtime=<ms>   + If-None-Match: *
changed    : PUT /files/content?path=/~/a.txt               + If-Match: "<version you last saw>"
large file : POST /uploads {path,size,sha256,mtime,if_match|if_none_match}
             PATCH /uploads/<id> (Upload-Offset: n, body = chunk <= max_chunk_bytes) ...
             on interruption: GET /uploads/<id> -> offset, resume from there
             POST /uploads/<id>/complete
rename/move: POST /files/move {from,to,if_match}
delete     : DELETE /files?path=..&recursive=true  + If-Match
folder     : POST /folders {path, parents:true, exist_ok:true}
```

**Conflicts:** a write never overwrites anything silently.

- `412 precondition_failed`: the version no longer matches `If-Match`, or
  the target already exists while you sent `If-None-Match: *`.
- `409 conflict`: the target exists and you sent no `If-Match`.

Both responses include `current`, the server's state. The usual approach
is to save your local copy under a new name, such as
`a (conflict from Pixel).txt`, and then download the server version.
`overwrite=true` replaces the target on purpose.

Uploads first go to a temporary file. They only become visible after
the size and SHA-256 are verified, with an atomic rename. That way other
clients never see a half-written file.

**Download:** `GET /files/content?path=..` supports `Range`/`If-Range`,
which lets an app resume a download, and `If-None-Match`, which returns
304. The `ETag` is the `version`.

**Delete is permanent.** The file manager has no trash, so ask the user
for confirmation before you delete.

## 5. Errors and limits

Errors are always JSON: `{"error": "<code>", "message": "..."}`.

| Status | Codes |
|---|---|
| 400 | `invalid_path`, `invalid_request`, `invalid_cursor`, `not_a_folder`, `not_a_file` |
| 401 | `invalid_token` |
| 403 | `insufficient_scope`, `forbidden` |
| 404 | `not_found`. Also returned for paths you are not allowed to see |
| 409 | `conflict`, `parent_missing`, `folder_not_empty`, `offset_mismatch`, `incomplete` |
| 410 | `cursor_expired` |
| 412 | `precondition_failed` |
| 413 | `too_large` |
| 422 | `checksum_mismatch` |
| 429 | `too_many_uploads` |
| 507 | `quota_exceeded`, `too_many_entries` |

The limits are in `GET /api/v1/me` and can be set in `config.json` under
`"api"`:

| Key | Default |
|---|---|
| `maxUploadBytes` | 10 GB |
| `maxChunkBytes` | 64 MB |
| `maxOpenUploadsPerUser` | 20 |
| `uploadTtlHours` | 24 |
| `maxHashBytes` | 4 GB |
| `scanIntervalSeconds` | 15 |
| `maxSyncEntries` | 500000 |
| `uploadDir` | `<app>/api-uploads` |

The personal-folder quota (`userFolderSizeLimit`) also applies to the
API. The change history is kept for 30 days.

## 6. Example (curl, personal token)

```bash
T=fmp_...; H="Authorization: Bearer $T"; S=https://files.example.com/api/v1
curl -H "$H" $S/roots
curl -H "$H" -T notes.txt -H 'If-None-Match: *' "$S/files/content?path=/~/notes.txt"
curl -H "$H" "$S/files/content?path=/~/notes.txt" -o notes.txt
curl -H "$H" "$S/delta?root=~"
```
