How to use Avand's file service from your own application's back end: object storage, CDN
delivery, on-the-fly image transforms and video streaming, driven by the Avand HTTP API. Every
example is copy-pasteable curl, and section 13 has the same journey in Node and C#.
Interactive reference: /scalar/ on a running instance. Machine-readable contract: served live at
/openapi/v1.json (https://avandapi.shokoofa.ai/openapi/v1.json for the suite, in-network
http://bee-api:8080/openapi/v1.json), and committed as
docs/openapi/avand-v1.json, the same contract (regenerated, never hand-edited).
Contents
- What Avand is, and the four planes
- Accounts, roles and permissions
- Sessions or API keys: which credential to use
- API keys
- Sessions: sign in and refresh
- Conventions that hold everywhere
- Storage zones and zone access keys
- The storage data plane: upload, download, list, delete
- Resumable uploads
- CDN: pull zones, cache, purge, edge rules, signed URLs
- Images and video
- Administration, the audit log and analytics
- End to end: upload a file and get its CDN URL, in Node and C#
- Troubleshooting
- Quick reference
1. What Avand is, and the four planes
Avand is the web app; Avand is the API behind it. Everything you can do in Avand you can do against Avand directly, and that is what this guide is about.
| How Avand is running | Base URL |
|---|---|
docker compose up | http://localhost:20331 (published port is AVAND_API_HOST_PORT) |
dotnet run directly | http://localhost:20331 |
| A deployment | The origin Avand names as PUBLIC_AVAND_ORIGIN (https://avandapi.shokoofa.ai for the suite) |
| The suite's deployment, from another back end on the server | http://bee-api:8080 over the Docker network shokoofa-shared-net |
A back end on the suite's server calls Avand and Keycloak in-network, never through the public
hosts: those are behind Cloudflare, which answers server clients' default User-Agents with an HTML
403 (never Avand's) and limits a request to about 100 MB and about 100 s. The rules are in
integrating-apps.md §1.5.
The examples use a shell variable so they work anywhere:
AVAND=http://localhost:20331
Avand's endpoints split into four planes with different authentication. Knowing which plane you are on answers most "why am I getting a 401?" questions.
| Plane | Paths | Credential | Purpose |
|---|---|---|---|
| Control | /api/v1/** | Access token from the Central IdP: traded from an API key, or a session's | Create and configure everything |
| Storage data | /storage/{zone}/** | Zone access key | Upload, download, list and delete raw objects |
| Upload sessions | /upload/sessions/** | The same access token | Resumable uploads |
| Delivery | /cdn/**, /img/** | None | Serve content to end users |
The delivery plane has no auth header at all: access is governed by each pull zone's own security settings (signed URLs, referrer, IP and country rules).
2. Accounts, roles and permissions
There is no account creation, password or sign-in in Avand: people sign in through the central
Keycloak (realm identity-service), and the first request carrying their token creates the local
account, keyed by the token's sub, and its personal space. Roles are assigned in the Central IdP,
not here.
Avand authorises on permissions, which it computes from the person's roles: their current
realm roles, read from Keycloak and cached for at most a minute. The roles and what each grants are
one table, Avand's role catalog, in API_GUIDE §1 › Roles and permissions:
avand.viewer, avand.member, avand.operator and avand.admin for everyday use and
administration, platform.* roles for deployment-wide work and legal holds. Roles are assigned in
the account center, not here. A person with no entitlement is own-space-only: they can list,
read, download and delete in zones they own, see /api/v1/me/space and /api/v1/auth/me, and use
account self-service; upload, share, link and access-list changes answer
403 access.own_space_read_only, and every other surface 403 access.no_app_access.
Permissions are a hierarchy, not a flat set. Each operation's documentation names the permission it needs, and higher ones satisfy lower ones:
| Operation needs | Satisfied by |
|---|---|
bee:read | bee:read, bee:write, bee:admin |
bee:write | bee:write, bee:admin |
bee:purge | bee:purge, bee:write, bee:admin |
bee:stream | bee:stream, bee:write, bee:admin |
bee:admin | bee:admin |
bee:platform | bee:platform only |
bee:legal-hold | bee:legal-hold only |
So a role that grants bee:write can read without naming bee:read: bee:write implies it.
3. Sessions or API keys: which credential to use
People use sessions. API keys are only for administrators and for system callers (jobs that
are not a person). A person has no key of their own on Avand. The credentials that reach the
control plane end in an access token from the Central IdP, or, for a system key, in the key itself,
sent as Authorization: Bearer; Avand issues no token of its own.
| Session token | Admin API key (shk_…) | |
|---|---|---|
| Obtained by | the Central IdP, through Avand's web app (which keeps it on its server) | The account center → API keys, for the app avand, once; only a person who currently holds avand.admin may use it |
| Sent as | Authorization: Bearer <token> | Traded at the IdP's token endpoint for an access token, sent as Authorization: Bearer <token> |
| Lives for | The IdP's access-token lifetime; the web app refreshes it with Keycloak | The key: until revoked, expired, or idle for 90 days. Each traded token: 5 minutes |
| Carries | All the account's permissions | The permissions you chose (bee:read, bee:write, bee:purge, bee:stream, and bee:admin), narrowed to what the administrator holds now |
| Revocable | Not by Avand: an access token is valid until it expires. Ending a session is Keycloak's job | Yes, in the account center: the next trade fails, a token already traded lives out its 5 minutes |
| Session-only operations (system accounts and keys, profile, export) | Yes | No |
| Meant for | People, and the Avand app itself | An administrator's own scripts |
A system key (avand_ak_…, §4) is the third credential: it belongs to a system account, is sent
to Avand directly, always expires, and can never act for a person.
Use a key for anything unattended. A back end has no business holding a person's session:
it carries everything the account can do and Avand cannot revoke it. A key holds only what you gave
it and each admin-key token it yields lives five minutes. An app that acts for a signed-in person
does not use a key at all: it exchanges the person's token (docs/integrating-apps.md). The
samples in this guide send $AVAND_TOKEN: an access token traded from an admin key or, for the
operations that need a signed-in person (zone keys, system accounts, the audit log), an
administrator's session token.
4. API keys
Admin keys
Administrators' API keys for Avand are issued, stored and verified by the Central IdP. Only a person who currently holds avand.admin may use one: once they lose it, the
key's token answers 403 access.api_keys_admin_only on every route.
- Create one in the account center for the app avand, ticking only the permissions it
needs:
bee:read,bee:write,bee:purge,bee:stream, andbee:adminfor administration. The key (shk_…) is shown once; copy it into your secret store. - Trade it at the IdP's token endpoint for an access token:
AVAND_TOKEN=$(curl -s \
-d grant_type=urn:shokoofa:params:oauth:grant-type:api-key \
-d client_id=administration-keys \
-d api_key=$AVAND_API_KEY \
https://auth.shokoofa.ai/realms/identity-service/protocol/openid-connect/token | jq -r .access_token)
The answer holds only an access_token, valid for 5 minutes: trade again when it expires or
on a 401. A refused trade is invalid_grant: the key is revoked, expired, idle for 90 days, or
its person is disabled.
3. Send the token as Authorization: Bearer $AVAND_TOKEN, exactly like a session token. Every
sample in this guide does.
The token carries the key's permissions intersected with the administrator's current ones,
recomputed on every request, so a demotion narrows the key within a minute. It never counts as an
interactive session: managing system accounts and keys, the profile and the export answer 403;
it is exempt from step-up. GET /api/v1/auth/me reports "authMethod": "apiKey", and the audit
trail names it via = api-key:<key_id>. Details: API_GUIDE §1 › Admin keys.
System accounts and system keys (avand_ak_)
A system account owns the files of a job or script that has no sign-in: a log shipper, UI
graphics, generated content. It is never a person, and nothing it does can be attributed to one.
An administrator manages system accounts and their keys in an interactive session (they need
bee:admin), in the dashboard or with the API below. An account is disabled and enabled, never
deleted in this release; disabling stops every one of its keys at once and keeps its data.
Create a system account
curl -s -X POST $AVAND/api/v1/system-accounts \
-H "Authorization: Bearer $SESSION_TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: create-media-service" \
-d '{"name":"media-service","purpose":"Generated thumbnails","quotaBytes":10737418240}'
{
"id": "0198c0de-…",
"name": "media-service",
"purpose": "Generated thumbnails",
"quotaBytes": 10737418240,
"defaultZoneId": "0198c0df-…",
"createdAt": "2026-10-06T12:00:00+00:00",
"disabledAt": null
}
The name is unique (409 bee.system_account_name_taken) and made of lowercase letters, digits and
hyphens (400 bee.system_account_name_invalid). quotaBytes is the allowance; null means
unlimited, and must be said explicitly. The account gets a private zone s- followed by its id
without hyphens, and may create more with a bee:write key. Also GET /api/v1/system-accounts,
GET /api/v1/system-accounts/{id}, POST …/disable, POST …/enable and
PUT …/quota with {"quotaBytes": …}.
Mint a key
curl -s -X POST $AVAND/api/v1/system-accounts/$ACCOUNT_ID/keys \
-H "Authorization: Bearer $SESSION_TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: mint-media-service-key-1" \
-d '{"name":"thumbnailer","permissions":["bee:write"],"expiresAt":"2027-08-24T00:00:00Z"}'
{
"id": "0198c0de-…",
"name": "thumbnailer",
"keyPrefix": "avand_ak_0198c0de…",
"permissions": ["bee:write"],
"zoneIds": [],
"plaintextKey": "avand_ak_0198c0de00007000800000000000abcd_Kj3…43 characters…",
"createdAt": "2026-10-06T12:00:00+00:00",
"expiresAt": "2027-08-24T00:00:00+00:00"
}
The key is shown once; Avand stores only a hash. expiresAt is required
(400 bee.api_key_expiry_required) and at most 365 days ahead (400 bee.api_key_expiry_too_far;
the limit is AvandApiKeys:MaxLifetime). permissions are some of bee:read, bee:write,
bee:purge, bee:stream, never admin. A disabled account cannot be issued keys
(409 bee.system_account_disabled).
The format
avand_ak_<32 hex characters: the key id>_<43 characters: the secret>
The id is inside the plaintext, so Avand looks the key up directly and compares one hash. The
part before the last _ is the keyPrefix Avand lists, which is how you match a key you find
in a config file to its row. Secret scanners can match a leaked key with
avand_(ak|zk)_[0-9a-f]{32}_[A-Za-z0-9_-]{43}.
Send it
Either of these works on every route a system key may reach, wherever the documentation says
"bearer token or API key" ($AVAND_API_KEY holding the avand_ak_ key):
# Standard: the same header a session token uses
curl -s "$AVAND/api/v1/files?storageZoneId=$ZONE_ID" -H "Authorization: Bearer $AVAND_API_KEY"
# bunny.net-style alias, for code written against bunny's APIs
curl -s "$AVAND/api/v1/files?storageZoneId=$ZONE_ID" -H "AccessKey: $AVAND_API_KEY"
The interactive reference at /scalar/ accepts the key in its bearer field as-is.
What a key can and cannot do
- It authenticates as the system account, never as a person, and cannot act for one. It carries the permissions it was minted with, and works only on the account's own zones.
- It may be limited to some of the account's zones with
zoneIds. A zone-limited key is fail-closed: it works only on zone-aware requests on those zones (the files API, storage-zone object and upload routes, upload sessions,/api/v1/me/space,/api/v1/auth/meand the storage-zone list filtered to its zones). Everything else (pull zones, video, webhooks, saved transforms, file keys, zone administration) answers403 bee.api_key_zone_not_owned. - It is refused, with the same
401as a wrong key, after it is revoked, afterexpiresAtand while its account is disabled. Which of those applied is logged server-side and never told to the caller. - It cannot manage system accounts or keys, change the profile or download an export. Those
answer
403to a key. - On the delivery plane a key with
bee:readwhose account owns the zone stands in for a signed URL. GET /api/v1/auth/mereports"authMethod": "apiKey"and the key's effective permissions.- An account holds at most 25 active keys.
Rotate, revoke, audit
# A new secret under the same name, permissions and expiry. The old one dies in the same write.
curl -s -X POST $AVAND/api/v1/system-accounts/$ACCOUNT_ID/keys/$KEY_ID/rotate -H "Authorization: Bearer $SESSION_TOKEN"
# Dead on the next request. Irreversible.
curl -s -X DELETE $AVAND/api/v1/system-accounts/$ACCOUNT_ID/keys/$KEY_ID -H "Authorization: Bearer $SESSION_TOKEN"
# Everything the account has had, active first. Never the secret.
curl -s $AVAND/api/v1/system-accounts/$ACCOUNT_ID/keys -H "Authorization: Bearer $SESSION_TOKEN"
Rotation has no overlap window: a system key is one process's configuration, so deploy the new
secret right away. Every create, rotate and revoke is written to the audit log (section 12), and
so is every use of a key: one apiKey.use row with via = api-key:<id>, the route template (or
(unmatched)) and the status. Throttled (429) uses are summarised at most once a minute per key
and route, with suppressed429=N. Administrators see system-account entries in the audit log.
Keep it secret
Treat either kind of key like a password: an environment variable or a secret manager, never
source control, never a client-side bundle, never a log line. If it leaks, revoke it: an
admin key in the account center (the next trade fails), a system key in Avand (the next request
with it gets 401).
5. Sessions: sign in and refresh
Avand's web app signs you in through the Central IdP and keeps the token on its server; Avand itself
has no sign-in, refresh or password endpoints. A script obtains a token from Keycloak (for a
person, through the app it works for; for a service, with client credentials) and sends it as
Authorization: Bearer <token>. Refreshing, and ending sessions, is Keycloak's business. Avand
validates a token offline for its whole lifetime and cannot revoke it; once it expires the answer is
401 invalid_token, and the cure is a fresh token, never a retry.
6. Conventions that hold everywhere
- Creates return
201with aLocationheader and{"id":"<guid>"}, not the resource. Fetch it separately if you need it. Updates and deletes return204with no body. - Errors are RFC 9457 problem documents (
application/problem+json) withtype,title,status,detail, atraceIdyou can quote when reporting a bug, and a stable dottedcode(bee.storage_zone_not_found) to branch on and translate;titleanddetailare an English developer gloss. Validation failures adderrors, every failure as{ code, field, params? }:[{"code":"validation.required","field":"name"}]. The API guide lists every code. SendAccept-Language: faorenwith each call. Exception: the delivery plane (/cdn/**,/img/**) returns bare status codes with no body, because its consumers are<img>tags and video players; only its429is a problem document, like every other429. - Lists are cursor-paginated, oldest first. Pass
limit(default 50, clamped to 1..200) and thenextCursorfrom the previous page. Stop whenhasMoreisfalse. Cursors are opaque; never build or parse one. A page with more behind it also carries aLink: <…>; rel="next"header you can follow instead of assembling the next request. - Idempotency: endpoints that say so accept an
Idempotency-Keyheader (any string up to 128 characters). Replaying the same key returns the original response without redoing the work; a replay while the first request is still running returns409; reusing a key for a different request returns422instead of replaying something you did not send. A key is honoured for 24 hours, then it is a fresh key. Use one key per user intent and reuse it across network retries. - Enums are camelCase strings (
"ignoreAll"), timestamps are RFC 3339 UTC, ids are UUIDs, and any field ending inBytes,Seconds,KbpsorPercentis in that unit. - Zones and libraries are versioned. Reading a pull zone, storage zone or video library returns an
ETag. Send it back asIf-Matchwhen you change the zone and the write is refused with412if someone else changed it first, so nobody's edit is silently lost; send it asIf-None-Matchto re-read without a body when nothing changed (304). Optional unless your operator requires it (428). - Every response carries
X-Bee-Request-Id, on every plane, including a304, a redirect or a429. It is the same value a problem document'straceIdholds. Quote it when reporting a problem; it links the response to the server-side trace. Avand assigns it and ignores one you send; to link your own trace, send a W3Ctraceparentheader instead. - Responses are compressed on request. Send
Accept-Encoding: brorgzipand text, JSON (problem documents included), playlists and SVG come back compressed withVary: Accept-Encoding. Byte ranges (206), images, video segments and credential responses (issuing an API key, a zone key or a webhook secret, and the account export) are always identity. HTTP clients decompress transparently; acurlneeds--compressed. - Security headers.
X-Content-Type-Options: nosniffis on everything; the control plane addsX-Frame-Options: DENY,Referrer-Policy: no-referrerand aContent-Security-Policy. The delivery, image, storage and upload planes carry none of the latter three, so Avand-hosted media stays embeddable in your pages.
7. Storage zones and zone access keys
Create a zone
curl -s -X POST $AVAND/api/v1/storage-zones \
-H "Authorization: Bearer $AVAND_TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: create-assets-zone-1" \
-d '{
"name": "my-assets",
"primaryRegion": "eu",
"tier": "standard",
"quotaBytes": 10737418240,
"replicationRegions": []
}'
# 201 → {"id":"<storageZoneId>"}
tier is standard or performance. Region codes are short lowercase strings (2–8 characters,
for example eu, us, apac). Provisioning is asynchronous: poll the zone until state is
ready. quotaBytes: 0 means no quota, and an account's own storage allowance applies on top.
A browser reading the zone directly needs CORS. By default the deployment-wide
AvandCors:AllowedOrigins list applies; a zone can carry its own instead:
curl -s -X PATCH $AVAND/api/v1/storage-zones/$ZONE_ID \
-H "Authorization: Bearer $AVAND_TOKEN" \
-H "Content-Type: application/merge-patch+json" \
-d '{ "cors": { "enabled": true, "allowedOrigins": ["https://app.example.com"], "allowedExtensions": [] } }'
When enabled, the zone's origins replace the deployment-wide list for /storage/my-assets/…
(preflight included); allowedExtensions limits which objects get CORS headers at all (empty
means every object). The policy reads back on the zone.
The same PATCH changes name, quotaBytes and replicationRegions. Replication regions are
sent as the desired full set: regions missing from it are removed, new ones added, [] stops
replication, and the primary region may not be listed. The tier cannot be changed after creation.
Issue a zone access key
The data plane authenticates with a key scoped to one zone, not with your account credential.
Issuing one needs bee:admin, which an IdP-issued key never carries: issue it from Avand, or with
an administrator's session token.
curl -s -X POST $AVAND/api/v1/storage-zones/$ZONE_ID/keys \
-H "Authorization: Bearer $AVAND_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name":"backup-script","scope":"readOnly"}'
{
"id": "…",
"name": "backup-script",
"scope": "readOnly",
"keyPrefix": "avand_zk_…",
"plaintextKey": "avand_zk_<32 hex>_<43 characters>",
"issuedAt": "…"
}
Both name and scope are required: the name tells rotated keys apart, and an omitted scope is
refused rather than defaulted to read-write. plaintextKey is shown exactly once. Prefer
readOnly wherever downloads are all you need; a key is a bearer secret for the whole zone.
Rotate with POST .../keys/{id}/rotate (the old key stops working immediately) and revoke with
DELETE .../keys/{id}. Issue, rotate and revoke are audited.
A key issued before keys carried their id has no keyPrefix and keeps working unchanged.
8. The storage data plane: upload, download, list, delete
Send the zone key as X-Bee-Access-Key, or as AccessKey if your code was written against
bunny.net's storage API. A request without a valid key gets 401 with
WWW-Authenticate: AccessKey realm="bee-storage". Requests are rate limited per key (4 000
requests of burst, refilling at 2 000 per second) and, across every key, per zone (20 000 burst,
10 000 per second); the excess gets 429 naming the budget that fired.
Upload
Raw bytes in the body, not multipart. The path after the zone name may contain /. Leave
Content-Type out and the object gets the type its extension implies (.jpg → image/jpeg),
falling back to application/octet-stream:
curl -s -X PUT "$AVAND/storage/my-assets/photos/111.jpg" \
-H "X-Bee-Access-Key: $ZONE_KEY" \
-H "Content-Type: image/jpeg" \
--data-binary @111.jpg
# 201 with a Location header and the stored object's metadata
Optionally send the expected SHA-256 so Avand verifies what it stored: as RFC 9530
Content-Digest: sha-256=:<base64>:, as bunny.net's Checksum header (hex, either case), or as
hex in X-Bee-Content-Sha256. A mismatch rejects the upload (422) instead of storing corrupt
bytes; an algorithm Avand cannot compute, a malformed digest, or headers that disagree are refused
with 400 before the body is read. Every successful upload answers with
Repr-Digest: sha-256=:<base64>: of the stored bytes. Over the account's allowance is 507; over
the request size limit is 413. Needs a readWrite key.
The first upload to a path answers 201; overwriting an existing object answers 200. Both
return the object's metadata (created says which) and its ETag. Send that tag as If-Match
on a later PUT or DELETE and the write is refused with 412 if someone changed the object
first; If-None-Match: * makes a PUT create-only (412 when the path already holds an
object); If-Unmodified-Since does the same by date. A 412 writes nothing.
Names are normalised to Unicode NFC (both spellings of an accented character are one object);
a segment may not start or end with whitespace, be . or .., contain control
characters, or exceed 255 bytes of UTF-8, and an encoded slash (%2F) is refused with 400
rather than treated as a separator.
Download
curl -s "$AVAND/storage/my-assets/photos/111.jpg" -H "X-Bee-Access-Key: $ZONE_KEY" -o 111.jpg
Range is honoured (206, Content-Range, 416 past the end), If-None-Match (strong or
weak, a list, or *) and If-Modified-Since answer 304 with ETag and Last-Modified,
Accept-Ranges: bytes is always sent, and every object response carries
Repr-Digest: sha-256=:<base64>: (RFC 9530) unless Want-Repr-Digest: sha-256=0 declines it.
Add ?download to get Content-Disposition: attachment named after the object, or
?response-content-disposition=inline / attachment; filename="x" to set it yourself. HEAD returns the same status and headers
(Content-Length, ETag, Last-Modified, Content-Type) with no body. Works with a readOnly key.
List
A path ending in /, or the zone root, lists instead of downloading. It is the same
directory view the control plane serves, reachable with the zone key alone, so a script that
uploads can see what it uploaded without an account credential:
# The zone root
curl -s "$AVAND/storage/my-assets/" -H "X-Bee-Access-Key: $ZONE_KEY"
# One level down, paged
curl -s "$AVAND/storage/my-assets/photos/?limit=50" -H "X-Bee-Access-Key: $ZONE_KEY"
{
"items": [
{ "path": "photos/2026/", "name": "2026", "isDirectory": true, "object": null },
{ "path": "photos/111.jpg", "name": "111.jpg", "isDirectory": false, "object": { "sizeInBytes": 48213, "contentType": "image/jpeg", "…": "…" } }
],
"nextCursor": null,
"hasMore": false
}
Each object carries sizeInBytes, contentType, contentHash (SHA-256, lower-case hex),
checksum (the same SHA-256 in the upper-case hex bunny.net lists), eTag, lastModifiedAt,
createdAt and storageZoneName. Folders are inferred from / in object paths and carry no
object; recurse by requesting the folder's path. Page with cursor until hasMore is false. The control-plane form,
GET /api/v1/storage-zones/{id}/objects?prefix=photos/, returns the same shape with an account
credential.
Delete
# One object
curl -s -X DELETE "$AVAND/storage/my-assets/photos/111.jpg" -H "X-Bee-Access-Key: $ZONE_KEY"
# Everything under a prefix, recursively
curl -s -X DELETE "$AVAND/storage/my-assets/photos/" -H "X-Bee-Access-Key: $ZONE_KEY"
The trailing slash is the whole contract. Both return 204, so a stray slash deletes far
more than intended with no distinguishable response. Deletion is permanent. If-Match and
If-Unmodified-Since guard a single-object delete (412 when the object changed); a prefix
delete ignores them.
9. Resumable uploads
The upload plane speaks tus 1.0.0 (OPTIONS $AVAND/upload/sessions lists the extensions:
creation, creation-with-upload, creation-defer-length, expiration, checksum, termination), so any
tus client works; the examples use curl. Open a session, PATCH chunks at the offset the server
reports, and the chunk that reaches the declared length finalises the upload. A dropped connection
loses only the current chunk. Sessions expire 24 hours after creation (Upload-Expires on every
response). Every response carries Tus-Resumable: 1.0.0; a request naming another version is
refused with 412 and Tus-Version. All calls take an account credential.
# 0. Discover the protocol (no credential needed)
curl -s -i -X OPTIONS $AVAND/upload/sessions
# Tus-Version: 1.0.0, Tus-Extension: creation,creation-with-upload,creation-defer-length,expiration,checksum,termination
# Tus-Max-Size: <bytes>, Tus-Checksum-Algorithm: sha256
# 1. Open a session, tus style: Upload-Length plus base64 Upload-Metadata naming the target
# (storageZoneId + path or filename, optional filetype and contentSha256;
# for a video source: videoLibraryId + videoId)
ZONE_B64=$(printf '%s' "<storageZoneId>" | base64 -w0)
PATH_B64=$(printf '%s' "backups/big.zip" | base64 -w0)
TYPE_B64=$(printf '%s' "application/zip" | base64 -w0)
curl -s -i -X POST $AVAND/upload/sessions \
-H "Authorization: Bearer $AVAND_TOKEN" \
-H "Tus-Resumable: 1.0.0" \
-H "Upload-Length: 104857600" \
-H "Upload-Metadata: storageZoneId $ZONE_B64,path $PATH_B64,filetype $TYPE_B64"
# 201 + Location: /upload/sessions/<sessionId>, Upload-Offset: 0, Upload-Expires: <HTTP date>
# Upload-Defer-Length: 1 instead of Upload-Length opens a session of unknown size (send
# Upload-Length once, on a later PATCH); a body of application/offset+octet-stream on the
# POST is taken as the first chunk.
# 1b. The JSON body Avand accepted before tus still works
curl -s -i -X POST $AVAND/upload/sessions \
-H "Authorization: Bearer $AVAND_TOKEN" \
-H "Content-Type: application/json" \
-d '{"storageZoneId":"<storageZoneId>","path":"backups/big.zip","totalLength":104857600,"contentType":"application/zip"}'
# 2. Send chunks at the current offset; Upload-Checksum has each one verified as it streams
curl -s -i -X PATCH $AVAND/upload/sessions/$SESSION \
-H "Authorization: Bearer $AVAND_TOKEN" \
-H "Tus-Resumable: 1.0.0" \
-H "Upload-Offset: 0" \
-H "Upload-Checksum: sha256 $(openssl dgst -sha256 -binary chunk-0 | base64 -w0)" \
-H "Content-Type: application/offset+octet-stream" \
--data-binary @chunk-0
# 204 + the new Upload-Offset; a mismatched checksum is 460 and the offset does not move
# 3. After an interruption, ask where to resume
curl -s -I $AVAND/upload/sessions/$SESSION -H "Authorization: Bearer $AVAND_TOKEN" -H "Tus-Resumable: 1.0.0"
# Upload-Offset: <bytes received so far>, Upload-Length (or Upload-Defer-Length: 1), Upload-Metadata
# 4. The chunk that brings Upload-Offset to Upload-Length finalises the upload: the object (or
# the video source) exists when that PATCH answers 204. DELETE cancels and discards the bytes.
# POST .../complete is deprecated; it still answers 204 for a finished session.
10. CDN: pull zones, cache, purge, edge rules, signed URLs
Put a pull zone in front of a storage zone
curl -s -X POST $AVAND/api/v1/pull-zones \
-H "Authorization: Bearer $AVAND_TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: create-assets-cdn-1" \
-d '{
"name": "my-assets-cdn",
"originType": "storageZone",
"originStorageZoneId": "<storageZoneId>"
}'
originType decides the required companion field: http needs originUrl; storageZone and
videoLibrary both send the backing id in originStorageZoneId. Provisioning is asynchronous;
poll the zone until state is ready. Then anyone can fetch, with no auth header:
curl -s "$AVAND/cdn/my-assets-cdn/photos/111.jpg" -o photo.jpg
# X-Bee-Cache: MISS | HIT | STALE | BYPASS | REVALIDATED
# Cache-Status: bee;fwd=uri-miss;fwd-status=200;ttl=3600;stored (RFC 9211; a hit is `bee;hit;ttl=3599`)
# Server-Timing: cache;desc=MISS, origin;dur=41.2, edge;dur=43.0
# Proxy-Status: bee;error=connection_refused;details="..." (only on a 502/503/504/508)
# ETag / Last-Modified: validators. If-None-Match or If-Modified-Since -> 304; If-Range guards a Range
Cache policy
curl -s -X PUT $AVAND/api/v1/pull-zones/$PZ/cache \
-H "Authorization: Bearer $AVAND_TOKEN" -H "Content-Type: application/json" \
-d '{
"edgeTtlSeconds": 3600,
"browserTtlSeconds": 300,
"respectOriginCacheControl": true,
"queryStringMode": "ignoreAll",
"queryStringParameters": [],
"vary": "none",
"cacheErrorResponses": false,
"enableRequestCoalescing": true,
"staleWhileRevalidateSeconds": 60,
"staleIfErrorSeconds": 300
}'
# The same settings, sparsely: PATCH applies only the members you send
curl -s -X PATCH $AVAND/api/v1/pull-zones/$PZ/cache \
-H "Authorization: Bearer $AVAND_TOKEN" -H "Content-Type: application/merge-patch+json" \
-d '{"edgeTtlSeconds": 7200}'
PATCH …/cache and PATCH …/security take the same members as the PUTs, every one optional;
an empty array clears a list and 0 lifts a rate limit. queryStringMode is includeAll, ignoreAll or includeListed (with
queryStringParameters naming the list). vary is a comma-separated string of dimensions
("cookie, acceptEncoding", or "none"). acceptEncoding is accepted for compatibility and
does nothing: Avand compresses on the way out, so the cache is never split by encoding.
browserTtlSeconds is what a client's own cache is told: every cacheable response carries
Cache-Control: public, max-age=<browserTtlSeconds> (plus immutable when the origin said so).
With respectOriginCacheControl on, an origin's private, no-cache or no-store is relayed
instead; a denied request or an error the edge did not cache is always no-store.
The last three fields are optional and additive. staleWhileRevalidateSeconds (RFC 5861) is how
long past the edge TTL an expired entry is still served immediately (X-Bee-Cache: STALE) while
a fresh copy is fetched in the background; staleIfErrorSeconds is how long it is served when the
origin cannot be reached or answers 5xx. Past both windows the edge revalidates in line with its
own validators, and an unchanged body costs a 304 (X-Bee-Cache: REVALIDATED).
enableRequestCoalescing collapses a burst of misses on one key into a single origin fetch; the
others wait briefly for it and report Cache-Status: bee;hit;…;collapsed.
Origin Vary. With respectOriginCacheControl on, an origin's Vary splits the edge cache
per value of Accept, Accept-Language and Origin, and the response repeats that Vary to
the client. Accept-Encoding is ignored (the edge compresses on the way out). Vary: * or any
other header the edge cannot key on makes the response uncacheable rather than cached wrongly.
Purge
# One URL, a prefix, or the whole zone
curl -s -X POST $AVAND/api/v1/pull-zones/$PZ/purge \
-H "Authorization: Bearer $AVAND_TOKEN" -H "Content-Type: application/json" \
-d '{"scope":"prefix","target":"photos/"}'
# Everything the origin tagged (Cache-Tag / CDN-Tag / Cache-Groups) with one surrogate key
curl -s -X POST $AVAND/api/v1/pull-zones/$PZ/purge \
-H "Authorization: Bearer $AVAND_TOKEN" -H "Content-Type: application/json" \
-d '{"scope":"tag","target":"product-42"}'
Budgets are per zone: exact url purges 120 burst and 300 a minute, prefix/tag/zone
purges 20 burst and 30 a minute; the excess is a 429 with Retry-After and
RateLimit-Policy: "bee-purge-broad";q=30;w=60.
Needs bee:purge. Purging is asynchronous and propagates across replicas; edges may serve the
old copy briefly.
Custom hostnames
Every zone is born with one system hostname under Avand's delivery domain, so it serves immediately. Attach your own with:
curl -s -X POST $AVAND/api/v1/pull-zones/$PZ/hostnames \
-H "Authorization: Bearer $AVAND_TOKEN" -H "Content-Type: application/json" \
-d '{"hostname":"cdn.example.com"}'
Each hostname carries its own forceHttps (on for a new one): a plain-HTTP request arriving on
it is redirected with 308 when the deployment can answer on HTTPS, whatever the zone's own
flag says. Turn it off with PATCH …/hostnames/cdn.example.com and {"forceHttps": false};
the current values read back as hostnameSettings on the zone.
Getting a certificate for it. Once cdn.example.com points at Avand, an ACME client on your
origin (certbot, acme.sh, Caddy) can still pass an HTTP-01 validation for that name:
/.well-known/acme-challenge/<token> on every pull zone is handed to the origin exactly as
received, skipping the cache, edge rules, access policy and signed URLs. Zones whose origin is a
storage zone or a video library have no server to ask, so they answer 404 there; use DNS-01 for
those names.
Edge rules
Rules run in order per request; a block or redirect ends evaluation. Actions: forceHttps,
redirect, block, setRequestHeader, setResponseHeader, overrideCacheTime,
overrideOrigin, bypassCache, disableTokenAuthentication, enableTokenAuthentication.
Triggers match on url, requestHeader, responseHeader, fileExtension, countryCode,
remoteIp, queryString, httpMethod or hostname.
# Block hotlinking of zip files: create (edgeRuleId: null) or replace (edgeRuleId set)
curl -s -X PUT $AVAND/api/v1/pull-zones/$PZ/edge-rules \
-H "Authorization: Bearer $AVAND_TOKEN" -H "Content-Type: application/json" \
-d '{
"edgeRuleId": null,
"description": "No zip downloads",
"actionKind": "block",
"actionParameter1": null, "actionParameter2": null, "actionParameter3": null,
"triggerMatchMode": "all",
"triggers": [
{ "kind": "fileExtension", "matchMode": "any", "patterns": ["zip"], "parameter": null }
]
}'
Reorder with PUT .../edge-rules/order, toggle with PATCH .../edge-rules/{id}
({"isEnabled":false}), remove with DELETE.
What the actions do on the wire: setRequestHeader reaches the origin, setResponseHeader is
written after every header the edge sets itself, and both refuse hop-by-hop and framing headers,
Host, and the edge's own CDN-Loop, Via, Forwarded and X-Forwarded-* (a 400 when the
rule is saved). forceDownload answers with Content-Disposition: attachment (RFC 6266/8187),
naming the file from actionParameter1 or the last path segment. redirect accepts 301, 302,
307 or 308. forceHttps answers 308 to the same URL over HTTPS; the zone's own forceHttps
security flag does the same only when the deployment can serve HTTPS (a TLS endpoint,
AvandHost:EnforceHttps, or a trusted proxy is configured), so a plain-HTTP deployment never
redirects into a loop. A rule with a responseHeader trigger runs after the origin (or the cache)
answers and may only set a response header, override the cache time, bypass the cache or force a
download. Each trigger's own matchMode combines its patterns.
Signed URLs
Require tokens on a zone (PUT .../security with "signedUrlsRequired": true), then mint
URLs server-side:
curl -s -X POST $AVAND/api/v1/signed-urls \
-H "Authorization: Bearer $AVAND_TOKEN" -H "Content-Type: application/json" \
-d '{
"pullZoneId": "<pullZoneId>",
"path": "photos/111.jpg",
"expiresAt": "2026-08-14T00:00:00+00:00",
"isPrefixToken": false,
"clientIpAddress": null,
"allowedCountryCodes": [],
"blockedCountryCodes": [],
"maxBytesPerSecond": null
}'
# → { "url": "https://<zone-hostname>/photos/111.jpg?expires=1786665600&token=...", "expiresAt": "..." }
The URL is minted on the zone's custom hostname when it has one, otherwise on the deployment's
public delivery origin (PUBLIC_AVAND_ORIGIN) as {origin}/cdn/<zoneName>/<path>, the same form
as every other delivery URL, so it works without DNS for the system hostname. maxBytesPerSecond
is bytes (1000 is 1 KB/s). The token signs the path (or the prefix, with
isPrefixToken, which HLS playback needs), so the path must be used as returned. Of the query
string only expires and the restriction parameters it carries (ca, cb, rt, and bi for an
object URL) are signed, so changing one of them invalidates the URL while adding an unrelated
parameter does not; a signed URL's own
parameters (token, expires, ca, cb, rt) can be copied onto sibling paths under a prefix
token. Rotate the zone's
signing key with POST .../signing-key/rotate; existing URLs die immediately.
To hand one private file to someone without an account for days rather than minutes, make a
share link instead: POST /api/v1/files/{zoneId}/links answers a token once, anyone holding it
gets a fresh 15-minute download URL from POST /api/v1/links/{token}/download-url until the link
expires (30 days at most by default) or you revoke it. See API_GUIDE.md §2b.
Tokens are HS256-<base64url>; a prefix token also carries token_path=<prefix>, which the
edge honours for any path under it. A prefix token covers one folder: a path ending in / covers
that folder (photos/2026/), any other path covers its parent ({videoId}/playlist.m3u8 covers
{videoId}/), and a path with no folder of its own (a bare top-level name such as u123, the root,
. or x/..) would cover the whole zone and is refused with 400 bee.signed_url_prefix_too_broad.
The edge accepts the same parameters under their Bunny
names (bcdn_token, token_countries, token_countries_blocked, limit in kB/s,
token_ignore_params) and the directory form /bcdn_token=…&expires=…&token_path=…/path, so a
player written for that scheme needs no changes. An IP-bound token covers the client's whole
IPv6 /64. maxBytesPerSecond (rt) is enforced: the body is paced to it.
Referrer, IP and country rules
PUT /api/v1/pull-zones/{id}/security replaces the whole security configuration:
signedUrlsRequired, forceHttps, blockRootPathAccess, allowedReferrers,
blockedReferrers, blockedIpAddresses, allowedCountryCodes, blockedCountryCodes, and the
optional allowedIpAddresses, rateLimitRequestsPerSecondPerIp, rateLimitBurstSize and
rateLimitBytesPerSecondPerConnection. IP entries are single addresses or CIDR networks
(203.0.113.0/24, 2001:db8::/32); a non-empty allow-list refuses everyone else, and a block entry
wins. The request budget is per client address and answers 429 with Retry-After and
RateLimit-Policy: "bee-zone";q=<rate>;w=1; the byte rate paces every response body. All of it is
enforced at the edge; a blocked request is a bare 403.
11. Images and video
Image transforms
Transforms happen only on the /img/ plane. Take the image's /cdn/ delivery URL, ask Avand
to build the transform URL, and use what comes back:
curl -s -X POST $AVAND/api/v1/images/url \
-H "Authorization: Bearer $AVAND_TOKEN" -H "Content-Type: application/json" \
-d '{
"sourceUrl": "'"$AVAND"'/cdn/my-assets-cdn/photos/111.jpg",
"transformation": { "width": 300, "height": 200, "fit": "contain" }
}'
# → "http://localhost:20331/img/my-assets-cdn/photos/111.jpg?width=300&height=200&fit=contain"
The builder canonicalises parameter order, so identical transforms share one cache entry;
prefer it over hand-building URLs. POST /api/v1/images/srcset does the same at several widths
and returns entries ready for an <img srcset>.
| Parameter | Values | Notes |
|---|---|---|
width, height | pixels | Never upscales unless upscale=1 |
fit | contain, cover, fill | Default cover |
aspect_ratio | e.g. 16:9 | Height follows from the width (the source's width when width is absent); height is ignored |
crop | w,h | gravity (alias crop_gravity) picks the region: center, north, southEast, … |
crop_offset | x,y | Explicit top-left corner, read only together with crop; overrides gravity |
format | jpeg, png, webp, avif, gif | Omit to negotiate from Accept: AVIF, then WebP, then the source format (a GIF source stays GIF) |
quality | 1–100 | |
brightness, contrast, saturation, hue, gamma | numbers | Colour adjustments |
blur, sharpen | numbers | |
sepia, flip, flop | 1 | flip is vertical, flop horizontal |
tint | hex colour, e.g. ff8800 | Luminance multiplied by the colour: a monochrome in that hue |
rotate | 90, 180, 270 | Degrees clockwise |
The response carries X-Bee-Image-Size: <width>x<height>.
Leave format out and Avand negotiates it from the request's Accept header (RFC 9110 §12.5.1): a
client that lists image/avif gets AVIF, one that lists image/webp gets WebP, and anyone else
gets the source's own format. These responses carry Vary: Accept. Wildcards such as image/*
do not select a modern format, and a GIF source is never converted by negotiation alone. An
explicit format is used when this host can encode it and allows it
(AvandImaging:AllowedOutputFormats), and otherwise the source's own format is; either way
Accept is not consulted.
A zone whose cache policy has imageClientHints on also reads RFC 8942 client hints:
Sec-CH-DPR scales the requested width by the device pixel ratio (1–4) and Sec-CH-Width
supplies a width when the URL names none. Such responses advertise the hints with Accept-CH
and list the ones used in Vary. The flag is off by default because hinted responses vary on
headers most intermediary caches ignore.
A transformed variant is cached at the edge and served from there afterwards, for at most
AvandImaging:VariantCacheTtl (7 days by default) and never longer than the source stays fresh;
purging the source (by URL, prefix, tag or zone) removes its variants. The response carries the
same headers as /cdn: a strong ETag, the source's Last-Modified and Cache-Control,
Cache-Status (bee;fwd=uri-miss;fwd-status=200;ttl=N;stored on the first request,
bee;hit;ttl=N afterwards), and a 304 for a matching If-None-Match. HEAD returns the
headers alone; Range is ignored because a variant is always delivered whole.
Saving a transformed file
A transform URL does its work on every request. When you want one rendering for good, save it
from the Images page (or POST /api/v1/images/saved): Avand renders it once and writes the result
into the pull zone's origin storage zone as an ordinary object, transforms/{slug}.{ext}, served
at /cdn/{zone}/transforms/{slug}.{ext} with no parameters.
- Give it a name; the slug (the file name) is derived from it unless you choose your own. Slugs
are lower-case letters, digits and single hyphens, unique within the pull zone. Saving under a
slug that is already taken offers to replace that file once you type
replace. - Only a pull zone in front of a storage zone can keep one; an HTTP-origin zone has nowhere to put the file.
- The file shows up in the zone's file browser under
transforms/and counts toward the quota. Delete it from the Images page or from the browser; either way both the file and its record go. - If the source URL you saved from was signed, the saved file inherits that signature's expiry, country lists and rate limit: the page offers a signed URL under the same terms for as long as the original expiry lasts, and a fresh one can be minted at any time.
Video
# A library needs a storage zone to hold sources and renditions
curl -s -X POST $AVAND/api/v1/video-libraries \
-H "Authorization: Bearer $AVAND_TOKEN" -H "Content-Type: application/json" \
-d '{
"name": "tutorials",
"storageZoneId": "<storageZoneId>",
"encodingTier": "standard",
"encodingLadder": ["p360", "p720", "p1080"]
}'
curl -s -X POST $AVAND/api/v1/video-libraries/$LIB/videos \
-H "Authorization: Bearer $AVAND_TOKEN" -H "Content-Type: application/json" \
-d '{"title":"Getting started","videoCollectionId":null}'
# → {"id":"<videoId>"}
# encodingTier: standard = H.264 (plays everywhere); premium = H.265/HEVC, ~1/3 fewer bytes, needs HEVC-capable players
# Upload the source: raw body in one request for small files
curl -s -X PUT $AVAND/api/v1/video-libraries/$LIB/videos/$VID/source \
-H "Authorization: Bearer $AVAND_TOKEN" \
-H "Content-Type: application/octet-stream" \
-H "X-Bee-File-Name: intro.mp4" \
--data-binary @intro.mp4
# 202 Accepted: encoding runs in the background
Large files use an upload session (section 9) with videoLibraryId + videoId, or have Avand
pull it with POST .../videos/{id}/fetch and {"sourceUrl":"https://..."}; Avand downloads it
inside that request, so a source that is unreachable or answers other than 2xx fails the call.
Through the suite's public host, Cloudflare refuses a body over about 100 MB and stops waiting after
about 100 s: send a larger raw PUT as an upload session, and make a long fetch in-network. Poll
GET .../videos/{id}: state goes created → uploading → queued → processing → ready | failed,
encodeProgressPercent advances, and when ready playbackPath is set and isPlayable is true.
Whole-file playback and downloads. Two library settings (PATCH .../video-libraries/{id}):
enableMp4Fallback makes the encoder also write one progressive, faststart MP4 per rung,
served at {videoId}/play_{height}p.mp4 (listed as mp4Path on each rendition and used as
embed.json's downloadPath), for download controls and players without HLS; exposeOriginal
serves the uploaded source at {videoId}/original (off by default, 404 until enabled).
enableMp4Fallback applies to videos encoded after the change (POST .../reencode for older
ones); exposeOriginal is read on every request, so it applies at once.
Player telemetry (CMCD/CMSD). A player that sends CTA-5004 Common Media Client Data (hls.js
and dash.js with CMCD enabled) as the CMCD query parameter or the CMCD-Request/-Object/
-Status/-Session headers is understood: the parameter never affects caching, and the d
(object duration) of each video segment request (ot=v or ot=av) becomes the video's
watchTimeSeconds in its statistics; players that send no CMCD contribute no watch time. Every
rendition and audio response carries CMSD-Static (CTA-5006) stating the object type, format and
bitrate.
From a browser. Your server keeps the credential and mints a grant for the one video; the
browser sends the returned headers instead of a token, on PUT …/source or on every
/upload/sessions call for that video (tus clients: pass them as extra headers). A grant reaches
nothing else, and it is bound to the library's own signing key.
curl -s -X POST $AVAND/api/v1/video-libraries/$LIB/videos/$VID/upload-grant \
-H "Authorization: Bearer $AVAND_TOKEN" -H "Content-Type: application/json" \
-d '{"lifetimeSeconds": 3600}'
# {"signature":"…","expiresAt":"…","headers":{"X-Bee-Upload-Signature":"…","X-Bee-Upload-Expire":"<unix>",
# "X-Bee-Upload-Library":"<libraryId>","X-Bee-Upload-Video":"<videoId>"}}
# The bunny.net names AuthorizationSignature / AuthorizationExpire / LibraryId / VideoId are aliases.
Audio-only files. A library takes a file with no video stream too: MP3, WAV, FLAC, Ogg (Vorbis or Opus), raw AAC, M4A, or any accepted container holding only sound. A picture embedded as cover art doesn't make it a video. It goes through the same endpoints and the same states, and comes out as an item with mediaKind: "audio": no width, height, renditions or storyboard, and its bitrates in audioVariants. It is AAC-LC at up to 64, 128 and 192 kbps over the same CMAF HLS (half that for a mono source), never above the source, so playbackPath, signed and private playback, captions and embed.json work as they do for a video. The poster is the file's cover art, when it has one. With the library's MP4 fallback on, the top bitrate is also a whole file at {videoId}/play_audio.m4a; the original stays available through "expose original", for a lossless master.
What is accepted. Containers MP4/M4V, MOV, MKV, WebM, AVI, FLV, WMV/ASF, MPEG-TS, MPEG-PS/VOB;
video H.264, H.265/HEVC, VP8, VP9, AV1, MPEG-2, ProRes (plus MPEG-4 Part 2, MJPEG, WMV, VC-1 and
Theora when they arrive inside an accepted container); audio AAC, MP3, LPCM, FLAC, ALAC, WMA, Opus,
Vorbis, AC-3. At most 72 hours, 2160p and 60 fps (server-configurable). The check runs the moment the
source is durable, on every path: a refused source answers 422 with problem type
video-source-unsupported and the reason, the bytes are discarded, and the video is back to
created with failureReason set, so a corrected file can be uploaded to the same video. On a host
without ffprobe the check is skipped.
Playback goes through a pull zone whose origin is the library ("originType": "videoLibrary",
"originStorageZoneId": "<videoLibraryId>"). playbackPath ({videoId}/playlist.m3u8) is
relative to that zone's root and is a standard HLS master, with captions as a subtitle group,
{videoId}/thumbnail.jpg, {videoId}/storyboard.vtt for scrubber previews and
{videoId}/embed.json for player metadata. Video delivery responses always carry
Access-Control-Allow-Origin: *, answer a browser's OPTIONS preflight (204 with the allow
headers and Access-Control-Max-Age: 86400) and expose the validators, range, cache and timing
headers to script. The simplest way to play it is Avand's own embeddable player:
copy the embed code from the video's page.
Captions: PUT .../videos/{id}/captions/{lang} with {"label","format":"webVtt","content"} ({lang} is a
well-formed BCP 47 tag such as en or pt-BR; anything else is 422)
replaces the track for that language; DELETE removes it. POST .../reencode re-runs encoding
from the stored source. A published video keeps playing its current version (its isPlayable stays
true) until the new encode is ready, then playback switches to it, captions included; a video
that was never published stays unplayable until its first encode completes. A failed re-encode keeps
the current version playing and records failureReason. Playlists and embed.json are served with
Cache-Control: no-cache, so a player started after the switch gets the new playlists. Segments
keep the zone's browser TTL, so a browser that played the video within that TTL before the switch
can hold cached old segments for up to that long; a cleared cache, or waiting out the TTL, plays it
cleanly. A viewer already mid-video at the switch may need to reload.
12. Administration, the audit log and analytics
Administrators (bee:admin) list accounts with GET /api/v1/users. Entitlements and locking live
in the account center: PUT /api/v1/users/{id}/roles and POST /api/v1/users/{id}/lock / unlock
answer 409 managed_in_idp, and locking a person is disabling their account there.
The audit log is append-only and records who did what, when and from where:
curl -s "$AVAND/api/v1/admin/audit-log?limit=50" -H "Authorization: Bearer $AVAND_TOKEN"
It carries every API-key create, rotate and revoke (apiKey.*, with the key's name, id and
permissions), every zone-key issue, rotate and revoke (zoneKey.*, with the zone and scope),
and administrative purges. It is the first place to look after a suspected leak. Entries are kept
for 400 days by default (AvandAnalytics:AuditLogRetentionDays) and then swept.
Organization storage
If your organization bought storage, everyone who joins it draws their personal space from that one
total. Organization owners and admins manage it with /api/v1/tenant-storage (signed in as a person; an
API key is refused):
# The organizations you administer, with what each has used (empty if you administer none)
curl -s $AVAND/api/v1/tenant-storage -H "Authorization: Bearer $AVAND_TOKEN"
# Who is charged to "acme", what each stores and their share
curl -s "$AVAND/api/v1/tenant-storage/acme/members?limit=50" -H "Authorization: Bearer $AVAND_TOKEN"
# Give a member 5 GiB; send {"shareBytes": null} to remove the share
curl -s -X PUT $AVAND/api/v1/tenant-storage/acme/members/$USER_ID/share \
-H "Authorization: Bearer $AVAND_TOKEN" -H "Content-Type: application/json" \
-d '{"shareBytes": 5368709120}'
- Shares may add up to more than the total you bought: the total stays the hard cap, so the last uploads fail once everyone together has filled it.
- A share cannot be below what the member stores now (
409 bee.tenant_storage_share_below_usage). Lowering a share or the total never deletes anything; it only refuses new bytes. - The share and the allowance an Avand administrator set on the account both apply; the smaller wins.
- An organization you do not administer answers
404 bee.tenant_storage_not_found, the same as one that does not exist. - On the account page,
GET /api/v1/auth/mereturnsorganizationfor people charged to one: the organization's total and use, their share, andpersonalLimitBytes, the most they can store now.
Privacy: export, erasure, data residency
- Export. A signed-in person downloads everything Avand holds about them with
GET /api/v1/users/me/export: profile, zones with their object catalogues and key metadata, pull zones, video libraries with videos and captions, API-key and webhook metadata, and the audit entries they wrote. It is one JSON attachment; secrets are never in it, and an API key cannot pull it. - Erasure is the account deletion lifecycle: deleting the account in the account center (or
POST /api/v1/users/{id}/deletion) starts a 30-day retention period, after which its store is purged unless a legal hold keeps it (API_GUIDE §14 › Account deletion and legal hold). The immediatePOST /api/v1/users/{id}/eraseanswers409 account-deletion-lifecycle. The audit trail keeps one entry with the acting administrator and the counts, never the erased person; the entries the account wrote itself stay, because a trail that forgets its actors is not a trail. - Client addresses are truncated (IPv4 to /24, IPv6 to /48) before any access-log record or
audit entry is written; the operator can drop them entirely or, with a lawful basis of their
own, keep them whole (
AvandAnalytics:IpAnonymization). - Residency. An Avand deployment lives where its operator runs it: one database, one object store,
one region. There is no cross-region replication of personal data unless the operator builds it;
the
primaryRegionandreplicationRegionsof a storage zone label where the operator promises the bytes are, and Avand enforces nothing beyond that label.
Analytics:
# Delivery traffic, all zones or one; granularity is hourly, daily or monthly
curl -s "$AVAND/api/v1/statistics/delivery?from=2026-08-01T00:00:00Z&to=2026-08-13T00:00:00Z&granularity=daily&pullZoneId=$PZ" \
-H "Authorization: Bearer $AVAND_TOKEN"
# Storage consumption and transfer for a zone. Every authenticated data-plane request is
# recorded: a download counts as egress, an upload as ingress, in the zone's daily bucket.
curl -s $AVAND/api/v1/storage-zones/$ZONE_ID/usage -H "Authorization: Bearer $AVAND_TOKEN"
# Per-video playback: views, watch time (from players that send CMCD) and bytes sent
curl -s "$AVAND/api/v1/video-libraries/$LIB/videos/$VID/statistics?from=...&to=..." \
-H "Authorization: Bearer $AVAND_TOKEN"
13. End to end: upload a file and get its CDN URL, in Node and C#
The journey: with an access token traded from an IdP-issued key (§4), find the storage zone,
upload a file on the data plane with its zone key, list the folder, and print the public URL. Both
examples assume AVAND_TOKEN, AVAND_ZONE_KEY (a readWrite zone key, issued once in Avand,
because issuing one needs bee:admin) and AVAND in the environment, and a zone named my-assets
fronted by a pull zone named my-assets-cdn.
Node (no dependencies)
// upload.mjs — node upload.mjs ./photo.jpg photos/photo.jpg
import { readFile } from "node:fs/promises";
const AVAND = process.env.AVAND ?? "http://localhost:20331";
const headers = { Authorization: `Bearer ${process.env.AVAND_TOKEN}` };
const zoneKey = process.env.AVAND_ZONE_KEY;
if (!zoneKey) throw new Error("Set AVAND_ZONE_KEY to a readWrite key of my-assets.");
async function api(path, init = {}) {
const response = await fetch(`${AVAND}${path}`, { ...init, headers: { ...headers, ...init.headers } });
if (!response.ok) {
// Every control-plane failure is a problem document with a traceId worth logging.
throw new Error(`${init.method ?? "GET"} ${path} → ${response.status}: ${await response.text()}`);
}
return response.status === 204 ? null : response.json();
}
const [file, objectPath] = process.argv.slice(2);
// 1. The zone, by name.
const zones = await api("/api/v1/storage-zones?limit=200");
const zone = zones.items.find((candidate) => candidate.name === "my-assets");
if (!zone) throw new Error("Create the my-assets zone in Avand first.");
// 2. The zone key for the data plane comes from AVAND_ZONE_KEY. Issuing one needs bee:admin,
// which an IdP-issued key never carries, so it is issued once, in Avand (section 7).
// 3. Upload: raw bytes, PUT, on the data plane with the zone key.
const bytes = await readFile(file);
const upload = await fetch(`${AVAND}/storage/${zone.name}/${objectPath}`, {
method: "PUT",
headers: { "X-Bee-Access-Key": zoneKey, "Content-Type": "image/jpeg" },
body: bytes,
});
if (upload.status !== 201) throw new Error(`upload → ${upload.status}`);
// 4. See it listed, with the same key.
const folder = objectPath.slice(0, objectPath.lastIndexOf("/") + 1);
const listing = await fetch(`${AVAND}/storage/${zone.name}/${folder}`, {
headers: { "X-Bee-Access-Key": zoneKey },
}).then((response) => response.json());
console.log(listing.items.map((entry) => entry.path));
// 5. The public URL through the pull zone.
console.log(`${AVAND}/cdn/my-assets-cdn/${objectPath}`);
C# (HttpClient, .NET 8+)
// dotnet run -- ./photo.jpg photos/photo.jpg
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
string avand = Environment.GetEnvironmentVariable("AVAND") ?? "http://localhost:20331";
string token = Environment.GetEnvironmentVariable("AVAND_TOKEN")
?? throw new InvalidOperationException("Set AVAND_TOKEN.");
string zoneKey = Environment.GetEnvironmentVariable("AVAND_ZONE_KEY")
?? throw new InvalidOperationException("Set AVAND_ZONE_KEY to a readWrite key of my-assets.");
string file = args[0];
string objectPath = args[1];
using HttpClient control = new() { BaseAddress = new Uri(avand) };
control.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
// 1. The zone, by name.
JsonElement zones = await control.GetFromJsonAsync<JsonElement>("/api/v1/storage-zones?limit=200");
JsonElement zone = zones.GetProperty("items").EnumerateArray()
.First(candidate => candidate.GetProperty("name").GetString() == "my-assets");
string zoneName = zone.GetProperty("name").GetString()!;
// 2. The zone key for the data plane comes from AVAND_ZONE_KEY. Issuing one needs bee:admin,
// which an IdP-issued key never carries, so it is issued once, in Avand (section 7).
// 3. Upload: raw bytes, PUT, on the data plane with the zone key.
using HttpClient data = new() { BaseAddress = new Uri(avand) };
data.DefaultRequestHeaders.Add("X-Bee-Access-Key", zoneKey);
using ByteArrayContent body = new(await File.ReadAllBytesAsync(file));
body.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
HttpResponseMessage upload = await data.PutAsync($"/storage/{zoneName}/{objectPath}", body);
if (upload.StatusCode != System.Net.HttpStatusCode.Created)
{
// The body is an RFC 9457 problem document; its traceId links to the server-side trace.
throw new InvalidOperationException($"Upload failed: {(int)upload.StatusCode} {await upload.Content.ReadAsStringAsync()}");
}
// 4. See it listed, with the same key.
string folder = objectPath[..(objectPath.LastIndexOf('/') + 1)];
JsonElement listing = await data.GetFromJsonAsync<JsonElement>($"/storage/{zoneName}/{folder}");
foreach (JsonElement entry in listing.GetProperty("items").EnumerateArray())
{
Console.WriteLine(entry.GetProperty("path").GetString());
}
// 5. The public URL through the pull zone.
Console.WriteLine($"{bee}/cdn/my-assets-cdn/{objectPath}");
14. Troubleshooting
| Status | Meaning | What to do |
|---|---|---|
400 + errors | Validation failure | Fix the named fields; each item has a code and its field. bee.api_key_expiry_required and bee.api_key_expiry_too_far on expiresAt, and bee.system_account_name_invalid on name mean what they say; bee.api_key_zone_not_owned on zoneIds is the 400 when minting with a zone the account does not own. |
401, bare Bearer challenge | No credential | Send a token: trade your key, or sign in |
401, invalid_token | The access token expired or is invalid; or an avand_ak_ key is wrong, revoked, expired, or its system account disabled | Get a fresh token: trade the admin key again (a refused trade, invalid_grant, means the key is revoked, expired, idle or its person disabled: create a new one in the account center); a session is refreshed by the web app. A refused system key: mint a new one (§4) |
403 | Credential valid, permission missing; access.no_app_access (no Avand entitlement, on a surface an own-space-only person may not use); access.own_space_read_only (no entitlement: uploading, sharing and links are off, reading and deleting in your own space still work); access.api_keys_admin_only (an admin key whose person is not an administrator); bee.api_key_zone_not_owned (a zone-limited system key used on anything but its zones); or a key on a session-only operation | Retrying will not help. Give the key the right permissions or ask for the entitlement; use a session for system accounts, the profile and the export |
404 | Not found; another account's resource; or, on /cdn, any denied or missing content | The delivery plane never explains itself |
409 | Name taken, idempotency key still in flight, 25 active keys on a system account, rotating a dead key, bee.system_account_name_taken, bee.system_account_disabled, or managed_in_idp (roles or locks) | Pick another name, wait and replay the same key, revoke a key first; do the managed_in_idp work in the account center |
413 / 422 / 507 | Upload too large / checksum mismatch / account allowance exceeded | Resumable upload; re-send; ask an administrator for allowance |
502 / 504 / 508 on /cdn | The origin refused, dropped or failed the connection or sent an unparseable response / did not answer in time / the request already carried CDN-Loop: bee | Check the zone's origin URL and host header; 504 means raise AvandEdge:OriginResponseTimeout or speed up the origin; 508 means something in front of the origin points back at Avand. An origin's own 5xx is passed through as-is |
429 | Rate limited | Wait Retry-After seconds, which every plane sends. RateLimit-Policy names the budget that fired ("bee-delivery";q=30000;w=1) and RateLimit says when it resets |
Every control-plane and storage-plane error is a problem document with a traceId: quote it
when reporting a problem, it links the response to the server-side trace. Reading
WWW-Authenticate tells a client whether a fresh token is worth getting; an avand_ak_ key that
was refused is never worth retrying: mint a new one.
Rate limits. Delivery: 30 000 requests per second per client address, bursting to 60 000.
Control plane: 12 000 per minute per account. Storage data plane: 2 000 per second per zone key,
bursting to 4 000, and 10 000 per second per zone across every key, bursting to 20 000. Share links
(/api/v1/links/**): 600 per minute per address. Purges: 300 a minute (burst 120) for exact URLs
and 30 a minute (burst 20) for prefix, tag and zone purges, per pull zone. These are the defaults;
an operator tunes them under AvandRateLimits (see docs/host-configuration.md), and a 429 always
tells you which budget and how long to wait.
Timeouts and retries. GET, HEAD, PUT and DELETE are safe to retry. Retry POST only
with an Idempotency-Key. Through the suite's public host, Cloudflare stops waiting for an answer
after about 100 s and refuses bodies over about 100 MB (the origin nginx behind it allows 1 h and
4 GiB), with an error page rather than a problem document; in-network only Avand's own limits apply.
15. Quick reference
| Credential | Header | Format | Where it works |
|---|---|---|---|
| Admin API key (administrators only) | Traded at the IdP token endpoint; the token goes in Authorization: Bearer <jwt> | shk_…; the traded token is a JWT, 5 minutes | /api/v1/**, /upload/sessions/**, except system accounts and keys, the profile and the export |
| Session token | Authorization: Bearer <jwt> | JWT from the Central IdP; its lifetime is the IdP's | Everything on the control plane |
| System key (system accounts only) | Authorization: Bearer <key> or AccessKey: <key> | avand_ak_<32 hex>_<43 chars> | The account's own zones through the control, storage and upload planes (a zone-limited key: zone-aware routes only); /cdn, /img for a zone its account owns |
| Zone access key | X-Bee-Access-Key: <key> or AccessKey: <key> | avand_zk_<32 hex>_<43 chars> | /storage/{zone}/** only |
| Signed URL | Query string | ?token=…&expires=… | /cdn/**, /img/** on zones that require it |
| Share link | Path segment | 43 base64url characters | /api/v1/links/{token}, anonymous (API_GUIDE.md §2b) |
| Permission | Lets a credential… |
|---|---|
bee:read | Read every resource the account owns |
bee:write | Create and change zones, pull zones, rules, libraries, videos; implies read, purge and stream |
bee:purge | Purge CDN caches |
bee:stream | Manage video libraries and videos |
bee:admin | Everything, including zone keys, users and the audit log; never on an IdP-issued key |
| Data-plane verb | Path shape | Effect |
|---|---|---|
PUT | /storage/{zone}/{path} | Upload raw bytes (readWrite) |
GET | /storage/{zone}/{path} | Download, ranges honoured |
GET | /storage/{zone}/{prefix}/ or /storage/{zone}/ | List one level, JSON, paged |
DELETE | /storage/{zone}/{path} | Delete one object (readWrite) |
DELETE | /storage/{zone}/{prefix}/ | Delete everything under the prefix (readWrite) |