Store files #

View this page as Markdown

On this page

Add file uploads and downloads to your app, and control who can access each file. Read this page to set up storage, write file routes, or let a browser or mobile app transfer a file directly.

For a public gallery with no sign-in, use the complete upload starter, including its server, gallery page and check script.

Prompt:

Let users upload images, and keep each user's images private to that user.

Also works:

  • "Save each generated report as a file the user can download later."
  • "Let people attach a photo to a listing."
  • "Let anyone upload images to a shared gallery, with no sign-in."

For a manual upload, use Upload a file from the application's page. To add file handling to your app, read Before your AI starts, then follow Steps: declare an area, write file routes, and add direct transfers where needed. Step 2 (Put, fetch, list, delete) includes a private service. Build a public upload gallery gives the complete public starter.

The later steps cover limits, area declarations outside the manifest and deploy uploads. Check Expected result for successful responses or Refusals for a remedy.

Your backend or a script can also call the file routes directly over HTTPS without the Storage package. The credential and environment requirements in step 2 (Put, fetch, list, delete) apply; your backend still checks which files each end user may access. An application calling those routes lists no Storage package row in the manifest's packages; with no library entry at all, it declares packages: [] (Author the manifest).

To use the package, get @turnzero/storage with turnzero library take --entry storage (turnzero.cmd in Windows PowerShell), not from the npm registry. The command downloads the library entry, copies its compiled code into your app, and installs the local dependency; Use the library covers the credential and project layout.

For a small JSON value or list read and replaced whole, use a storage area with a conditional put, as Files or a database explains. For records you search, sort, transact on, or change individually from concurrent requests, use PostgreSQL. Keep key-value records gives the scaffold command for a key column and a value column. Turn Zero Cloud has no separate key-value storage service.

Upload a file from the application's page #

You can upload a file yourself without a command or a file-upload feature in your app. This also helps when your AI cannot read a file's bytes, such as a photo attached to a chat.

  1. Sign in at turnzero.ai, open Applications, and choose your application.
  2. Beside its storage areas, choose the area your AI named. If none is listed, ask your AI to declare one first.
  3. Choose the file and select Upload a file. For a file to include in a deploy, use development if the app has two environments. With production alone, there is no environment to choose.
  4. The upload keeps the file's own name. Give your AI the file name shown after the upload and the area name. Uploading the same name to the same area and environment replaces that file.

Uploads require a sign-in within the last 8 hours. If prompted, select Sign in again to upload a file, then upload.

For the AI tool: Declare an area bound to the application with declare_storage_area if it has none. Ask the person to follow these steps and tell you the stored name. Do not call mint_upload_grant for this route; the page handles the upload, and no grant passes through the chat. deploy_files reads each stored file from the environment receiving the deploy: production when the application has production alone, and development when it has two environments. With production alone, the page uploads to production without offering an environment choice. With two environments, ask the person to choose development for a file the deploy will use.

Include the file in the complete deploy_files.files list with an entry such as:

{ "path": "valley.png", "stored": { "area": "site-assets", "name": "valley.png" } }

path is where the file belongs in the version; area and name identify the uploaded copy. An optional top-level sha256 checks the stored bytes. The platform copies those bytes exactly, and the answer's stored lists their size and SHA-256.

Stored entries have no 512 KiB per-file limit. They still count toward deploy_files' 4 MiB total and 200 entries. Inline files keep the 512 KiB limit.

If the file is missing, artifact_not_found points to the application's page. Check the area, file name and deploy environment, then ask the person to upload again if needed. artifact_area_mismatch means the area cannot be used for this application's deploy.

What your AI tool does #

  • Reads the add-service skill (read_context, id skill:add-service) and follows it.
  • Copies the Storage package for examples that use it, and the Account package where users sign in (Use the library).
  • Writes the routes of A minimal upload service. Each route checks the signed-in user and keeps that user's files under the user's id.
  • Or writes the complete starter of A public upload service with no sign-in, where anyone may upload and read every file: its server, its gallery page, and its check script.
  • Adds the grant route of step 3 (Hand a browser or a native app a transfer grant) where a web page or a native app uploads or downloads directly from storage.
  • Deploys the change and waits until the deploy finishes (Deploy from your computer).
  • Asks you which files each user may read and write before it writes the routes, where the prompt does not say.
  • Asks you first before one action, delete_environment. It erases the development files in every area of the application, and runs only after you approve it in the browser (Applications and environments).

What you need #

  • A decision on which files each end user, a person who uses your application, may read and write. Your backend enforces it, because the platform doesn't separate files by user.
  • Stored files and the database share the application's 100 GB stored-data ceiling. Read the current application limits without signing in, or call read_plan_quotas with plan: "shared-0.5gb" or plan: "shared-1gb" and measure: "stored-data-capacity". File storage posts a day's share on its own line. Read its rate on the pricing page or with read_rate_card.

Before your AI starts #

For the AI tool: Check the following before starting.

  • Before declaring storage or deploying, connect and sign in to Turn Zero Cloud (Connect your AI assistant). Taking the Storage package with the CLI also requires a CLI credential (Use the library). A public upload service needs no end-user sign-in; a private service needs application sign-in.
  • The application's identifier, which list_applications returns. Your server code reads TURNZERO_CLOUD_APPLICATION and passes it as mintArea's application option. StorageWireClient reads no environment variables. A deploy sets that setting, and the provision command sets it for a run on your machine.
  • For a run on your machine, follow Write the environment file. The provision command writes the settings your backend uses to reach development storage. That guide explains which data and credentials the local run shares with production.
  • An absolute link your backend returns is built from APP_PUBLIC_HOST, the environment's public hostname, never from the request's Host header, which names the platform's internal address for the environment (the settings table).
  • A file the application needs again goes in an area. What the code writes to the running copy's own disk is lost whenever the copy is replaced or stops, as at a deploy or after an idle stop (Running copy).

Steps #

1. Declare the service and the areas #

Add {"kind": "object_storage"} to the manifest's services array. The object_storage kind alone creates no storage area. Each area is declared in the entry's areas, with the client's mintArea at the backend's start, or with declare_storage_area, before its first use. The storage routes and declare_storage_area work for a declared area with or without the entry. The entry's areas list holds one to fifty areas. Each has a name and account_keyed, and no name appears twice.

{"kind": "object_storage", "areas": [{"name": "photos", "account_keyed": true}]}

Each time a submission records the manifest, it declares every listed area for the application, and none of those areas keeps earlier versions of a file. Its receipt marks each area created or unchanged. An area is declared by one of three routes:

  • The manifest's areas, for an area the application knows when it is built.
  • The client's mintArea, for an area the running application creates, such as one per notebook.
  • The declare_storage_area action, for a script or a tool.

Use the manifest's areas for an area the application knows when it is built, the usual case. Use mintArea for an area the running application creates, and declare_storage_area for a script or a tool. One route is enough for an area: each manifest submission declares the areas it lists, so those need neither of the other calls.

Two routes may declare one area, such as the manifest's areas and a mintArea at each start. Under the application's platform credential or a token for that application, a mintArea that omits application still declares the area for that application. The same declarations answer unchanged, and different ones are refused (step 5: Declare or remove an area outside the manifest).

An area the list drops keeps its declarations and its files, because no submission ends an area. Step 5 (Declare or remove an area outside the manifest) covers declaring an area outside the manifest, and removing an area.

On every application, each area has two parts: development and production. A file written in development cannot be seen from production, and one name can mean a different file in each part. A run on your machine under the development platform credential writes to the development part. This holds on an application with one environment too, so test files never reach production. delete_environment erases every area's development files and leaves production's as they were.

2. Put, fetch, list, delete #

The platform keeps applications apart from one another, but it does not keep apart the end users of one application (What each application has of its own). It does not separate files by end user, and an end user's session cannot call the storage routes. Your backend calls them with the application's platform credential, after it checks which user sent the request. Start each user's file names with the user's id, and each route then reaches only that user's files.

If no end user is signed in, your backend still passes a nonempty identity on each write, such as anonymous for a visitor or report-job for a background task. This is an attribution label your backend chooses, not a sign-in credential or an access check. Your backend decides which files the caller may reach (File names, environments, and conditional writes).

The platform credential already belongs to one environment, so your backend sends no environment header. A script of your own may call the file routes with a minted token, for example to delete a test file. Such a script sends x-turnzero-cloud-environment with development or production on every call. A read, a list, and a delete need it as a write does. Without it the call is refused 400 environment_required (File names, environments, and conditional writes).

Call storage without end-user sign-in #

This example runs in your deployed backend and uses Node.js's built-in fetch, without the Storage or Account package. It declares a shared notes area through PUT /storage/v0/areas/notes, the HTTP route mintArea calls, writes hello.txt, lists the area, then reads the file.

No visitor signs in, and the backend needs no browser session. It still uses its platform credential; a call with no credential returns 401 authentication_required. Keep that credential in the backend.

// src/storage-no-sign-in.mjs: declare, write, list and read shared files
const origin = process.env.TURNZERO_CLOUD_GATEWAY_URL || process.env.TURNZERO_CLOUD_API;
const auth = { authorization: `Bearer ${process.env.TURNZERO_CLOUD_APP_TOKEN}` };

async function call(path, init = {}) {
  const response = await fetch(`${origin}/storage/v0/${path}`, {
    ...init,
    headers: { ...init.headers, ...auth },
  });
  if (!response.ok) {
    const { error, detail } = await response.json();
    throw Object.assign(new Error(`${error}: ${detail}`), { error });
  }
  return response;
}

// Every file name in the area, a page at a time; the last page has no cursor.
async function listNames(area) {
  const names = [];
  let cursor;
  do {
    const query = cursor ? `?${new URLSearchParams({ cursor })}` : '';
    const page = await (await call(`areas/${area}/files${query}`)).json();
    names.push(...page.files.map((file) => file.name));
    cursor = page.cursor;
  } while (cursor);
  return names;
}

// The file's text, or null where the area holds no file by that name.
async function readText(area, name) {
  try {
    return await (await call(`areas/${area}/files/${name}`)).text();
  } catch (failure) {
    if (failure.error === 'no_such_file') return null;
    throw failure;
  }
}

await call('areas/notes', {
  method: 'PUT',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ account_keyed: false, version_keeping: false }),
});
await call('areas/notes/files/hello.txt', {
  method: 'PUT',
  headers: { 'x-acting-identity': 'anonymous', 'content-type': 'text/plain' },
  body: 'hello',
});
console.log(await listNames('notes'));
console.log(await readText('notes', 'hello.txt'));
console.log(await readText('notes', 'missing.txt'));

The write records anonymous as its acting identity. That label grants no access. The credential already selects the environment, so these calls need no environment header. Each run writes hello.txt. If the notes area was empty when you started, the example prints [ 'hello.txt' ], hello and null.

A list answers { files, cursor }, each file with the fields File names, environments, and conditional writes shows. listNames passes each cursor back unchanged until a page comes without one.

A read of a missing file is refused 404 no_such_file, with the body Storage response bodies shows. readText answers null for that error alone, since an undeclared area is refused 404 too, as undeclared_area.

For a run on your machine, the developer signs in to the CLI once, then the provision command supplies the backend's credential. For a complete public web app, use A public upload service with no sign-in.

A minimal upload service #

These six files make a service that keeps each signed-in user's files private in one area. It uploads, lists, and downloads the user's own files, and gives a native app a transfer grant for an upload. A test runs them. Put them in your application's folder. Then take the Storage and Account packages as Add an entry to the library folder shows. The take command copies them into lib/storage/ and lib/account/ and runs npm install.

The take command requires --entry, for example turnzero library take --entry storage. Call read_library with entry: "storage" and use the command form for your operating system from its download response, then take account the same way.

For offline tests, use Storage's createStorageDouble as Use the other doubles describes.

Signed-in service files #

The platform's storage needs no egress entry; the list is for outside hosts. manifest.json declares sign-in and storage and records the two packages:

{
  "manifest_version": 1,
  "services": [{ "kind": "accounts" }, { "kind": "object_storage" }],
  "health": "/health",
  "region": "usa",
  "egress": [],
  "audience": { "kind": "public" },
  "packages": [
    { "name": "account", "version": "0.23.3" },
    { "name": "storage", "version": "0.23.2" }
  ]
}

package.json installs the two packages from their copies under lib/ and starts src/main.mjs:

{
  "name": "files-service",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "node src/main.mjs"
  },
  "dependencies": {
    "@turnzero/account": "file:lib/account",
    "@turnzero/storage": "file:lib/storage"
  }
}

src/storage.mjs builds the Storage client. The client makes its calls through the transport function, which sends each call to TURNZERO_CLOUD_GATEWAY_URL, or to TURNZERO_CLOUD_API where that is not set. It adds the credential from TURNZERO_CLOUD_APP_TOKEN. A deploy sets these settings, which A deployed app's settings lists. The provision command writes them for a run on your machine, so the same files run in both places.

// src/storage.mjs
import { StorageWireClient } from '@turnzero/storage';

export const AREA = 'uploads';

// Each call goes to the platform with the application's credential.
export function transport(path, init = {}) {
  const origin = process.env.TURNZERO_CLOUD_GATEWAY_URL || process.env.TURNZERO_CLOUD_API;
  return fetch(`${origin}${path}`, {
    ...init,
    headers: { ...init.headers, authorization: `Bearer ${process.env.TURNZERO_CLOUD_APP_TOKEN}` },
  });
}

export const storage = new StorageWireClient(transport);

src/users.mjs tells which user sent a request. It is the check from Tell which user sent a request, which explains it:

// src/users.mjs
import { makeVerifyClient } from '@turnzero/account';

// A deployed copy receives all three settings. A local run has no
// TURNZERO_CLOUD_REALM_KEYS, so the client is built without keys there and
// verifies through the platform's route.
const keys = process.env.TURNZERO_CLOUD_REALM_KEYS;
const accounts = makeVerifyClient({
  baseUrl: process.env.TURNZERO_CLOUD_API,
  credential: process.env.TURNZERO_CLOUD_APP_TOKEN,
  ...(keys ? { realmKeys: keys } : {}),
});

// The session token: the cookie's value from a browser, or the bearer from a native app.
function sessionOf(request) {
  const auth = request.headers.authorization ?? '';
  if (auth.startsWith('Bearer ')) return auth.slice('Bearer '.length);
  for (const part of (request.headers.cookie ?? '').split(';')) {
    // Spaces and tabs come off a pair and nothing else, so a name is read as it stands.
    let from = 0;
    let to = part.length;
    while (from < to && (part.charCodeAt(from) === 0x20 || part.charCodeAt(from) === 0x09)) from += 1;
    while (to > from && (part.charCodeAt(to - 1) === 0x20 || part.charCodeAt(to - 1) === 0x09)) to -= 1;
    const pair = part.slice(from, to);
    const at = pair.indexOf('=');
    if (at > 0 && pair.slice(0, at) === '__Host-turnzero_cloud_realm') return pair.slice(at + 1);
  }
  return null;
}

export async function userIdOf(request) {
  const verdict = await accounts.verifySession(sessionOf(request), {
    sessionHeader: request.headers['x-turnzero-cloud-session'] ?? null,
  });
  return 'user' in verdict ? verdict.user.id : null;
}
Signed-in request handler #

src/server.mjs starts listening on PORT straight away. Then it declares the area with mintArea, naming the application from TURNZERO_CLOUD_APPLICATION. Until the declaration succeeds, every route returns 503, the health path included. The declarations here must equal any declaration your AI tool made for the area with declare_storage_area. Otherwise every start fails: the platform refuses with differing_redeclaration, which the client throws as declarations_differ.

Every route except GET /health answers 401 when no user is signed in. The other routes are PUT /files/<name> to upload, GET /files to list, GET /files/<name> to download, and POST /grants/<name>. The last one is the grant of step 3 (Hand a browser or a native app a transfer grant), for a web page or a native app. Each route reads and writes under <user id>/<name>, and lists only names with that prefix, so no user reaches another user's files. A write also records the user's id as the acting identity, which says who made it.

The upload route answers the file's address from APP_PUBLIC_HOST, the public hostname the platform injects. A request's Host names the platform's internal address for the environment, so an address built from it does not resolve outside the platform.

The download route sends each file as an attachment, with x-content-type-options: nosniff. A browser then saves an uploaded page or image instead of running it on your application's hostname. An <img> element still shows such an image, because attachment governs only what a browser does when it opens the file's address itself. Each response also ends when the request's abort signal fires, as the deploy's rules require.

// src/server.mjs
import { createServer } from 'node:http';
import { AREA, storage, transport } from './storage.mjs';
import { userIdOf } from './users.mjs';

// A request's abort signal. The deployed runtime attaches its own signal to each
// request, and it aborts at the request's window. A local run has none of its own,
// and Node's request.signal can abort at a normal request end on some Node 24
// releases, so a local run's signal aborts when the response closes unfinished.
function abortSignalOf(request, response) {
  const own = Object.hasOwn(request, 'signal') ? request.signal : undefined;
  if (own) return own;
  const controller = new AbortController();
  response.once('close', () => {
    if (!response.writableFinished) controller.abort();
  });
  return controller.signal;
}

// Each user's files are kept under the user's id.
const pathOf = (user, name) => `${user}/${name}`;
const encodePath = (path) => path.split('/').map(encodeURIComponent).join('/');

async function readBytes(request) {
  const chunks = [];
  for await (const chunk of request) chunks.push(chunk);
  return new Uint8Array(Buffer.concat(chunks));
}

// This service answers each listed file's name, size, version, and content type.
async function listFiles(user) {
  const files = [];
  let cursor = null;
  do {
    const page = await storage.list(AREA, { prefix: `${user}/`, cursor });
    for (const file of page.names) {
      const { size, version, contentType } = file;
      files.push({ name: file.name.slice(user.length + 1), size, version, contentType });
    }
    cursor = page.cursor;
  } while (cursor);
  return files;
}

// A transfer grant for one upload, minted under the application's credential.
async function uploadGrant(user, name) {
  const response = await transport('/storage/v0/grants', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ area: AREA, name: pathOf(user, name), direction: 'upload', identity: user }),
  });
  const body = await response.json();
  if (!response.ok) return { status: response.status, body: { error: body.error } };
  const address = `${process.env.TURNZERO_CLOUD_API}/storage/v0/areas/${AREA}/files/${encodePath(pathOf(user, name))}`;
  return { status: 201, body: { address, grant: body.grant, expires_at: body.expires_at } };
}

let ready = false;

async function handle(request, response) {
  // End the response when the request is aborted (abortSignalOf, above).
  const signal = abortSignalOf(request, response);
  signal.addEventListener('abort', () => response.destroy(), { once: true });
  const send = (status, body) => {
    if (response.destroyed) return;
    response.writeHead(status, { 'content-type': 'application/json' });
    response.end(JSON.stringify(body));
  };
  if (!ready) return send(503, { error: 'starting' });
  // A target that does not parse as a URL names no route, so it ends like any unknown path below.
  let pathname = '';
  try {
    pathname = new URL(request.url, 'http://localhost').pathname;
  } catch {}
  if (request.method === 'GET' && pathname === '/health') return send(200, { ok: true });
  const user = await userIdOf(request);
  if (!user) return send(401, { error: 'sign_in_required' });
  if (request.method === 'GET' && pathname === '/files') return send(200, { files: await listFiles(user) });
  if (request.method === 'POST' && pathname.startsWith('/grants/')) {
    const grant = await uploadGrant(user, decodeURIComponent(pathname.slice('/grants/'.length)));
    return send(grant.status, grant.body);
  }
  if (!pathname.startsWith('/files/')) return send(404, { error: 'not_found' });
  const name = decodeURIComponent(pathname.slice('/files/'.length));
  if (request.method === 'PUT') {
    const contentType = request.headers['content-type'] ?? 'application/octet-stream';
    const { version } = await storage.put(AREA, pathOf(user, name), await readBytes(request), { identity: user, contentType });
    // The address a browser reaches: the public hostname, never the request's Host.
    const url = `https://${process.env.APP_PUBLIC_HOST}/files/${encodePath(name)}`;
    return send(201, { name, version, url });
  }
  if (request.method === 'GET') {
    try {
      const { bytes, meta } = await storage.get(AREA, pathOf(user, name));
      // An attachment, never shown in place, so an uploaded page cannot run on this hostname.
      response.writeHead(200, {
        'content-type': meta.contentType,
        'content-disposition': 'attachment',
        'x-content-type-options': 'nosniff',
      });
      return response.end(bytes);
    } catch (error) {
      if (error.code === 'no_file') return send(404, { error: 'no_file' });
      throw error;
    }
  }
  send(405, { error: 'method_not_allowed' });
}

export async function startServer(port) {
  const server = createServer((request, response) => {
    handle(request, response).catch((error) => {
      const refused = error instanceof URIError || error.code === 'invalid_name';
      if (!refused) console.error(error);
      if (response.destroyed) return;
      if (!response.headersSent) response.writeHead(refused ? 400 : 500, { 'content-type': 'application/json' });
      response.end(JSON.stringify({ error: refused ? 'invalid_name' : 'internal' }));
    });
  });
  await new Promise((resolve) => server.listen(port, resolve));
  // Declare the area before any file route runs. Every start restates the same declarations.
  await storage.mintArea(AREA, { accountKeyed: false, versionKeeping: false, application: process.env.TURNZERO_CLOUD_APPLICATION });
  ready = true;
  return server;
}
Start the signed-in service #

src/main.mjs starts the server on PORT:

// src/main.mjs
import { startServer } from './server.mjs';

await startServer(Number(process.env.PORT ?? 8080));

A page on the application's hostname uploads with fetch('/files/photo.png', { method: 'PUT', body: file }), and the browser sends the user's sign-in cookie with it. A body can be up to 32 MiB by default (step 4: Limits and metering).

In a project the scaffold wrote #

A project that turnzero scaffold wrote has the same two files in a different form. Its src/server.mjs exports createAppServer, and its src/main.mjs starts that server. Add the file routes above as one more branch of that server's request handler, before its 404. Then declare the area in src/main.mjs once the server listens, as startServer does above. Until the declaration has answered, have every route answer 503, the health path too, as the ready flag does above. A deploy then counts the copy as ready only once its area is declared.

A public upload service with no sign-in #

Use Build a public upload gallery for the complete service, gallery page and check script. It includes the Storage-package and fetch-only forms, with public access, limits and cleanup explained beside the files.

The starter without the library #

Use The starter without the library to write the gallery with fetch alone before signing in. Declaring storage and deploying still need a Cloud sign-in.

File names, environments, and conditional writes #

The client calls the storage routes for you, at /storage/v0/areas/{area}/files/{name} on the platform's origin. File routes on the Storage package page lists every answer each route gives, with its status.

These are the platform's file routes, called with the credential and environment that step 2 (Put, fetch, list, delete) describes. They are separate from the sample application's own /files routes:

Route Successful response
PUT /storage/v0/areas/{area}/files/{name} JSON with name, area, size, content_type, created_at, last_written_at, actor, and version, plus the ETag header.
GET /storage/v0/areas/{area}/files/{name} The file's bytes. Add ?meta=1 to receive those same fields as JSON instead.
DELETE /storage/v0/areas/{area}/files/{name} JSON with deleted, including when the file is already absent.
GET /storage/v0/areas/{area}/files?prefix=&cursor=&limit= A JSON object with files, an array of those file objects, and an optional cursor for the next page.

A list returns an object, not a bare array. Its file fields use the wire's snake_case names, including content_type. For example:

{
  "files": [{
    "name": "report.txt",
    "area": "documents",
    "size": 123,
    "content_type": "text/plain",
    "created_at": "2026-01-01T00:00:00.000Z",
    "last_written_at": "2026-01-01T00:00:00.000Z",
    "actor": "user-123",
    "version": "example-version"
  }],
  "cursor": "<opaque cursor>"
}

Pass the returned cursor unchanged in the next request's cursor query parameter, keeping the same prefix and environment. Files are in name order. On the last page, cursor is absent; an empty listing is {"files": []}. The Storage client's list result names it cursor too and uses camelCase file fields, as The client describes.

The file name is taken exactly from the path, slashes included. A name is refused 400 invalid_request when one of its segments, the parts a slash or a backslash separates, is . or ...

A write is also refused 400 invalid_request when the name holds a backslash, or when any segment ends with a dot, the last one included. This is because the storage service may keep such a name under another name. Separate segments with a forward slash, and end no segment with a dot. A file already stored under such a name can still be read, listed, and deleted.

Every call needs the account's credential, and reaches one environment's part of the area. The application's platform credential reaches its own environment. A header naming the other environment is refused 403 environment_mismatch. A session or a minted token belongs to no environment. So a call with either names the environment in the header x-turnzero-cloud-environment, as development or production, and is refused 400 environment_required without it.

A file's name is also refused 400 invalid_request when it is too long for the store. The store holds a name of at most 1,024 characters, counted with the account, area, and environment the file is stored under. A write and an upload grant's request count UTF-16 code units, so an emoji counts as two. A read, a metadata read, a delete, and a download grant's request count code points, so a stored file stays reachable. The refusal's detail gives the room left for the name in that area and environment.

A file's name is refused the same way when it has too many folders. The store holds a name of at most 254 segments, a segment being a part between slashes, and the account, area, and environment take three of them. A write and an upload grant's request count every part. A read, a metadata read, a delete, and a download grant's request count the parts that are not empty and allow one more, so a stored file stays reachable. The refusal's detail gives the segments left for the name.

Every write records an acting identity, sent in the header X-Acting-Identity. It says who made the write and grants no access. The client sends the identity you pass. A write without it, and with no grant that sets one, is refused 400 identity_required. The client refuses such a write before sending it, with no_identity and a message that opens unattributed write. An upload from a visitor who is not signed in still passes one: any nonempty string of your own, such as anonymous.

A conditional write sends If-Match with the version you expect, or If-None-Match: * for a name not yet used. A write whose condition fails is refused 412 version_mismatch.

A gallery or feed, newest first shows how to keep each caption in a Database row, or how to name files so the list shows the newest first.

The client's methods #

StorageWireClient is built over a transport that adds your credential, as A minimal upload service shows; The client lists its methods, their results, and their refusals.

The delete method is delete_(area: string, name: string, { identity }?: { identity?: string }): Promise<void>. Pass a nonempty identity even though the type makes the options optional; without it, the client rejects with no_identity before sending a request.

For an already declared uploads area and the client above, await storage.delete_('uploads', 'anonymous/photo.png', { identity: 'anonymous' }); deletes that file in the credential's environment. The promise resolves with no return value, including when the file is already absent. A service acting for a signed-in user passes that user's id and checks access before deleting.

3. Hand a browser or a native app a transfer grant #

A transfer grant is a short-lived credential for one file. It lets a client other than your backend upload or download that file directly from storage, so the file's bytes do not pass through your backend. A web page can use one in the browser. The file routes accept a PUT or GET with a grant from a page on any origin, and no cookie is sent. A native app uses one the same way.

Your backend mints each grant after its own user check. Your backend's own routes, as in A minimal upload service, are still how files are listed and deleted.

The sample's POST /grants/<name> route mints an upload grant after the same user check. It calls POST /storage/v0/grants under the application's platform credential or a token for that application. Name the environment as in step 2 (Put, fetch, list, delete); the grant then reaches only that environment's files. An account session or an account-scoped token cannot issue a grant on this route. They use mint_upload_grant instead (An upload grant from your tool). Send JSON with:

  • area and name;
  • direction: upload or download;
  • identity: a nonempty acting identity, fixed for the grant;
  • max_bytes, for an upload only: a positive integer up to the upload limit, which is the default when you leave it out.

The response returns grant once, with id, area, name, direction, identity, max_bytes, and expires_at. The page or the app sends the grant in the authorization header, as Bearer <grant>. With an upload grant, a PUT to the file's address uploads that one file; with a download grant, a GET downloads it. The grant is refused for other files, the other direction, and other routes.

In a page, the upload is two calls: the sample's grant route, then the PUT to the address it returns.

const { address, grant } = await (await fetch(`/grants/${encodeURIComponent(file.name)}`, { method: 'POST' })).json();
await fetch(address, { method: 'PUT', headers: { authorization: `Bearer ${grant}` }, body: file });

An upload grant is refused for a name that a write refuses, as step 2 (Put, fetch, list, delete) describes. A download grant for a file already stored under such a name is issued as usual.

An upload grant allows one successful write. After a refused write, it stays usable until it expires. A download grant allows repeated reads until it expires. A conditional write's If-Match or If-None-Match still applies to an upload under a grant.

A grant lasts five minutes by default, and platform staff can change the default. The upload must finish before the grant expires. Request the grant just before sending the file, especially on a slow connection. A grant also ends when its application or account is deleted. The storage routes then refuse it within the time When an ending takes effect gives. While the account is suspended, a grant is refused 403 account_suspended on its file route, and the backend cannot mint a new one. But suspension ends no grant: an unexpired grant works again once platform staff reinstate the account.

A platform credential and an application-scoped token each reach only their application's areas. Neither can issue a grant for another application's area.

4. Limits and metering #

A request body can be up to 32 MiB by default, and a list page up to 100 files. Platform staff can change both. An upload grant can set a smaller max_bytes, never a larger one. A list request takes prefix, cursor, and limit. A limit above the page maximum is reduced to it.

The cursor is opaque: pass it back as you received it. It does not expire. It remains valid after a new version of the application, and the next request may use a different limit. Follow the returned cursor for the next page.

The cursor marks the next page's first file by name. If that file has been deleted, the page starts at the next name, without a refusal. A file added with a name before the cursor's name does not appear on later pages. To include those additions, list again from the first page. A listing does not freeze the files while you read its pages.

The cursor names no account, area, or environment, so a backend may give it to visitors. The platform checks the cursor's form and its digest of the account, area, environment, and prefix. It also checks that the cursor's file name lies under the prefix and passes the rules for reading a stored file. So a file stored under a name a write now refuses still appears. The digest does not cover the cursor's file name, so an edited cursor only moves within the same listing.

A cursor from production cannot be used on development, or the reverse. A cursor for another account, area, environment, or prefix, or any other cursor that fails these checks, is refused 400 invalid_cursor: list again from the first page.

For each file operation, the platform records its bytes, outcome, and time against the application. When the application passes its stored-data ceiling, puts are refused usage_over_quota, and reads, lists, and deletes keep working (What an over state stops). Deleting the account removes its areas and files, and keeps the record of usage.

5. Declare or remove an area outside the manifest #

Outside the manifest, call declare_storage_area with:

  • name: a letter or digit, then letters, digits, hyphens, or underscores, up to 64 characters. A name beginning export- or deploy- is the platform's and is refused area_name_reserved;
  • account_keyed: true or false;
  • version_keeping: false;
  • application: the application the area belongs to. list_applications returns the identifier, and a call without it is refused 400 application_required.

You can also declare an area with PUT /storage/v0/areas/{area} and a JSON body containing the same members. On that route, a call under the application's platform credential or a token for that application can leave out application, and the area goes to that application. A call under a session or an account-scoped token must give it, or is refused the same way.

The Storage package's mintArea forwards application only when your code supplies it. The server examples above read that value from TURNZERO_CLOUD_APPLICATION.

A server that mints its area at each start needs no declare_storage_area call, so the declarations live in one place. For an area the manifest's areas lists, that place is the manifest, and the area needs neither the call nor a mint. Where the mint and the call both run, they must name the same declarations, or the server's start fails with declarations_differ.

The client spells the two declarations in JavaScript's style: mintArea takes accountKeyed and versionKeeping, and sends them as account_keyed and version_keeping. A tool's call or an HTTP request names the wire's spelling.

Declaring an area again with the same declarations changes nothing. Different declarations, including a different application, are refused.

version_keeping: true is refused: the platform keeps no earlier versions of a file. The platform records account_keyed, but it does not separate files by end user, so its value changes nothing about who can read a file. An area's declarations are fixed, so a different value needs a new area.

list_storage_areas returns the account's areas. It is a management action, not a storage route, and no storage route lists areas. The declaration route PUT /storage/v0/areas/{area} and list_storage_areas take no environment header.

The signed-in application page uses list_storage_files to list one page of an area's files and read_storage_file to read one file's fields, never its content. Scripts can call both management actions over HTTP with a bearer credential that reaches the area. Customer MCP connections do not list these actions.

Pass application and an area bound to it; read_storage_file also takes name. If you omit environment, both actions use the application's deploy target, where an upload with no environment writes. The file listing action and the storage listing route accept each other's cursors for the same area, environment and prefix.

To remove an area that contains no file in either environment, call declare_storage_area with its name and remove: true. It removes the area and frees the name, so a later declaration under that name creates a new area. Removing an area that still contains a file is refused area_not_empty, so delete its files in both environments first. Only the account can remove an area, under a session or an account-scoped token. An application-scoped token is refused by name.

Every area belongs to one application, and none belongs to two or to none. Deleting an application deletes its areas and every file in them.

6. The deploy area, and deploying from an area of your own #

A deploy's zip goes to the application's deploy area, deploy-<application id>, which the platform creates and keeps. Deploy from your computer shows the turnzero deploy command that uploads it. Only a deploy's short-lived upload grant reaches its files. The command alone receives it, from the call that prepares the upload. Your session, your tokens, and the application's platform credential are refused 403 area_scope_refused there.

A file in the deploy area older than a day is deleted at the next daily cleanup. The cleanup keeps a file saved by deploy_files while either environment serves or is deploying a version that lists it (Deploy from your computer). The area's bytes count toward your application's stored data, and an export leaves the area out.

You can send the deploy grant's upload again with the same zip, for example after a response was lost. After the first upload has landed, and until the grant expires, a repeat gets status 200 and nothing is written. The response gives the file's name, area, size, and sha256, with no version and no ETag. Different bytes are refused transfer_grant_spent. When the command prepares a new upload, its deploy call cancels the previous upload if its deploy has not started.

The prefix deploy- is reserved: a new area whose name begins with it is refused 400 area_name_reserved. An area you declared under the prefix before it was reserved keeps its files and your access.

The artifact form is the route that needs no turnzero command. A script of your own deploys from an area of its own. It uploads with one of the two commands that mint_upload_grant returns, which need no turnzero command, or with the put command, as An upload grant from your AI tool describes. Or it uploads under a minted token, with the header naming the environment the deploy goes to and an acting identity, as An upload under a minted token shows.

That script then calls deploy with artifact: the area, the file name, and the SHA-256 hash (Deploy from your computer). Set artifact.environment to the environment holding the ZIP; if omitted, it defaults to the environment the deploy goes to.

An upload grant from your tool #

To upload one file from a shell, your AI tool calls the management action mint_upload_grant instead of keeping a token in the shell. It takes:

  • application, and an area bound to that application;
  • name, the file's name in the area;
  • environment, optional: left out, it is the environment a deploy goes to, production on an application with one environment and development on one with two;
  • identity, optional: the acting identity, "deploy" when you leave it out;
  • local_path, optional: the file on your machine, as an absolute path or one relative to the folder the upload command runs in. Where you leave it out, the file is the one whose name is the last segment of name, in that folder.

On an application with one environment, leaving environment out puts the file beside your live application's own files. Name development for a test or seed file, so it stays with the data your local runs use.

The platform never reads the file at local_path: the upload command reads it on your machine. A local_path a shell would change in the upload command is refused 400 invalid_request, and nothing is minted. Such a path has a control character, a double quote, $, a backtick, %, !, &, |, <, >, ^, a typographic double quote, a doubled backslash, or a trailing backslash. PowerShell passes a path that has no space to turnzero.cmd without its quotes, and cmd then reads &, |, <, >, and ^ as command syntax. So those five are refused on every operating system.

The upload command does not expand ~: name your home folder in full.

The response contains grant once, expires_at, max_bytes, the file's whole address, and these upload commands:

  • command_npx and command_npx_windows, the put command through npx for macOS/Linux and Windows, with no global installation needed;
  • command and command_windows, the installed forms of the turnzero command, using turnzero and turnzero.cmd;
  • commands, two upload commands that need no turnzero command: commands.curl, run in a shell such as bash with curl 7.76 or later, and commands.powershell, run in Windows PowerShell. Run curl --version to read its version on the first line.

Your AI tool first runs command_npx, or command_npx_windows on Windows, once, exactly as returned, before expires_at. If npx cannot run here, use the installed form when turnzero --version responds.

For a deploy with no usable command, use deploy_files within its limits, then the upload route past them. For an upload, use the returned curl or PowerShell command. Install the turnzero command only if the person wants to keep it.

The put command reads the grant from standard input, never from an argument. Each of the two commands sends only the grant, as the bearer token, because the grant already fixes the environment and the identity. All of them read the same file on your machine.

This is command for a call that names the area artifacts and the name app.zip, with <grant> where the call's own grant goes. A test checks that it matches the upload command the platform builds:

echo <grant> | turnzero put --area artifacts --name app.zip --path "app.zip"

If your AI tool is connected to a platform other than https://turnzero.ai, the returned command includes --origin with that platform's address.

After its version line, the command prints one line that opens with put: and gives the file as the area stores it, as JSON: its name, area, size, version, content_type, and last_written_at. It ends with one of three statuses:

  • 0: the file was written;
  • 3: nothing was written, as on a refusal such as transfer_grant_spent: a write that lands spends the grant, so a second run after it is refused;
  • 2: the outcome is unknown, so the file may have been written. Call mint_upload_grant again and upload under the new grant.

The returned commands.curl uses --fail-with-body and sets no time limit of its own. The whole upload must arrive before the grant's expires_at, five minutes after minting by default. Request the grant just before uploading. Its outcomes differ from the put command's:

  • Exit 0 with the stored file's JSON confirms the upload.
  • Exit 22 means an HTTP status of 400 or above. Curl still prints the response body. For a platform refusal, read its error and detail and follow the remedy.
  • Exit 28 means a timeout. It gives no confirmation: the file may have been written. Call mint_upload_grant again and upload under the new grant.
  • Another nonzero exit also gives no confirmation. Mint a new grant and upload under it.

If the response is missing or is not the platform's own, treat the outcome as unknown too. A successful write spends this grant, so do not repeat an uncertain upload with the same grant.

For a deploy whose uploads repeatedly time out, use the turnzero command where it can run. Otherwise, follow When to ask the person, giving them the exact command you cannot complete.

The response has none of command, command_windows, command_npx, and command_npx_windows where the name contains a character that the put command cannot pass unchanged through every shell. A space is the common case. The put command can carry a name of up to 1,024 characters made of letters, digits, ., _, -, and /, starting with neither - nor /. The response's detail then says so, and your AI tool runs commands.curl or commands.powershell, which read the same file.

The put command sends the file as it is, in one write, and follows no redirect. A write of a name that is already stored replaces that file.

In Windows PowerShell 5.1, Invoke-WebRequest needs -UseBasicParsing, and commands.powershell includes it.

The grant is an upload grant like any other: one file, spent by the one write that lands, and refused on every other route. A second write after that one landed is refused transfer_grant_spent, even with the same bytes. A refused write leaves the grant standing until it expires. The session, an account-scoped token, and a token for that application can call the action. The application's platform credential cannot, and the backend mints on POST /storage/v0/grants instead.

An upload under a minted token #

The samples below show an upload without the turnzero command. They upload app.zip with a minted token into an area of your own named artifacts, for a script of your own that deploys with artifact. The token is in the environment variable TURNZERO_CLOUD_MINTED_TOKEN, and deploy-tool is the acting identity.

With curl 7.76 or later, from a shell. Here curl reads the Authorization header from standard input, so the token never appears in curl's arguments.

printf 'Authorization: Bearer %s' "$TURNZERO_CLOUD_MINTED_TOKEN" | curl --fail-with-body --upload-file app.zip \
  -H @- \
  -H "x-turnzero-cloud-environment: production" \
  -H "X-Acting-Identity: deploy-tool" \
  -H "Content-Type: application/zip" \
  "https://turnzero.ai/storage/v0/areas/artifacts/files/app.zip"

With Node.js, saved as upload.mjs and run with node upload.mjs.

import { readFile } from 'node:fs/promises';

const response = await fetch('https://turnzero.ai/storage/v0/areas/artifacts/files/app.zip', {
  method: 'PUT',
  headers: {
    authorization: `Bearer ${process.env.TURNZERO_CLOUD_MINTED_TOKEN}`,
    'x-turnzero-cloud-environment': 'production',
    'x-acting-identity': 'deploy-tool',
    'content-type': 'application/zip',
  },
  body: await readFile('app.zip'),
});
console.log(response.status, await response.text());
if (!response.ok) process.exit(1);

Expected result #

The service's PUT /files/<name> returns 201 with the name, the version, and the file's address on APP_PUBLIC_HOST. GET /files lists the signed-in user's own files alone, each with its name, size, version, and content type, and a request without a session answers 401. POST /grants/<name> returns the grant once with its expires_at and the address the page or the app uploads to.

The public service's POST /files returns 201 with the name it chose, the version, and the file's address, with no session. Its GET /files lists every visitor's files a page at a time, each with an absolute url built from APP_PUBLIC_HOST, and returns the page's cursor. An upload outside its bounds answers 415, 413, or 429 and stores nothing.

When the manifest's object_storage entry lists areas, the submission returns each area in storage_areas, with its outcome and file address (the receipt table). declare_storage_area returns the area and an outcome, created for a new area or unchanged when the same declarations were repeated. Its detail gives the area's whole file address, https://turnzero.ai/storage/v0/areas/<area>/files/<name>, and list_storage_areas then lists the area with its declarations and its application.

A PUT on a file route returns 200, with the file's version in the ETag header and its metadata as JSON; the package's put returns that version. mint_upload_grant instead returns the upload grant once, with the file's address and the upload commands. It does not upload the file. Run a returned command as given; a successful put prints the stored file's metadata on a line opening with put: and exits with status 0. A file written from development is listed from development and absent from production.

A file's version is opaque. The platform's is an HTTP entity tag that keeps its double quotes, so the JSON string holds them too. Send a version back unchanged in If-Match or If-None-Match.

declare_storage_area with remove: true returns outcome: removed with the area as it was, or outcome: unchanged with area: null when no area has that name.

Refusals #

See the refusals reference for other platform errors.

Storage response bodies #

Storage's own refusals return JSON with error and detail. For example, a request for a missing photo.png in a declared uploads area returns status 404 with a body like this:

{
  "error": "no_such_file",
  "detail": "No file \"photo.png\" in \"uploads\"."
}

The platform's credential guard can refuse a request before it reaches storage. Those responses also include contract_version, for example a 401 authentication_required.

Handle either form by its error value. The detail text explains it for a person and can change; do not match that text in code. Storage's own refusals can add fields. For example, version_mismatch adds current_version, and some refusals add credential_kind or scope.

When using StorageWireClient, handle its own code instead, as Failures explains. A refused write stores nothing. Deploy from your computer lists the deploy's refusals, including the artifact checks.

Refusal causes and remedies #

Refusal Status Cause Remedy
invalid_request 400 A member or header is malformed; detail names it. For example, an area name breaks step 5 (Declare or remove an area outside the manifest). A grant request may break step 3 (Hand a browser or a native app a transfer grant). A path containing a NUL character (U+0000) is refused too, as is a declaration or grant body containing one or an unpaired UTF-16 surrogate; detail then names the character. A write, or an upload grant, whose file name holds a backslash or a segment that ends with a dot is refused too. So is a file name past 1,024 characters with its account, area, and environment. A write or an upload grant counts UTF-16 code units, and a read, a metadata read, a delete, or a download grant code points. So is a file name past 254 segments with its account, area, and environment, a segment being a part between slashes. Correct the named member, or remove the character detail names, and send the request again. For a file name, separate segments with a forward slash, and end no segment with a dot, and keep it within the room detail gives.
differing_redeclaration 409 The area was declared again with different declarations, such as another application. For a listed area, submit_manifest names this refusal in a manifest_invalid line at the area's path, and returns 409 only if another declaration lands while the call records it. Repeat the current declarations, use a new area name, or undeclare an empty area and declare it again.
environment_required 400 A session or minted token called a file route, the file list, or the grant mint without x-turnzero-cloud-environment, or with a value that names neither environment. Send the header with development or production.
environment_mismatch 403 A call under an application's platform credential named the other environment. Drop the header, or name the credential's own environment.
identity_required 400 A PUT or DELETE had no X-Acting-Identity header and no grant sets one. Send the acting identity on every write.
undeclared_area 404 Your account has no area by that name, on a file route, the grant mint, or mint_upload_grant. Declare it with declare_storage_area or PUT /storage/v0/areas/{area}. A name beginning export- or deploy- is the platform's and is never declared: choose another name.
area_scope_refused 403 The credential cannot reach the area, which belongs to another application. On mint_upload_grant, the area belongs to an application other than the one named. On an application's deploy area, every credential of yours is refused, and so is a grant from mint_upload_grant or the grant route. Call under the application's platform credential, a token for that application, or an account-wide credential. For mint_upload_grant, name the area's own application. For the deploy area, call deploy_command with the application, and run the deploy command it returns once.
application_other_account 403 An area declaration named an application that another account holds, not the account the call is signed in as. The detail names the account the call acted as and nothing of the other one. Compare turnzero whoami with read_account over your AI tool's connection, and declare the area from the one signed in to the account that holds the application.
no_such_file 404 A GET named a file the area does not contain, or a put named a version for a missing file. Under an export's download grant, a stored file created after the export listed its files returns the same refusal. Check the name and the environment. Create a new file with If-None-Match: * or a plain put. Under an export's download grant, Download the export says what to do next.
request_too_large 413 The body is larger than the request limit, 32 MiB by default, or the grant's max_bytes. Send a smaller body, or mint a grant with a larger max_bytes within the request limit.
usage_over_quota 429 The area's application passed its stored-data ceiling at the last usage check. Reads, lists, and deletes still work. Delete files or database rows and wait for the next daily check. The start of a new month does not clear it.
rate_capped 429 One client address sent your application more requests in a minute than the serving router admits, or the backend's credential made more than 600 storage calls in a minute. Wait the seconds Retry-After gives, then send the request again.
grant_minter_not_admitted 403 POST /storage/v0/grants was called under an account session or an account-scoped token. Mint the grant under the application's platform credential or a token for the application. For an upload from your AI tool, call mint_upload_grant.
app_credential_not_admitted 403 mint_upload_grant was called under the application's platform credential. Call it from your session or a minted token. The backend mints on POST /storage/v0/grants.
transfer_grant_not_admitted 403 A transfer grant was used for another file, the other direction, or another route. Use the grant only on PUT or GET for its one file, and an ordinary credential elsewhere.
transfer_grant_spent 403 The upload grant was already used by a successful write. Rarely, a refused write could not give the use back, and nothing was written. Under a deploy's grant, the same zip sent again returns 200 instead. Mint another grant for the next upload, from the backend or with mint_upload_grant. For a deploy's upload, call deploy_command again and run the deploy command it returns, unless a later deploy command of yours is already running.
transfer_grant_expired 403 The grant has expired, five minutes after minting by default. Mint another grant, from the backend or with mint_upload_grant for an upload.
account_suspended 403 The account is suspended: the calling credential's account, or, under a transfer grant, the account whose application minted the grant. Nothing on your side clears it. Once platform staff reinstate the account, an unexpired grant works again.
authentication_required 401 The call sent no credential, or one that matches no account. Or it sent a grant that was not accepted, and the detail opens "The grant this request presented was not accepted": the grant expired and was removed, or its value was changed. Send the application's platform credential, a minted token, or the session's credential. For a grant that was not accepted, use a new grant. Where your application requested the grant, request another from POST /storage/v0/grants. Where mint_upload_grant returned it, call that action again and run the upload command it returns.