# Tunnelbox Downloads — REST API

Audience: a script or AI agent working for one store. Follow section 3 for a bulk migration; section 4 lists every endpoint.

- Base URL: `https://tunnelbox.quantumtunnel.foundation/api/v1` (the merchant sees the exact value on *Settings → API access*; `GET https://tunnelbox.quantumtunnel.foundation/api/v1/docs` returns this document with the host filled in).
- Everything is scoped to the store that owns the API key. There is no way to reach another store.
- JSON over HTTPS. Send `Content-Type: application/json` on requests with a body. Responses are JSON with `Cache-Control: no-store`. There is no CORS: call from a server or script, not from a browser.
- File bytes never go through this API. You upload them directly to object storage with a short-lived presigned URL; you hold only the API key, never storage credentials.

## 1. Authentication

The merchant creates a key in the Shopify admin (*Apps → Digital Downloads → Settings → API access → Create API key*). The full key (`cdd_…`, 47 characters) is shown once.

```
Authorization: Bearer cdd_Ab12Cd...
```

A missing, unknown or revoked key, or an uninstalled store, gives `401 unauthorized`. Never log or print the key.

## 2. Conventions

### Errors

```json
{ "error": { "code": "validation_error", "message": "files may contain at most 100 entries (got 101).", "details": { "max": 100 } } }
```

| Status | `code` | Meaning |
|---|---|---|
| 400 | `validation_error`, `invalid_json` | Malformed request. Fix it; do not retry unchanged. |
| 401 | `unauthorized` | Bad/revoked key. Stop and tell the merchant. |
| 402 | `plan_limit` | The store's plan has no room for the new files (`details.reason`: `no_plan`, `files` or `storage`). Stop; the merchant must upgrade or delete files. Retrying does not help. |
| 404 | `not_found` | Unknown id, or it belongs to another store. |
| 405 | `method_not_allowed` | `Allow` header lists the right methods. |
| 409 | `conflict` codes: `upload_missing`, `size_mismatch`, `invalid_state`, `ambiguous_order` | The resource is not in the right state; see the endpoint. |
| 413 | `payload_too_large` | Request body over 25 MB. Send fewer items. |
| 429 | `rate_limited` | Wait `Retry-After` seconds, then retry. |
| 500 | `internal_error` | Retry with backoff (idempotent calls only, see below). |

Batch endpoints (`POST /files`, `POST /files/external`) answer `200` with one result per item; a bad item gets `"status": "error"` and `"error": { "code", "message" }` without failing the others. An item that does not fit the store's plan gets code `plan_limit`.

### Plan limits

Every store's plan caps the number of files (hosted and external) and the storage of hosted files; the current numbers are on the app's Plans page. Limits only stop *new* files: linking existing files, imports that only link library files, downloads and deletes always work. A hosted upload counts its declared `size` from `POST /files` on, so declare the real size.

### Rate limit

20 requests per second per key, bursts up to 40. The limiter is in memory and **per server process**; the app runs as a single web process, so treat it as one global limit. Over the limit: `429` with `Retry-After` (seconds). Back off and retry; do not hammer.

### Limits

| Limit | Value |
|---|---|
| Files per `POST /files` | 100 |
| Files per `POST /files/external` | 500 |
| Rows per `POST /imports` | 50,000 |
| Names per `GET /files?names=` | 500 (keep the URL under ~8 KB: about 200 names; use 100) |
| Request body | 25 MB |
| Largest file | `maxUploadBytes` from `GET /shop` (default 5 GiB) |
| Presigned upload URL lifetime | 1 hour (`upload.expiresAt`) |
| Orders per page | 100 |
| Import error rows | 100 in `GET /imports/{id}`, 500 per page in `/errors` |

Idempotency: `GET`, `POST /files` (same name → `exists`/resume), `POST /files/{id}/complete`, `POST /files/external` (same URL → `reused`), `proceed`/`cancel` (second call → 409) and linking via imports (same variant+file again updates, never duplicates) are safe to repeat. `POST /imports` is not: a retry after a timeout creates a second import (harmless, because re-linking is idempotent, but it is extra work).

## 3. Bulk migration recipe (SKU → file)

Input you need: a list of `(sku, filename)` pairs and the local files. File names are unique per store and matched **exactly** (case-insensitively) by imports.

### Step 1 — Check the store

```bash
curl -sS -H "Authorization: Bearer $KEY" https://tunnelbox.quantumtunnel.foundation/api/v1/shop
```
```json
{ "shopDomain": "example-store.myshopify.com", "deliveryEnabled": true, "storageDriver": "s3", "maxUploadBytes": 5368709120 }
```

Skip files larger than `maxUploadBytes` and report them. `deliveryEnabled: false` means buyers cannot download yet; tell the merchant.

### Step 2 — Upload files (batches of 100)

For each batch of up to 100 files:

1. `POST /files` with `{ "files": [{ "name", "size", "contentType" }] }` (`size` = exact byte length).
2. For each result:
   - `status: "exists"` → skip (already in the library; `fileStatus: "ready"` means done).
   - `status: "upload"` → `PUT` the bytes to `upload.url` with **exactly** the returned `upload.headers`, then `POST /files/{fileId}/complete`.
   - `status: "error"` → log `error.message`, skip.

```bash
curl -sS -X POST https://tunnelbox.quantumtunnel.foundation/api/v1/files \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"files":[{"name":"Book One.pdf","size":1048576,"contentType":"application/pdf"}]}'
```
```json
{ "files": [ {
  "name": "Book One.pdf", "status": "upload", "fileId": "6f0c…",
  "upload": { "method": "PUT", "url": "https://….r2.cloudflarestorage.com/…?X-Amz-Signature=…",
              "headers": { "Content-Type": "application/pdf" }, "expiresAt": "2026-10-23T08:00:00.000Z" }
} ] }
```

Upload and complete (curl streams the file; do not read it into memory):

```bash
curl -sS -f -X PUT -H "Content-Type: application/pdf" --upload-file "Book One.pdf" "$UPLOAD_URL"
curl -sS -X POST -H "Authorization: Bearer $KEY" https://tunnelbox.quantumtunnel.foundation/api/v1/files/6f0c…/complete
```

Python:

```python
import os, time, requests

BASE = "https://tunnelbox.quantumtunnel.foundation/api/v1"
S = requests.Session()
S.headers["Authorization"] = f"Bearer {os.environ['DIGI_API_KEY']}"

def api(method, path, **kw):
    for attempt in range(6):
        r = S.request(method, BASE + path, timeout=120, **kw)
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", "1")))
        elif r.status_code >= 500:
            time.sleep(2 ** attempt)
        else:
            return r
    r.raise_for_status()
    return r

def upload_batch(paths):
    body = {"files": [{"name": os.path.basename(p), "size": os.path.getsize(p),
                       "contentType": "application/pdf"} for p in paths]}
    by_name = {os.path.basename(p): p for p in paths}
    for item in api("POST", "/files", json=body).json()["files"]:
        if item["status"] != "upload":
            print(item["name"], item["status"], item.get("error", ""))
            continue
        up = item["upload"]
        with open(by_name[item["name"]], "rb") as fh:          # file object => streamed, not buffered
            put = requests.put(up["url"], data=fh, headers=up["headers"], timeout=3600)
        put.raise_for_status()                                  # do NOT send the API key to this host
        done = api("POST", f"/files/{item['fileId']}/complete")
        done.raise_for_status()
```

Do not send the `Authorization` header to `upload.url`; it is a different host and is already signed. Upload with a few parallel workers (4–8); the limit that matters is the 20 req/s API limit, not the uploads.

**Retry rules**

- Network error / 5xx on the `PUT`: retry the same `PUT` up to 3 times with backoff while `expiresAt` has not passed.
- `PUT` answered 403 or the URL expired: call `POST /files` again with the same name. The unfinished file is resumed (`status: "upload"`, same `fileId`, `"resumed": true`) with a fresh URL.
- `complete` → `409 upload_missing`: the bytes did not arrive; `PUT` again, then complete.
- `complete` → `409 size_mismatch`: the uploaded size differs from the `size` you declared; re-`PUT` the correct file (declare the right size via `POST /files` if the local file changed).
- `complete` → 5xx / 429: repeat; it is idempotent.
- Never reuse an upload URL after `expiresAt`.

Verify the whole set before importing (up to 500 names per call; use 100):

```bash
curl -sS -G -H "Authorization: Bearer $KEY" https://tunnelbox.quantumtunnel.foundation/api/v1/files \
  --data-urlencode "names=Book One.pdf,Book Two.pdf"
```
`files[].status` must be `ready`; `missing` lists names that do not exist.

### Step 3 — Link files to products (import)

`POST /imports` with one row per (variant, file). `variant` is the SKU (default `dataType: "sku"`) or a variant id; `filename` must be the exact library name from step 2. Several rows may share a SKU (several files for one product) or a file (one file on many SKUs).

```bash
curl -sS -X POST https://tunnelbox.quantumtunnel.foundation/api/v1/imports \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"name":"example migration 1","rows":[{"variant":"EM-0001","filename":"Book One.pdf"},{"variant":"EM-0002","filename":"Book Two.pdf"}]}'
```
```json
{ "importId": "b1d2…", "status": "validating" }
```

`202`: the rows are stored and a background job validates them against the Shopify catalog (SKUs resolved, files looked up). Up to 50,000 rows per import; large imports can take several seconds to accept, so use a generous timeout (120 s). For more rows, split into several imports.

Poll `GET /imports/{importId}` every 2–5 s until `status` is `review` (or `failed`):

```json
{
  "importId": "b1d2…", "status": "review",
  "totals": { "total": 2, "valid": 1, "invalid": 1, "succeeded": 0, "failed": 0 },
  "errors": [ { "row": 2, "variant": "EM-0002", "filename": "Book Two.pdf", "externalUrl": "", "status": "invalid",
                "errors": [ { "code": "file_not_found", "message": "No file named \"Book Two.pdf\" in the library." } ] } ],
  "error": null, "createdAt": "2026-10-23T07:00:00.000Z", "completedAt": null
}
```

Inspect `errors` (first 100; page through `GET /imports/{id}/errors?page=N` for all). Row `error.code` values: `missing_variant`, `variant_not_found`, `sku_not_found`, `duplicate_sku` (the SKU matches several variants), `missing_file_and_url`, `file_not_found`, `invalid_url`, `invalid_data_type`, `invalid_boolean`, `apply_failed`. Decide:

- Fix cause (upload the missing file, correct the SKU) and either `POST …/cancel` and create a new import, or
- `POST /imports/{id}/proceed` to apply the valid rows now. Rows with errors are skipped, not applied; re-submit them in a later import.

After `proceed` (`202`, status `processing`) poll `GET /imports/{id}` until `completed`. Check `totals.succeeded` and `totals.failed`; failed rows appear in `errors` with `status: "failed"` and code `apply_failed` (or `plan_limit` when the plan filled up during the import). `proceed` and `cancel` work only from `review` (else `409 invalid_state`). An import whose rows would add more new external files than the plan allows is refused with `402 plan_limit` and stays in `review`. Status flow: `validating → review → processing → completed`; `failed` (see `error`) or `cancelled` are terminal.

### Step 4 — Spot-check

`GET /orders?limit=5` and `GET /orders/{id}` show real orders and the files each line grants. To confirm a product, look for an order with that SKU; otherwise ask the merchant to open a buyer link from an order (`buyerUrl`) and download once. New digital orders are picked up automatically from Shopify; this API does not create orders.

## 4. Endpoint reference

All paths are relative to the base URL and need the `Authorization` header.

### `GET /shop`
Returns `{ shopDomain, deliveryEnabled, storageDriver, maxUploadBytes }`.

### `POST /files`
Request upload URLs. Body `{ "files": [{ "name": string, "size": integer > 0, "contentType"?: string }] }`, 1–100 items. `name` is a plain file name (no `/` or `\`, max 255 chars) and is used exactly as given; the API never adds a suffix.

Per item `status`:

| `status` | Fields | Meaning |
|---|---|---|
| `exists` | `fileId`, `fileStatus`, `existingName?` | A file with this name exists (names compare case-insensitively; `existingName` shows the stored spelling). No upload needed. |
| `upload` | `fileId`, `upload { method:"PUT", url, headers, expiresAt }`, `resumed?` | Upload the bytes, then call `complete`. `resumed: true`: an earlier unfinished upload of this name got a fresh URL. |
| `error` | `error { code, message }` | `invalid_file` (bad name/size/contentType), `file_too_large`, or `plan_limit`. |

Errors: 400 (body not an object, `files` missing/empty/over 100), 413.

### `POST /files/{fileId}/complete`
Checks the object exists in storage and has the declared size, then marks the file `ready`. Idempotent. `200 { "file": { fileId, name, kind, status, byteSize, createdAt } }`. Errors: 404; 409 `upload_missing`; 409 `size_mismatch`.

### `POST /files/external`
Register files hosted elsewhere. Body `{ "files": [{ "name"?: string, "url": "https://…" }] }`, 1–500 items. Per item: `{ name, url, status: "created" | "reused" | "error", fileId }`. The same URL reuses its file. If `name` is taken by a different URL the stored name gets a ` (2)` suffix; use the returned `name`. Only `http(s)` URLs.

### `GET /files`
- `?names=a.pdf,b.pdf` (repeatable; max 500, exact match; names containing a comma cannot be queried this way, use `q`) → `{ files: [{ fileId, name, kind, status, byteSize, createdAt }], missing: [names] }`.
- `?q=<substring>&page=N` (100 per page, newest first; omit `q` to list all) → `{ files, page, total, hasNext }`.

`kind` is `hosted` or `external`; `status` is `uploading` or `ready`; `byteSize` is null for external files.

### `DELETE /files/{fileId}`
`200 { "deleted": true, "fileId" }`. **Destructive:** the file is removed from storage, from every product link, and from past orders, so **buyers lose access to it** (including existing buyer download links). Re-uploading does not restore past orders' access. Errors: 404.

### `POST /imports`
Body:

```json
{ "name": "optional label", "rows": [ { "variant": "EM-0001", "dataType": "sku", "filename": "Book One.pdf", "externalUrl": "https://…", "allVariants": false } ] }
```

- `variant` (required string): SKU or variant id. `dataType`: `"sku"` or `"variant_id"`; omit to infer. `filename` (library file name) and/or `externalUrl` (creates/reuses an external file): at least one is needed, else the row is reported invalid. `allVariants` (boolean, default false): link the file to every variant of the product that owns the variant.
- 1–50,000 rows. Type errors (a non-string `variant`, a bad `dataType`…) fail the whole request with `400` and `details.problems` (row numbers are 1-based). Everything else is validated later and shows up per row.

`202 { importId, status: "validating" }`. Errors: 400, 413.

### `GET /imports/{id}`
`{ importId, status, totals: { total, valid, invalid, succeeded, failed }, errors: [first 100], error, createdAt, completedAt }`. `status`: `validating`, `review`, `processing`, `completed`, `failed`, `cancelled`. `error` is a message when `failed`. Error rows: `{ row, variant, filename, externalUrl, status: "invalid"|"skipped"|"failed", errors: [{ code, message }] }`. Errors: 404.

### `GET /imports/{id}/errors?page=N`
`{ errors: [...same rows], page, pageSize: 500, total, hasNext }`.

### `POST /imports/{id}/proceed`  ·  `POST /imports/{id}/cancel`
Same rules as the admin screen: allowed only while `status` is `review`. `proceed` → `202 { importId, status: "processing" }`; `cancel` → `200 { importId, status: "cancelled" }`. Otherwise `409 invalid_state` with `details.status`. `proceed` → `402 plan_limit` when the import's new files do not fit the plan. Errors: 404.

### `GET /orders?since=<ISO>&limit=<1-100>&cursor=<opaque>`
Digital orders oldest first by `createdAt` (when the app recorded the order, so back-filled old orders still appear in order for pollers). `since` is inclusive; `cursor` (from `nextCursor`) takes precedence over `since`. Default `limit` 50.

```json
{ "orders": [ { "orderId": "uuid", "orderName": "#1001", "email": "a@b.c", "orderedAt": "…", "createdAt": "…",
                "accessEnabled": true, "accessReason": null, "fulfilledAt": null, "downloads": 2 } ],
  "nextCursor": "eyJ0Ijo…" }
```
`nextCursor` is null on the last page. `accessReason`: `manual`, `refunded`, `cancelled` or null. Errors: 400 (`since`, `limit`, `cursor`).

### `GET /orders/{idOrName}`
`idOrName` is the `orderId` uuid, or the order number (`#1001` or `1001`, URL-encode `#` as `%23`).

```json
{ "orderId": "uuid", "orderName": "#1001", "email": "…", "customerName": "…", "financialStatus": "PAID",
  "orderedAt": "…", "createdAt": "…", "cancelledAt": null, "accessEnabled": true, "accessReason": null,
  "accessChangedAt": null, "fulfilledAt": null, "emailSentAt": null,
  "buyerUrl": "https://shop.myshopify.com/apps/downloads/orders/…", "downloads": 2,
  "items": [ { "title": "Book One", "variantTitle": null, "sku": "EM-0001", "quantity": 1, "refundedQuantity": 0,
               "files": [ { "fileId": "uuid", "name": "Book One.pdf", "kind": "hosted", "status": "ready", "downloads": 2 } ] } ] }
```
Errors: 404; 409 `ambiguous_order` if several orders share that number (use the uuid).

### `POST /orders/{idOrName}/access`
Body `{ "enabled": boolean }`. Same as the admin enable/disable: disabling sets `accessReason: "manual"` and buyers cannot download until enabled again; automatic refund/cancel handling will not re-enable it. `200 { orderId, accessEnabled, accessReason, accessChangedAt }`. Errors: 400, 404.

### `GET /docs`
This document (Markdown). No authentication.
