Connect an app to Nostrad
Nostrad gives your app AI models (images, video, speech, music, chat) and a Drive for files through the Nostrad gateway at https://gateway.nostrad.ai, an HTTP API. Your app never holds a supplier key.
Two ways in
Choose per app; an app can use both. Both reach the same models with the same commands; only who pays, and how your app proves who it is, differ.
| An API key | Sign in with Nostrad | |
|---|---|---|
| Who pays Nostrad | You, from your own Nostrad balance, for every call | Each person using your app, from their own Nostrad balance, within the monthly limit they choose for it |
| Your app's users | Need no Nostrad account; you charge them however you like | Sign in with their Nostrad account, the way they would sign in with Google |
| What your app holds | One key, on your server only (NOSTRAD_API_KEY) | A client ID (public), and a client secret for a web server; an access token per person |
| Pick it for | Your own server, scripts, background work, an app with its own accounts and billing | An app whose users already have, or are happy to make, a Nostrad account: Nostrad handles accounts, payment and their Drive |
| Start here | Quickstart: an API key | Quickstart: Sign in with Nostrad |
Sign in with Nostrad is standard OAuth 2.1 (authorization code with PKCE) at https://accounts.nostrad.ai; it gives your app an access token for one person. Either way, every gateway call carries Authorization: Bearer <API key or access token>.
1. Checklist: from nothing to a working app
- Have a Nostrad account, and open the developer console. Sign-up isn't open yet: accounts are made by invitation from Nostrad. To ask for one, email support@nostrad.ai and say what you'd like to build.
- Create app: give it a name. This is your app on Nostrad; its App ID never changes.
- Services: tick the services your app uses.
- Make what the way in you chose needs (Two ways in; an app can have both):
- An API key: API keys, then Create API key. It is shown once; put it in your server's secret store as
NOSTRAD_API_KEY, never in code or a file. - Sign in with Nostrad: the Sign in with Nostrad page, then Create client, one per program that signs people in. Web server if your app has its own server: you get a client secret, shown once, for the server's secret store. Phone, desktop or browser-only if it has no server: no secret, PKCE alone. Enter the exact return address (redirect URI) your program uses, for example
https://your-app.example/oauth/nostrad/callback.
- An API key: API keys, then Create API key. It is shown once; put it in your server's secret store as
- Integration: copy the values into your program. The For your coding agent box there holds everything below for your app, both ways, without any secret.
- Run the quickstart for your way by hand: an API key or Sign in with Nostrad. Each goes from nothing to a downloaded image.
- Build it: the gateway calls (section 4), and for sign-in the sign-in itself (section 3). A complete sign-in server, ready to deploy, is in section 9. Your app is personal until it goes public: only you can sign in to it.
Once you have an account, nothing else is needed: no request to Nostrad, no key to ask for, no setting outside the console. Stuck? See Getting help.
2. The developer console
The console is at accounts.nostrad.ai/developer/, with the same login as your Nostrad account. Each app has these pages:
| Page | What it holds |
|---|---|
| Overview | The App ID, whether the app is personal or public, and how many sign-in clients and API keys it has. |
| Models | Every model your app can use, what it costs, and whether it's running now. |
| Drive | How your app's files work, the commands for them, and the picker to try. |
| API keys | Your app's API keys: create, limit, rotate and delete them. |
| Integration | Every value your program needs, with worked examples. |
| Playground | Run a model in the browser before you write any code. |
| Logs | Every call, with its job ID. |
| Usage | What your app has used. |
| Sign in with Nostrad | Sign-in clients and their secrets. |
| Services | The services the app may ask for. |
| Monetize | Selling inside your app: products, subscribers, orders, earnings, notifications and testers. |
| App settings | The app's name, links (website, developer, source code, privacy policy, terms) and support email. The name is at most 30 characters, with no emojis and no symbol three times in a row, and is your app's own: another app's name with other capitals, spaces or punctuation is refused (Apple 2.3.7: "Choose a unique app name"). People see them on the consent page, where they connect their Nostrad account to your app; leave Support email empty and your app's support mail goes to your account email, which is never shown to people. A business address you type shows there and on people's purchases only once it's verified. Verify email address sends a 6-digit code to the support email; enter it within 15 minutes (5 tries; a new code at most once a minute). The email your Nostrad account signs in with is verified at once. Changing the support email needs it verified again. The rest of this page is below. |
| App settings: Price | What people who sign in to your app pay, as a percentage over Nostrad's prices, from 0 to 500 (0 to start). You get the difference. The page shows what three of your models then cost a customer; jobs started after you save use it. The consent page says it: "your app charges 30% over Nostrad's prices". |
| App settings: Adult models | Allow adult models, off to start. While it's off, models Nostrad marks as adult aren't listed for your app and their jobs answer 403. When it's on, the app is rated 18+ and the consent page says your app may make adult content. |
| App settings: Age rating | The App Store's age rating questionnaire: for each kind of content, how often it appears in your app (None, Infrequent or Frequent), and whether it has each feature (such as unrestricted web access or gambling). The answers give the rating, 4+, 9+, 13+, 16+ or 18+, the highest any answer gives, as Apple's do. You can choose a higher rating, never a lower one. The consent page shows the rating and what gave it. An app rated 18+ reaches only people whose Nostrad account says they're 18 or over: anyone else is refused on the consent page, and their jobs answer 403 age_restricted. Adult models are only for people 18 or over too. Answer it before you submit the app. |
| App settings: App review information | What Nostrad's reviewer needs to try your app, as the App Store's App Review information and Google Play's sign-in details ask. A contact (name, email and a phone number in international format, starting with + and the country code). Sign-in required: tick it if people sign in to your app's own account, and give up to 5 sets of sign-in details, each a user name and password for a demo account, or other instructions (a one-time code, a QR code's web address, another service's account). The demo account must not expire, must work from any country and must need no one-time code or two-step login. Notes: anything else that helps, up to 4,000 bytes. Only Nostrad sees it, it's kept encrypted, and you can change it at any time. |
| App settings: Who can sign in | Personal (only you can sign in), waiting for Nostrad's check, verified (public: anyone with a Nostrad account can sign in), or not verified with Nostrad's reason. Submit for verification needs the website, privacy policy and terms on this page, a typed support email verified (an empty one needs nothing), the age rating answered and the App review information filled in. It opens each of the app's links, and is refused if one doesn't open for anyone: a missing page, an error, a login, a page that doesn't answer within 10 seconds, an address without https, or a PDF or download instead of a web page. Send for review on a verified app's changes needs the App review information too. While it waits, Remove from review takes it back to personal; submitting it again starts the check over. Once it's verified, Unpublish lets nobody new connect to it, while people already connected keep using it; Publish again lets new people in again, with no new check. |
| App settings: Delete app | Type the app's name, then Delete app. If nobody else uses it, it's deleted at once. If people use it, nobody new can connect, its subscriptions stop renewing, and it keeps working for them for 90 days, or until the last paid period ends if that's later; their Apps page says when it stops. Until then, Keep the app stops the deletion. Deleting stops the app's sign-ins and API keys, takes its products off sale and frees its name for anyone; its sales and earnings records stay. It can't be undone. |
| App settings: Messages with Nostrad | Shown when Nostrad didn't verify the app, rejected an update or switched the app off, with Nostrad's reason. Reply (up to 4,000 characters) until you send the app again; Nostrad answers here. After a reply, Appeal the decision once if you believe the app follows the App review rules. |
| Inbox (from your account menu) | Messages from people using your apps, in your Inbox. Anyone using your app, or anyone at all once it's public, can write to you from the app's page on their account; you see them by the same ID your app gets for them (usr_...), never their email address, and answer in the conversation, up to 4,000 characters. You can't write to someone first: Announce to the people using your app sends one message to everyone using it, and their answers come back to you as messages. A person can stop your app's messages; then you can't write to them. If they choose Ask Nostrad to help, Nostrad reads the conversation and answers in it, seen by you both. You get an email for a new message, once until you read the conversation (switch it off under Account details, Emails). Never ask anyone for a password, a code or card details in a message. |
Client secrets
- A Web server client can have up to two secrets at once. Add secret makes a new one while the old one keeps working; move your server to the new one, then Disable the old one (Enable brings it back) and Delete it.
- A secret is shown once. Afterwards the console shows its last four characters and when it was last used.
- Lost or leaked secret: Add secret. The client ID stays the same, so nothing people installed stops working.
- A deleted client can be restored for 30 days. Its tokens stop working while it is deleted.
API keys
An API key calls the Nostrad gateway without anyone signing in, and you pay for every call made with it, from your own Nostrad balance, like a Google Maps key. Use it from a server only: a key in a web page, a phone or desktop program, or shared code can be copied and spent.
- Create API key asks a name, the services the key may use (from the app's), a monthly limit in dollars (required; $100.00 to start), and optionally an expiry date and up to 1,200 IP addresses or ranges (like
203.0.113.7,203.0.113.0/24or2001:db8::/32) it may be used from. With no addresses it works from anywhere. Nostrad emails you when a key has used 80% of its monthly limit and when it reaches it, once each a month (switch it off under Emails in Account details). - The key starts
nsk_and is shown once. Afterwards the console shows its first and last characters (likensk_abcdefgh…wxyz), this month's use and when it was last used. Keep it in your server's secret store, for example asNOSTRAD_API_KEY. - Send it as
Authorization: Bearer <key>, never in the address. Every gateway command works with it; the key's jobs and files are your own, for that app. - Your account may start about 600 jobs a minute and make about 3,000 other requests a minute, counted across all your keys together: another key adds nothing. Starts are counted apart, so asking about running jobs doesn't use up what starts them (the count is kept in each Cloudflare location, so it is approximate). A person signed in through Sign in with Nostrad is counted the same way, on their own account. Over either the gateway answers 429 too many requests for this account; try again in a minute with
retry-after: 60. - Rotate makes a new key with the same settings and asks when the old one stops working: right away, in 1 hour, in 24 hours, in 7 days, or when you delete it. Move your server to the new key before then. Lost or leaked key: Rotate with right away, which stops the old key first, even when the app already has as many keys as it can have. A key is rotated once: after that, use its new key. A key that has stopped can't be rotated; create a new one. The console sends the choice as
old_key_expires_in:0,3600,86400or604800seconds, or left out to keep the old key until you delete it. - A deleted key stops at once and can be restored for 30 days. An app can have up to 300 keys.
- Some models' makers allow them only through Sign in with Nostrad. A key's job on such a model answers 403 this model can't be used with an API key; it needs Sign in with Nostrad.
3. Sign in with Nostrad
Standard OAuth 2.1 authorization code flow. Any OAuth client library works. The discovery document lists everything below:
https://accounts.nostrad.ai/.well-known/oauth-authorization-server
| Value | |
|---|---|
| Issuer | https://accounts.nostrad.ai |
| Authorization address | https://accounts.nostrad.ai/authorize |
| Token address | https://accounts.nostrad.ai/oauth/token (also revokes: POST token=<token>, see below) |
| Resource | https://gateway.nostrad.ai (RFC 8707: the token is for the Nostrad gateway) |
| PKCE | Required for every client, method S256 |
| Access token | Lasts 1 hour |
| Refresh token | Lasts until it goes six months without being used |
Scopes: the services
Each service is an OAuth scope. Ask for the ones your app uses, separated by spaces. Asking for none means every service the app ticked under Services. Every connected app also has its own folder in the person's Drive, whatever it asks for, so an app that only keeps files (settings, notes, saved work) ticks nothing under Services and asks for nothing: the person then sees only its folder on the consent page, with no spending limit (step by step).
| Scope | What the person sees |
|---|---|
image | Make images |
video | Make videos |
speech | Make speech and use voices |
music | Make music |
chat | Chat and write text |
On the consent page (Connect your Nostrad account to your app's name) the person sees what your app will be able to see and that it saves files in its own folder in their Drive, can untick services (unticking all of them connects your app with its folder only), and sets a monthly spending limit for your app (100 US dollars unless they change it), then chooses Continue or Cancel. The token response's scope says which services they allowed. Later, on their account page under Apps, they can switch any of those services off (your app's next job for it is refused with 403), change the limit, or take access away. Nostrad emails them when your app has used 80% of their limit and when it reaches it, so they can raise it before your app's jobs are refused. To use a service they didn't allow, send them through sign-in again with it in scope: the new token also covers what they allowed before, and the consent page starts from the limit they already set.
Step 1: send the person to sign in
Make a random code_verifier (43 to 128 characters) and a random state, keep both on your side, then send the browser to:
https://accounts.nostrad.ai/authorize
?response_type=code
&client_id=<your client ID>
&redirect_uri=<a return address registered on the client, exactly>
&scope=image%20video
&state=<state>
&code_challenge=<BASE64URL(SHA-256(code_verifier))>
&code_challenge_method=S256
&resource=https%3A%2F%2Fgateway.nostrad.ai
Step 2: the person comes back
Nostrad sends the browser to your return address with code, state and iss. Check that state is the one you made and that iss is https://accounts.nostrad.ai (RFC 9207). If they chose Cancel, you get error=access_denied instead.
Step 3: swap the code for tokens
Web server client, with its secret as HTTP Basic credentials (client ID and secret each form-encoded first, RFC 6749 §2.3.1). Sending client_id and client_secret in the form body also works.
curl https://accounts.nostrad.ai/oauth/token \
-u "<client ID>:$NOSTRAD_CLIENT_SECRET" \
-d grant_type=authorization_code \
-d code=<code> \
-d redirect_uri=<the same return address> \
-d code_verifier=<code_verifier>
Phone, desktop or browser-only client: no secret, send client_id in the form instead of -u.
The answer:
{ "access_token": "...", "token_type": "bearer", "expires_in": 3600,
"refresh_token": "...", "scope": "image video", "user_id": "usr_4f1c9a..." }
Keep both tokens on your server, tied to that person's session in your app. Never send them to the browser.
Knowing who signed in. user_id is how your app recognises this person: save your data under it. It stays the same each time they sign in, on any device, even if they disconnect your app and come back. Another app gets a different ID for the same person, and it can't be used to find their email or name, which Nostrad doesn't give apps. Don't use the access token for this, since it changes. If the answer has no user_id, get it from GET /v1/key.
Step 4: refresh
curl https://accounts.nostrad.ai/oauth/token \
-u "<client ID>:$NOSTRAD_CLIENT_SECRET" \
-d grant_type=refresh_token \
-d refresh_token=<refresh token>
Use the new refresh token from each answer. Each refresh moves the end of the sign-in to six months on.
When a sign-in stops working
Write your app expecting that a refresh token can stop working. It stops when:
- the person takes your app's access away under Apps on their account page, or closes their account;
- it goes six months without being used;
- your app revokes it (below);
- the client it was made for is deleted (it works again if the client is restored within 30 days).
If Nostrad switches the person's account off, the Nostrad gateway answers 401 to their tokens until it's switched back on. If Nostrad switches your app off, its sign-ins stay, but every job is refused until it's switched back on.
A refresh that fails answers invalid_grant: send the person through sign-in again. Signing in again doesn't reset what they allowed.
Disconnecting someone. Call the token address with the refresh token when the person disconnects Nostrad in your app. That ends the whole sign-in, including its access tokens, and your app leaves their Apps list. Sending an access token ends only that access token; the refresh token keeps working and your app stays listed.
curl https://accounts.nostrad.ai/oauth/token \
-u "<client ID>:$NOSTRAD_CLIENT_SECRET" \
-d token=<refresh token>
The answer is 200 even when the token is unknown or already revoked.
Errors. The authorization and token addresses answer with standard OAuth errors as JSON: {"error": "...", "error_description": "..."}. On the return address they come as error and error_description in the query.
| Error | Where | Meaning | What to do |
|---|---|---|---|
invalid_request | authorize, token | A required part is missing or wrong, for example no code_challenge, a method other than S256, or a return address the client doesn't list | Fix the request |
invalid_client | token | The client ID or secret is wrong, or the client is deleted | Check the client on the console's Sign in with Nostrad page |
invalid_scope | authorize | A service isn't registered for your app | Ask only for services ticked under Services |
access_denied | return address | The person chose Cancel | Let them try again |
invalid_grant | token | The code or refresh token is wrong, expired, already used or revoked, or the code_verifier, client or return address doesn't match | Send the person through sign-in again |
unsupported_grant_type | token | grant_type isn't authorization_code or refresh_token | Fix the request |
server_error | any | A failure on Nostrad's side | Try again later |
On the Nostrad gateway, an access token that is expired, revoked or unknown gets 401. Refresh once, and if that answers invalid_grant, ask the person to sign in again.
4. The Nostrad gateway
Address https://gateway.nostrad.ai. Every command needs the person's access token, or one of your API keys:
Authorization: Bearer <access token or API key>
Your app sees only its own jobs and files for the signed-in person (with an API key: its own jobs and files for you). The gateway is for servers: it sends no CORS headers, so a browser page calls your own server, which calls the gateway.
| Command | What it does |
|---|---|
GET /v1/models | The models this token may use, with each model's inputs, settings and price |
POST /v1/quote | The most a job would cost: { model, inputs, params }, as for a job. Nothing runs and nothing is charged |
GET /v1/voices?model=<id> | The voices a speech model takes as voice_id |
GET /v1/key | What this key (or this sign-in) has used, and each limit that applies, the same fields as OpenRouter's key check |
POST /v1/jobs | Run a model: { model, inputs, params, webhook?, keep? }. 200 when done at once, 202 while it runs |
POST /v1/chat/completions | OpenAI's Chat Completions for chat models, streamed or not, with tools: a chat job underneath, charged and listed like one |
GET /v1/jobs/<id> | One job, as it is now: a running job is checked with the model when you read it |
POST /v1/jobs/<id>/cancel | Cancel a job that hasn't ended |
GET /v1/jobs | This app's jobs for this person, newest first, a page at a time: limit (up to 200, 50 if left out), cursor, start, end, state, model and job, as GET /v1/app/jobs takes them. With no start it goes back to the first job |
GET /v1/app/analytics | API key only: your whole app's requests over time, with counts of the people signed in to it, never who they are |
GET /v1/app/jobs | API key only: every job of your app, newest first, with no person and nothing they sent or got |
GET /files/<name> | A file in this app's folder for this person, or one the person picked for it (Range supported) |
POST /v1/files | Upload one file of up to 100 MB as the request body, into the app's folder |
GET /v1/files | This app's folder for this person, newest first (limit, cursor, path, bin=1, shared=1) |
GET /v1/files/<name> | One file's record |
PATCH /v1/files/<name> | Rename a file (name), move it inside the app's folder (path), or set its labels (app_properties, properties) |
DELETE /v1/files/<name> | Move a file to the bin |
POST /v1/files/<name>/restore | Take it out of the bin |
POST /v1/files/<name>/keep | Keep a temporary file in the person's Drive without sending it again (optional path) |
POST /v1/folders | Make an empty folder inside the app's folder |
GET /v1/files/<name>/link | The file's link anyone can open, or null |
POST /v1/files/<name>/link | Make that link (201), or get the one already there (200) |
DELETE /v1/files/<name>/link | Remove the link: it stops opening for everyone |
GET /v1/storage | The person's space: limit, used, remaining |
GET /v1/changes?cursor= | What changed among this app's files since the cursor |
POST /v1/uploads | Start an upload in parts, for a file over 100 MB |
PUT /v1/uploads/<id>/<n> | Part n |
GET /v1/uploads/<id> | Which parts arrived (to resume after a dropped connection) |
POST /v1/uploads/<id>/complete | Finish it |
DELETE /v1/uploads/<id> | Cancel it |
GET /v1/drive | The whole Drive, Nostrad's own apps only: how much space is used, and each app's folder with the app's name |
GET /v1/drive/changes?cursor= | What changed anywhere in the Drive since the cursor |
GET /v1/drive/changes/wait?cursor=&timeout= | Waits until something changes after the cursor, as Dropbox's longpoll does: { "changes": true } as soon as it does, or false after timeout seconds (30 to 480, 30 if left out). Then read the changes with the same cursor |
GET /v1/drive/files | One place or folder (place, app, path, q, type, sort, dir, since, cursor, folder_cursor, limit) |
GET /v1/drive/files/<name> | One file's record |
PATCH /v1/drive/files/<name> | Rename it (title), move it (to), or both |
DELETE /v1/drive/files/<name> | Move it to the Bin |
GET /v1/drive/files/<name>/content | Its bytes (Range and HEAD too) |
GET /v1/drive/files/<name>/thumbnail?size= | A picture's thumbnail: small, medium or large |
POST /v1/drive/files/<name>/restore | Take it out of the Bin |
POST /v1/drive/folders | Make a folder: { place, app?, path } |
PATCH /v1/drive/folders | Rename a folder (name) or move it (to) |
DELETE /v1/drive/folders?place=&app=&path= | Move a folder to the Bin |
POST /v1/drive/folders/restore | Take a folder out of the Bin |
POST /v1/drive/uploads | Start an upload, or with replaces a new version of a file |
PUT /v1/drive/uploads/<id>/<n> | Part n |
GET /v1/drive/uploads/<id> | Which parts arrived |
POST /v1/drive/uploads/<id>/complete | Finish it |
DELETE /v1/drive/uploads/<id> | Cancel it |
GET /.well-known/nostrad-webhooks.json | The public key that signs webhooks and purchase notifications (no token needed) |
GET /v1/products?ids=<a,b> | Selling: what your app has on sale, with prices (and, for a person's token, what they own) |
POST /v1/purchases | Start a purchase for the signed-in person: { product, quantity?, account_token?, return_url }. Answers the Nostrad page to send them to |
GET /v1/purchases | What the signed-in person owns in your app now (restore) |
GET /v1/purchases/voided | Your server: purchases refunded and taken back in the last 30 days |
GET /v1/purchases/<token> | Your server: one purchase, by its purchase token |
POST /v1/purchases/<token>/acknowledge | Your server: say you delivered it, within 3 days, or it is refunded |
POST /v1/purchases/<token>/consume | Your server: a consumable is used up, so it can be bought again |
POST /v1/purchases/<token>/consumption | Your server: your answer to a refund request |
POST /v1/purchases/<token>/cancel | Your server: stop a subscription renewing, { "type": "stop_renewals" | "stop_payments" }. Subscriptions |
POST /v1/purchases/<token>/revoke | Your server: end a subscription now and refund it, { "refund": "full" | "prorated" }. Subscriptions |
GET /v1/orders | Your server: your app's orders, newest first, 20 a page |
GET /v1/orders/<order_id> | Your server: one order, by the order ID the buyer sees |
POST /v1/orders/<order_id>/refund | Your server: refund an order in full or in part, and take it back or not |
POST /v1/notifications/test | Your server: send a test notification to your notifications address |
GET /v1/notifications/test/<test_token> | Your server: whether that test arrived |
GET /v1/notifications | Your server: the notifications sent in the last 180 days, and how each went |
The selling commands marked "your server" take an API key of the app with Sales ticked; the others take the person's sign-in token. Full guide: Selling inside your app.
Models
curl https://gateway.nostrad.ai/v1/models -H "Authorization: Bearer $TOKEN"
{ "models": [ { "id": "...", "label": "...", "modality": "image",
"inputs": [ { "key": "prompt", "kind": "text", "required": true } ],
"params": [ { "key": "aspect_ratio", "kind": "choice", "options": ["1:1", "16:9"], "default": "1:1" } ],
"price": [ { "unit": "image", "usd": "0.04" } ],
"available": true } ] }
- Use a model's
idexactly as listed. Don't hard-code a list: read it, since models are added. available: falsemeans the model can't run right now for this token: it is switched off, it has no price, or your app and way in (sign-in or API key) can't use it.- Each field has a
keyand akind:text,choice(one ofoptions),numberorinteger(betweenminandmax),flag(true or false),media(one file),media-list(several files) ormessages(a chat history). A field with adefaultcan be left out; arequiredone can't. A field Nostrad doesn't take is ignored and the job runs without it: a key a model doesn't list underinputsorparams, or anything besidemodelother thanmodel,inputs,params,webhook,keepandrequire_parameters. So a misspelt setting runs without it. To be told instead, send"require_parameters": truebesidemodel: then every such field is refused at once with 400invalid_fields, and nothing runs or is charged. - A media value is a
data:URL (base64), anhttps://address, or a file already in the person's Drive as its own address,/files/<name>(one in your app's folder, or one picked for it; see Files and storage), up to 25 MB each. A whole job request is at most 40 MB. - A speech model with a
voice_idsetting lists its voices atGET /v1/voices?model=<id>:{ "voices": [ { "id", "label", "type", ... } ] }. Send a voice'sidasvoice_id. Whenvoice_idis achoice, itsoptionsare the voices. - Chat models take
prompt, ormessagesas[{ "role": "user", "content": "..." }](rolessystem,user,assistant), and an optionalsystem.
Prices
To set your own price and show it to your customers, see Charging people for your app. What Nostrad checks before other people can use your app: App review rules.
Each model's price is a list of what one unit costs your caller, in US dollars as a decimal string, so no precision is lost: { "unit": "image", "usd": "0.04" }. It is the price this app's customers pay. price: null means the model has no price yet; unknown never means free, and such a model can't run.
| Unit | One unit is |
|---|---|
image, image_1k, image_2k, image_4k | One image made (at that size) |
edit, extra_input_image, input_image | One image edit; each input image past the first or past the free ones |
input_token, cached_input_token, output_token, video_token… | One token (makers quote these per million: multiply by 1,000,000). _long is the long-context price |
character | One character of text spoken |
second, second_768p, audio_second, input_video_second_… | One second of video or sound made, or of input video |
clip_720p_5s_audio and the like | One whole clip: resolution, length, and with or without sound |
song, clip | One song or one clip |
A job is charged for what it uses. When it starts, the most it can cost is held from the person's credit (with an API key, yours), and what it didn't use comes back when it ends. The total is rounded up once to a whole cent. A job that fails because of Nostrad costs nothing.
curl https://gateway.nostrad.ai/v1/quote -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" \
-d '{"model": "<id>", "inputs": {"prompt": "a lighthouse at dawn"}, "params": {"n": 2}}'
{ "model": "<id>", "max_usd": "0.08",
"lines": [ { "unit": "image", "units": 2, "usd_per_unit": "0.04" } ] }
max_usdis the most the job would cost, the amount held when it starts. Show it before your customer runs a job.- The request is checked as a job's is (400 for a bad setting, 404 for an unknown model). A media input is counted, not read: send its address, or any
https://placeholder. max_usd: nullwith adetailmeans the model has no price for that request yet.
Checking your limits
GET /v1/key answers for the token you call it with, with the same fields as OpenRouter's key check. Call it before a long task so you don't hit a limit partway through. Amounts are US dollars.
curl https://gateway.nostrad.ai/v1/key -H "Authorization: Bearer $TOKEN"
{ "data": {
"user_id": "usr_4f1c9a...", "label": "Server key", "via": "key",
"limit": 100, "limit_reset": "monthly", "limit_remaining": 87.5,
"usage": 40.2, "usage_daily": 1.1, "usage_weekly": 6.3, "usage_monthly": 12.5,
"expires_at": null,
"budgets": [
{ "scope": "api_key", "limit_usd": 100, "spend_usd": 12.5, "remaining_usd": 87.5, "reset_interval": "monthly", "resets_at": "2026-12-01T00:00:00.000Z" },
{ "scope": "account", "limit_usd": 100, "spend_usd": 30, "remaining_usd": 70, "reset_interval": "monthly", "resets_at": "2026-12-01T00:00:00.000Z" }
],
"effective_budget": { "scope": "account", "limit_usd": 100, "spend_usd": 30, "remaining_usd": 70, "reset_interval": "monthly", "resets_at": "2026-12-01T00:00:00.000Z" }
} }
user_idis who this is, to your app only: the person who signed in, or with an API key, you.limitis the key's monthly limit; with a sign-in token it is the limit the person set for your app, andlabelandexpires_atarenull.usage_dailycounts this UTC day,usage_weeklythis UTC week from Monday,usage_monthlythis UTC month. A job running now counts at the most it can cost until it ends.budgetslists each limit in the order a job is checked against them:api_keyorapp, thenaccount(the account's monthly spending limit, which rises as it buys credit).effective_budgetis the one that blocks first: one already spent, else the one with least left.- The credit balance isn't here. A job it can't cover answers 402.
Your app's activity
Two commands show your whole app: the jobs run with your API keys and those of every person signed in to it. They take one of your app's API keys; a person's sign-in token gets 403. The console's Usage and Logs pages show the same.
curl "https://gateway.nostrad.ai/v1/app/analytics?start=2026-11-01&timeframe=day" -H "Authorization: Bearer $NOSTRAD_API_KEY"
{ "app": "...", "start": "2026-11-01T00:00:00.000Z", "end": "2026-11-13T09:00:00.000Z", "timeframe": "day", "via": "all", "model": null,
"totals": { "request_count": 120, "success_count": 112, "user_error_count": 5, "error_count": 2,
"p50_prepare_duration": 1, "p75_prepare_duration": 2, "p90_prepare_duration": 4,
"p50_duration": 31, "p75_duration": 48, "p90_duration": 90, "active_people": 14 },
"time_series": [ { "bucket": "2026-11-01T00:00:00.000Z", "request_count": 9, ..., "active_people": 6 } ],
"people": { "shown": true, "minimum": 5, "active": 14, "new": 9, "returning": 5, "active_last_28_days": 17,
"retention": [ { "day": 1, "people": 9, "returned": 4 }, { "day": 7, "people": 6, "returned": 2 },
{ "day": 14, "people": null, "returned": null }, { "day": 28, "people": null, "returned": null } ] } }
startandendare ISO 8601 dates or date-times, end not included.enddefaults to now,startto 24 hours beforeend; at most 400 days apart.timeframeisminute,hour,day,week(from Monday) ormonth, in UTC; left out, it is picked from the range: minute under 2 hours, hour under 2 days, day under 64 days, week under 183 days, else month.via=signinorvia=keyandmodel=<id>narrow it.success_countis jobs that finished;user_error_countjobs that failed because of what was sent;error_countjobs that failed on Nostrad's side. A job still running counts only inrequest_count. Durations are seconds:prepare_durationis the wait before a job started,durationits run.- People are counted from jobs run through Sign in with Nostrad: a person is active when they ran at least one job.
newpeople ran their first job in your app in the range;returninghad run one before.active_last_28_dayscounts the 28 days up toend.retentiontakes the people whose first job was in the range and counts how many ran a job again exactly 1, 7, 14 and 28 days later (UTC days), counting only those for whom that day has come. - Counts of people show only when at least 5 people ran a job in the range (Apple's App Analytics does the same); otherwise
people.shownisfalsewith the reason, and eachactive_peopleisnull. A retention day or the last 28 days with fewer people than that isnulltoo. Nothing says who anyone is.
curl "https://gateway.nostrad.ai/v1/app/jobs?via=signin&state=failed&limit=50" -H "Authorization: Bearer $NOSTRAD_API_KEY"
{ "jobs": [ { "job_id": "job_...", "model": "...", "modality": "image", "via": "signin", "api_key": null, "yours": false,
"state": "failed", "error": "prompt: is required", "cost_cents": null,
"prepare_seconds": 1, "duration_seconds": 3, "created_at": 1794563000, "finished_at": 1794563004 } ],
"next_cursor": "1794562990:job_...", "start": "2026-10-14T09:00:00.000Z", "end": "2026-11-13T09:00:00.000Z" }
- Newest first;
startdefaults to 30 days beforeend.limitup to 200 (50 if left out); passnext_cursorback ascursorfor the next page,nullat the end.via,model,state(done,failed,processingorqueued),api_key=<key_...>(one key's jobs) andmodality(such asimageorvideo) narrow it.job=<id>finds one job whatever its date. api_keyis the key a job was run with.yoursistruefor a job run with your keys or by you signed in to your own app:GET /v1/jobs/<id>gives its results. A person's job never shows who they are, what they sent or what was made for them.erroris what your app was told when the job failed.cost_centsis what the job was charged, in US cents.usageis what a finished job used, in the units it was charged in, such as{ "image": 1 }.paramsis the settings a job of yours was sent; a person's job hasnull.
5. Running a job
curl https://gateway.nostrad.ai/v1/jobs \
-H "Authorization: Bearer $TOKEN" \
-H "content-type: application/json" \
-d '{"model": "<id from /v1/models>", "inputs": {"prompt": "a lighthouse at dawn"}, "params": {}}'
The answer is the job:
{ "job_id": "job_...", "model": "...", "modality": "image", "state": "done",
"outputs": [ { "url": "/files/job_..._0.png", "kind": "image", "mime": "image/png", "kept": false } ],
"error": null, "error_type": null, "retryable": null, "note": null, "usage": { "image": 1 },
"params": { "aspect_ratio": "1:1" }, "cost_usd": 0.04, "cost_cents": 4,
"cancel_requested_at": null, "created_at": 1759650000, "finished_at": 1759650012 }
params is the settings the job ran with: yours, with the model's defaults for any you left out. What you sent under inputs (a prompt, files) isn't kept, so it isn't here.
| state | Meaning |
|---|---|
queued, processing | Still running. Ask GET /v1/jobs/<job_id> again every few seconds (video can take minutes). Each read checks the job with the model, at most once every 5 to 10 seconds depending on the model, so asking faster than that answers the same. note may say where it is. GET /v1/jobs lists jobs as last checked; read one job for where it is now. |
done | Finished. outputs holds the results; cost_cents (and cost_usd, the same in dollars) is what the person was charged. |
failed | It didn't work. error says why (see Errors). Nothing was charged, unless a content check blocked it. |
- A chat job's text output carries
finish_reason, why the model stopped:stop(it finished),length(cut off atmax_tokensor the model's limit, so the text is incomplete),content_filter,tool_callsorerror. It's left out when the model didn't say. - A file output's
urlis a path on the gateway: fetchhttps://gateway.nostrad.ai/files/<name>with the same token, from your server. To show it in a page, serve it from your server or copy it to your own storage. - Files pass through by default. A result is a temporary file: download it and save it where your app keeps things. It leaves Nostrad 12 hours after Nostrad has finished sending all of it to your app in one
GET(aHEAD, aRangepiece or a download cut off on the way doesn't count), or after 7 days if it never does. Nostrad knows only that it sent the whole file, not that your app saved it, so save it as it arrives. To keep the results in the person's Drive instead, add"keep": true: they are kept in your app's folder when the person has switched on Let <your app> save files to my Drive (off until they do) and has room; otherwise they still arrive, as temporary files. Each file output carrieskeptsaying which. - A chat output is
{ "kind": "text", "mime": "text/plain", "text": "..." }. When the model asks your app to call a function, it also carriestool_calls, andtextmay be empty (see Chat Completions). - A chat model's
paramsare OpenAI's chat settings:max_tokens,temperature(0 to 2),top_p(0 to 1),stop(text, or up to 4),response_format,tools,tool_choice,parallel_tool_callsandreasoning_effort(none,minimal,low,medium,high,xhigh,max). One you leave out isn't sent. A model that doesn't take one answers 400 in words, and nothing is charged.messagestakes the rolessystem,developer,user,assistant(withtool_calls) andtool(withtool_call_id). - The person pays for each job from their Nostrad balance, within the monthly limit they set for your app. Before a job runs, the most it can cost is held; the job is charged what it used, never more.
- Jobs at once. Each account may have a few jobs running at the same time, counted across every app it uses: 2 for a new account, rising as it buys credit (5, 10, 20, then 40), as fal's concurrency limit does. The account is whoever pays: the signed-in person, or you for an API key's jobs. A job started while that many are running isn't run: it answers 429
concurrent_requests_limit, withmetadata.limitthe number that applies, nothing charged. Start it again when one of the running jobs ends (read it, or have a webhook tell you); the sameIdempotency-Keycan be used again.
Chat Completions (OpenAI-compatible)
For a chat model, POST https://gateway.nostrad.ai/v1/chat/completions takes and answers OpenAI's Chat Completions, as OpenRouter's does, so an OpenAI client library works with its base address set to https://gateway.nostrad.ai/v1 and your key or the person's token as its API key. It is a chat job underneath: the same price, hold and charge, the same limits, the same Idempotency-Key, and it shows in Logs. The completion's id is the job's ID, and model is the model's ID from GET /v1/models.
curl https://gateway.nostrad.ai/v1/chat/completions \
-H "authorization: Bearer <token or key>" \
-H "content-type: application/json" \
-d '{"model": "<a chat model's id>", "messages": [{"role": "user", "content": "What is the weather in Paris?"}],
"tools": [{"type": "function", "function": {"name": "weather", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}}}]}'
{ "id": "job_...", "object": "chat.completion", "created": 1759650000, "model": "...",
"choices": [ { "index": 0, "finish_reason": "tool_calls",
"message": { "role": "assistant", "content": null,
"tool_calls": [ { "id": "call_1", "type": "function", "function": { "name": "weather", "arguments": "{\"city\":\"Paris\"}" } } ] } } ],
"usage": { "prompt_tokens": 50, "completion_tokens": 10, "total_tokens": 60, "prompt_tokens_details": { "cached_tokens": 0 }, "cost": 0.01 } }
- Tools. Run the function yourself, then send the conversation again with the assistant's message (its
tool_calls) and one{ "role": "tool", "tool_call_id": "call_1", "content": "..." }per call. Nostrad never runs a function. - Settings. The chat settings above, by their OpenAI names;
max_completion_tokensis taken formax_tokens, and OpenRouter'sreasoning: { "effort": ... }forreasoning_effort. Any other field is ignored, unless you send"require_parameters": true, which refuses the request listing each one. - Streaming. With
"stream": truethe answer is a server-sent event stream ofchat.completion.chunklines as the model writes, eachdata: {...}: text inchoices[0].delta.content, a tool call in pieces inchoices[0].delta.tool_calls(byindex),finish_reasonon the last, then one more chunk withusage, thendata: [DONE]. Lines starting with:are comments: skip them. - Errors come as
{ "error": { "code": <status>, "message": "...", "type": "<Nostrad's code>", "metadata": { ... } } }, which OpenAI's libraries read aserror.message. A refusal before a stream begins is that, with its status. If the reply fails after the stream has begun, the status is already 200: the last chunk carrieserrorand"finish_reason": "error", no[DONE]follows, and the job is failed and free. - If your app stops reading a stream part way, the model's reply goes on for up to 30 seconds more (Cloudflare's limit for work after a caller leaves) and is charged what it used if it ends by then. One still going after that is cut off, failed and free.
- An image, video, speech or music model answers 400 here: send it to
POST /v1/jobs.
Trying again safely
If the connection drops after you send POST /v1/jobs, you can't tell whether the job started, and sending it again would run and charge it twice. To be safe, send a header with a value you make up for this one job, such as a UUID, and send the same value when you try again:
-H "Idempotency-Key: 8f14e45f-ceea-467f-a9f2-1c6a3e0b7d10"
- A repeat with the same key and the same body starts nothing and charges nothing. It answers the job the first request made, as it is now, with the header
Idempotent-Replayed: true. If that job failed, the repeat shows the failure: use a new key to run it again. - The same key with a different body answers 422
idempotency_key_reused. - If the first request was refused before anything started (no credit, a limit, a bad field), nothing is saved against the key, so you can use it again.
- A key is letters, digits,
-and_, up to 100. It belongs to one person in one app, and it is kept for as long as the job is.
Cancel a job
curl -X POST https://gateway.nostrad.ai/v1/jobs/<job_id>/cancel -H "Authorization: Bearer $TOKEN"
| Status | Answer | Meaning |
|---|---|---|
| 202 | { "status": "cancellation_requested" } | Asked. A job not started yet is stopped and nothing is charged. A job already running is stopped where the model allows it; otherwise it runs to its end and, if it finishes, is delivered and charged |
| 400 | { "status": "already_completed" } | The job is already done or failed |
| 404 | { "status": "not_found" } | No such job for this app and person |
A cancelled job ends failed with error: "cancelled by the app" and nothing charged. A job that finished anyway shows cancel_requested_at, the time you asked. Asking again is harmless.
Webhooks: be told when a job ends
Add "webhook": "https://your-server.example.com/nostrad" to POST /v1/jobs. When the job is done or failed, Nostrad POSTs this to that address, usually within a minute:
{ "job_id": "job_...", "app_id": "<your App ID>", "status": "OK",
"payload": { ...the job, as GET /v1/jobs/<job_id> shows it... },
"error": null }
statusisOKfor a done job andERRORfor a failed one, witherrorsaying why.- The address must be
httpsand public: an address inside a network (likelocalhost,10.0.0.1,192.168.x.x,.local,.internalor an IPv6 address) is refused with 400. - Answer with any 2xx to say you have it. If you answer with something else or don't answer within 15 seconds, it is sent again after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 24 hours, then no more. A redirect (3xx) is never followed and stops the sending.
- The same webhook can arrive more than once, so act on each
job_idonce, and only on ajob_idyour app submitted.
Every webhook is signed, so you can check it came from Nostrad and is for your app. It carries four headers:
| Header | What it is |
|---|---|
X-Nostrad-Webhook-Job-Id | The job's id |
X-Nostrad-Webhook-App-Id | Your App ID (the console's Overview shows it) |
X-Nostrad-Webhook-Timestamp | When it was sent, in seconds since 1970 (UTC) |
X-Nostrad-Webhook-Signature | An Ed25519 signature, in hex |
To check it:
- Fetch the public key from
https://gateway.nostrad.ai/.well-known/nostrad-webhooks.json(a JWKS:{ "keys": [ { "kty": "OKP", "crv": "Ed25519", "x": "...", "kid": "..." } ] }). Keep it; fetch it again only when a signature fails. - Refuse the webhook if the App ID isn't yours, or if the timestamp is more than 300 seconds away from your clock.
- Build the message: the job id, a newline, the App ID, a newline, the timestamp, a newline, and the SHA-256 of the raw request body as 64 lower-case hex characters.
- Check the signature over that message with each key in
keys; one must match. Read the body as JSON only after that.
// Checks a Nostrad webhook. Web Crypto only: Cloudflare Workers, Deno, Node 20 or later.
const MY_APP_ID = "<your App ID>";
const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
const bytes = (h) => new Uint8Array(h.match(/../g).map((x) => parseInt(x, 16)));
let keys = null, fetchedAt = 0; // the public keys: fetched once, again only when none matches (at most every 5 minutes)
async function verifies(signature, message) {
for (const k of keys ?? []) {
const key = await crypto.subtle.importKey("jwk", { kty: k.kty, crv: k.crv, x: k.x }, { name: "Ed25519" }, false, ["verify"]);
if (await crypto.subtle.verify({ name: "Ed25519" }, key, bytes(signature), message)) return true;
}
return false;
}
async function nostradWebhook(request) {
const jobId = request.headers.get("x-nostrad-webhook-job-id");
const appId = request.headers.get("x-nostrad-webhook-app-id");
const timestamp = request.headers.get("x-nostrad-webhook-timestamp");
const signature = request.headers.get("x-nostrad-webhook-signature");
const raw = await request.text();
if (!jobId || appId !== MY_APP_ID || !timestamp || !/^[0-9a-f]{128}$/.test(signature ?? "")) return null;
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return null;
const digest = hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(raw)));
const message = new TextEncoder().encode(`${jobId}\n${appId}\n${timestamp}\n${digest}`);
if (!(await verifies(signature, message))) {
if (Date.now() - fetchedAt < 300_000) return null; // not from Nostrad: answer 400
fetchedAt = Date.now();
keys = (await (await fetch("https://gateway.nostrad.ai/.well-known/nostrad-webhooks.json")).json()).keys;
if (!(await verifies(signature, message))) return null;
}
return JSON.parse(raw); // then act only on a job_id your app submitted
}
6. Files and storage
Every Nostrad account has one Drive, which the person opens at https://accounts.nostrad.ai/drive/: Apps (one folder per app), My files (their own files, any kind), Temporary (files passing through, which leave on their own), the Bin, and History (files that have left, with when and why). Every account starts with 1 GB of space. Your app has one place in it: its own folder, Apps / <your app>, holding every file it uploaded or a model made for that person. Your app reads and writes that folder, and the files the person picks for it (the picker), and nothing else.
- A file is kept in your folder only when your app asks (
"keep": trueon a job,x-keep: trueor"keep": trueon an upload), the person has switched on Let <your app> save files to my Drive (on their account page under Apps, or in your folder in their Drive; off until they do), and there is room. Otherwise it passes through: a job's result leaves 12 hours after Nostrad has finished sending all of it to your app (7 days if it never does), an upload 12 hours after it arrived. The person sees these under Temporary and can press Keep on one before it leaves.keptandleaves_aton every record say which. A file that has left answers410saying why. - To keep a temporary file your app already has (a job's result, an upload), for a Save to my Drive button, send
POST /v1/files/<name>/keepwith no body: nothing is sent again. To keep it in a folder, send{ "path": "Audio/Score" }; with nopathit goes to the folder it was sent to (x-path,pathorkeep_path), else the top. A title already in that folder takes the next free one, as an upload's does; on a file already kept,pathmoves it. The same rules hold: the person's Let <your app> save files to my Drive (403 keep_offwithout it) and room (403 storage_full). The answer (200) is the file's record, now withkept: trueandleaves_at: null; a file already kept answers the same. Only a file in your folder:409 in_binin the bin,403 not_yoursfor a file only picked for your app,410once it has left. It works while the person keeps what's in their files from your app, since keeping doesn't open the file. The changes list sayskept, also when the person presses Keep themselves. - The person can download, rename, move and bin the files in your folder, and put files in it. A file they move out to My files is gone for your app:
GET /v1/files/<name>answers 404 and the changes list saysmovedwithremoved: true. Moved back, it isaddedagain. - Your folder takes any kind of file, as My files does: Markdown, Word, spreadsheets, code, settings, archives, pictures, video, sound. Send its type in
content-type(any media type, such astext/markdown; none meansapplication/octet-stream); something that isn't a media type answers415. The file's name ends in the extension of its type, else ofx-file-name. One check: a file that says it's a picture, video, sound, 3D model, plain text, JSON, PDF or zip must really be one, since Nostrad reads those kinds from the bytes. A file sent asimage/pngwhose bytes aren't a PNG is refused with415 type_mismatchand nothing is kept. - Every record also carries
app_propertiesandproperties, your app's labels on the file ({}when none). - Every record carries what was found:
found_mime,widthandheightfor pictures,duration_mswhere the header says,risky: truewhen the file starts like a program or is titled like one (.exe,.bat,.js, ...),place(app) andpath(its folder inside yours,""at the top),shared: trueon a picked file. - Nostrad doesn't scan files for viruses. A file is served so a browser won't run it as a page (settings below):
GET /files/<name>answers the type the bytes say (plain bytes,application/octet-stream, when they disagree with what was declared or match no known type), withx-content-type-options: nosniff,content-security-policy: sandbox,cache-control: private, no-store, andcontent-disposition: inlinefor a picture, video or sound andattachment; filename*=UTF-8''<title>for anything else. Show a risky file's warning to your own users before they download it. A file a scan later marks answers403 malware.
A program that keeps its own files (settings, notes, saved work)
For a desktop program, a tool or a phone app that signs in to keep its own files in the person's Drive and nothing else, such as settings synced between computers:
- In the developer console, Create app. Under Services, untick everything and choose Save.
- Under Sign in with Nostrad, Create client of kind Phone, desktop or browser-only (no secret), with the return address
http://127.0.0.1/callback. At sign-in any port on it works (RFC 8252 §7.3): listen on a free port of127.0.0.1and sendhttp://127.0.0.1:<port>/callbackasredirect_uri. - Open the person's own browser (not a window inside your program, RFC 8252 §8.12) at
/authorizewith PKCE and noscope. The consent page shows your app's name, that it saves files in its own folder, and Continue; there's nothing to tick and no spending limit. - Swap the code for tokens with
client_idin the form and no secret, then keep the refresh token where the system keeps passwords (Windows Credential Manager, the macOS Keychain, Android's Keystore). Refresh the same way, withclient_id; each refresh gives a new refresh token. - Check
GET /v1/storage. Whilecan_keepisfalse, ask the person to switch on Let <your app> save files to my Drive athttps://accounts.nostrad.ai/account#apps: until then what you upload passes through and leaves after 12 hours. Kept files count toward their space (remaining). - Save a file:
POST /v1/fileswithx-keep: true,x-file-name,x-pathfor its folder (for exampleskills%2Faudit) and itscontent-type. Save a new version of it withPOST /v1/uploadsandreplacesplusrev(above), so a change made on another computer meanwhile becomes a conflicted copy instead of being lost. - Find files with
GET /v1/files?path=<folder>, or by labels you put on them; read one withGET /files/<name>. - Keep each computer in step with
GET /v1/changesand its cursor. - The files are the person's: they see them in their Drive under Apps → your app, and can open, change, move or bin them. Your changes list tells you when they do.
Storage settings
Everything that decides whether a file is kept, who sets it and where.
| Setting | Set by | Where | Default | What it does |
|---|---|---|---|---|
keep on a job | your app, per request | POST /v1/jobs with "keep": true (the console Playground's Keep the results in my Drive tick sends it) | false | Asks to keep the job's results in your folder. |
keep_path on a job | your app, per request | POST /v1/jobs with "keep_path": "Pictures/Coats" | "" (the top) | The folder inside yours the job's kept results go in, made as they arrive. The job's record says it. |
path on an upload | your app, per request | POST /v1/uploads with "path"; POST /v1/files with x-path | "" (the top) | The folder inside yours the upload goes in, made once it is kept. |
keep on an upload | your app, per request | POST /v1/uploads with "keep": true; POST /v1/files with x-keep: true | false | Asks to keep the upload in your folder. |
| Let <your app> save files to my Drive | the person, per app | their account page under Apps → Manage, or the top of your folder in their Drive | off | Without it your keep is ignored and files pass through. GET /v1/storage says it as can_keep. Turning it off keeps the files already kept. |
| Let <your app> open what's in my files | the person, per app | their account page under Apps → Manage, or the top of your folder in their Drive | on | Off, your app still lists, uploads, moves and bins their files and sees each one's name and size, but not what's in them (below). GET /v1/storage says it as can_open. |
| Keep (one file) | the person | a file under Temporary in their Drive | - | Keeps a file passing through, in your folder, if there is room. |
| Picked files | the person | the picker; Stop sharing under Apps → Manage | none | Which files outside your folder your app may read. |
Picker types and max | your app, per request | the picker address | every kind except files that look like programs; 1 | What the person may pick, and how many. |
| Free space | Nostrad | - | 1 GB per account | Space every account gets. Lowering it never deletes files; an account over it keeps its files and can't keep more until it has room. |
Set by Nostrad and the same for every app: a temporary result leaves 12 hours after Nostrad has finished sending all of it to your app in one GET (Nostrad can't tell whether your app saved it), or after 7 days if it never does; an upload that isn't kept leaves 12 hours after it arrived; the bin keeps a file 30 days; an unfinished upload lasts 7 days; a file is at most 5 GB.
Upload one file (up to 100 MB)
curl https://gateway.nostrad.ai/v1/files \
-H "Authorization: Bearer $TOKEN" \
-H "content-type: image/png" \
-H "x-file-name: holiday%20photo.png" \
--data-binary @photo.png
content-lengthis required.x-file-nameis optional and percent-encoded.x-keep: trueasks to keep it (see above);falseor no header lets it pass through. Any other value answers 400.- Optional
x-path, percent-encoded: the folder inside your app's folder the file goes in, such asRenders%2FMarch, so your app saves into a folder in one request instead of an upload and a move (Dropbox's upload takes the whole path; OneDrive's makes the path's folders as it goes). The folder and those above it are made once the file is kept; a file passing through keeps the path in its record and goes there if it is kept later. The path's rules are those ofPATCHbelow. - Optional
x-content-hash: the file's Dropbox-style content hash (SHA-256 of each 4 MiB block, then SHA-256 of those digests joined, as 64 hex characters). If it doesn't match what arrived, nothing is kept (400content_hash_mismatch). - The answer (201) is the file's record:
name,url,title,mime,found_mime,size,source,job_id,kept,content_hash,place,path,risky,malware,width,height,duration_ms,shared,created_at,updated_at,binned_at,leaves_at. - An upload that isn't kept waits 12 hours, as an input for a job; at most 5 GB of them can wait at once.
leaves_atsays when a file leaves;nullmeans it stays.
Rename, folders and a file as a job's input
curl -X PATCH https://gateway.nostrad.ai/v1/files/<name> \
-H "Authorization: Bearer $TOKEN" -H "content-type: application/json" \
-d '{"name": "holiday 2026.png", "path": "trips/2026"}'
nameis the title the person sees; the file'snamein its address never changes.pathis a folder inside your app's folder, made as you go (names joined by/, each up to 255 characters, at most 100 deep, and at most 400 characters for the whole path with the file's name);""is the top. Two files in one folder can't have one title: renaming or moving onto a title already there is409 exists, and a new file sent with one is kept under the next free title,photo (2).png, which its record says.GET /v1/files?path=trips/2026lists one folder; with nopath, everything in your folder.- An empty folder:
POST /v1/folderswith{ "path": "Renders/March" }makes it and those above it (Dropbox'screate_folder). A new one answers 201, one already there 200, both{ path, made }. A folder stays in the person's Drive, so it needs Let <your app> save files to my Drive (403 keep_offwithout it). Folders also appear on their own when a kept file is sent to one. - A file picked for your app can be read but not changed:
PATCH,DELETEandrestoreon it answer403 not_yours. - Where a model takes media, send a file's own address instead of its bytes:
"image": "/files/<name>", for a file in your folder or one picked for your app. Any other name answers400 not_your_file.
Labels on a file
A file sits in one folder, but your app can keep its own labels on it, such as which characters and which project a picture belongs to, the way Google Drive's custom file properties work. Every file's record has two objects of "key": "value":
app_properties: your app's own. Only your app ever sees them (Drive'sappProperties, "private to the requesting app").properties: seen by every app that can reach the file, such as another app the person picks it for (Drive'sproperties, "visible to all apps").- Set them with
PATCH /v1/files/<name>:{ "app_properties": { "character": "Mara", "project": "Winter" }, "properties": { "scene": "4" } }. Keys you leave out stay as they are, andnullremoves a key. They can go with a rename or move in the same request. - Or send them when the file is made:
x-app-propertiesandx-propertiesonPOST /v1/files(each a JSON object, percent-encoded),app_propertiesandpropertiesonPOST /v1/uploadsandPOST /v1/files/<name>/keep, andfile_app_propertiesandfile_propertiesonPOST /v1/jobs(every file the job makes gets them; the job's record shows them). - Find files by them:
GET /v1/files?app_property=character%3DMaralists the files with that key and value (Drive'sappProperties has { key='…' and value='…' });?app_property=characterlists those with the key, whatever its value;?property=does the same forproperties. Several together must all match, and they work withpath,bin=1andshared=1. - Google's limits: at most 30
app_propertiesfrom your app and 30propertieson one file, 100 in all, and each key with its value at most 124 bytes in UTF-8. Over a count is400 too_many_properties; too long is400 property_too_long. Values are text; a key can't contain=or control characters. - Only your app's own files: on a file only picked for it,
PATCHanswers403 not_yours. The labels stay while a file is in the bin, while it is moved or renamed, and while the person keeps what's in their files from your app (they are your app's words about the file, not what is in it). They go when the file is deleted for good. A change shows in the changes list asproperties. The person doesn't see them in their Drive, as in Google Drive.
The picker: files from the rest of the person's Drive
To use a file the person keeps elsewhere in their Drive, your app lets them choose it in Nostrad's picker, as Google's Drive Picker does: the person sees their Drive, ticks files, and your app gets exactly those. Nothing else of their Drive is ever visible to your app.
- Open, in a popup or the system browser (never a web view inside your app),
https://accounts.nostrad.ai/pick?client_id=<your client ID>&redirect_uri=<a return address registered on that client>&state=<a value you check on return>. Optional:types=image,video,audio,other(one or more;anyalso offers files that look like programs; anything else is refused) andmax=<how many, 1 or more; 1 if you leave it out>. Only files of those kinds can be picked, and a pick is all the ticked files or none. Each picker page can be answered once, by the account signed in, within 30 minutes; the return address andstateare always the ones the page was opened with. The client ID and return addresses are those of Sign in with Nostrad; the person must already have connected your app with it. - The person logs in if needed, sees their places (My files and each app's folder; never the bin or temporary files), searches, ticks files, and chooses Pick or Cancel.
- Nostrad sends the browser back to your return address with
?state=<your value>&picked=<name>,<name>, or?state=...&error=cancel(error=not_connectedwhen the person hasn't connected your app yet). A web app's return page passes the names to the page that opened the picker; a phone or desktop app registers its own return address as it does for sign-in. - Your app then reads each file like its own:
GET /v1/files/<name>(withshared: true),GET /files/<name>, or as a job's input;GET /v1/files?shared=1lists every file picked for it, including files the person picked from a shared space they are in. Your app reads a file from a shared space only while the person still could: they are still in the space, may still download there, and aren't kept out by a folder with limited access; the file isn't in the space's Bin. Otherwise it answers 404. A pick lasts until the person stops sharing the file (under Apps on their account page, or by removing your app's access) or deletes it for good; then it answers 404 and the changes list saysunsharedwithremoved: true. A picked file in the person's bin still reads until it is gone for good.
Bigger files, in parts (up to 5 GB)
POST /v1/uploadswith{ "type": "video/mp4", "size": <bytes>, "name": "clip.mp4" }(optionalpart_size, a multiple of 4 MiB, default 8 MiB; optionalcontent_hash; optional"keep": true; optional"path", the folder inside yours, asx-pathabove). The answer givesupload_id,part_sizeandparts.PUT /v1/uploads/<upload_id>/<n>for n = 1 toparts, each exactlypart_sizebytes except the last.POST /v1/uploads/<upload_id>/complete. The answer (201) is the file's record.- Connection dropped:
GET /v1/uploads/<upload_id>lists the missing parts; send only those. An unfinished upload is dropped after 7 days.
Bin, space and keeping in step
DELETE /v1/files/<name>moves a file to the bin for 30 days;POST /v1/files/<name>/restorebrings it back. Apps can't delete a file for good; the bin empties itself after 30 days, and the person can empty it or delete a file for good at any time.- A new version of a file in your own folder:
POST /v1/uploadswith{ "replaces": "<name>", "rev": "<the file's rev>", "type": ..., "size": ... }and optional"note"(up to 1,023 characters), then send the parts and complete as for any upload. The file keeps its name, and the old contents become an older version the person can restore. If the file has moved on fromrev, your bytes become a new file beside it,<name> (conflicted copy), withconflicted: true; with norevyou save over whatever is current.revis in every file's record, and isnulluntil a file's first new version. It takes the person's Drive space with no temporary fallback:403 keep_offif they haven't let your app save,403 storage_fullwith no room,409 not_keptfor a temporary file,403 not_yoursfor a file only picked for your app. GET /v1/storage:limit,usage,remaining,state(none,normal,nearing,critical,exceeded),usage_in_bin,app_usage(your folder),place_usage(app: your folder,mine: the person's My files),can_keep(the person's switch for your app:falsemeans anything you ask to keep passes through),can_open(falseonce the person keeps what's in their files from your app, below). Files in the bin count. Never another app's files.GET /v1/changeswith no cursor gives the current cursor. Later,GET /v1/changes?cursor=<cursor>gives what changed since:changes(each{ name, what, at, removed, file };whatisadded,renamed,moved,binned,restored,deleted,shared,unshared,updated(a new version was saved:/files/<name>now answers the new contents),kept(a temporary file is now kept in the person's Drive) orproperties(its labels changed);fileis the file's record as it is now, ornullwithremoved: trueonce your app can't reach it: deleted, moved out of your folder, or no longer picked for it), a newcursor, andmore(ask again with the new cursor while it is true). A cursor older than 30 days answers 410cursor_expired: list the files again from the start.- The storage commands allow 600 requests a minute per person per app; over that they answer 429
rate_limitedwithretry-after. - Error codes the storage commands name in
error:storage_full,type_mismatch,content_hash_mismatch,exists,not_yours,not_your_file,not_kept,keep_off,malware,contents_hidden,too_many_properties,property_too_long,cursor_expired,rate_limited.
Links to your app's files
As Dropbox's create_shared_link_with_settings, an app can give a file in its own folder a link that anyone can open, with no Nostrad account. It is the same link the person sees under Share in their Drive, so they can remove it there too, and every Drive rule holds.
POST /v1/files/<name>/linkanswers{ "link": { "id", "url", "created_at" } }: 201 when it is new, 200 when the file already had one (one link per file).GETanswers the same, or{ "link": null }, withready(falsewhile Nostrad's file host isn't switched on).DELETEanswers{ "removed": "<link id>" }, or 404no_link.- Add
?dl=1to the link to download the file, or?raw=1to get the file itself without the page (a redirect, so follow redirects), as Dropbox's links do. - With Sign in with Nostrad, ask for the scope
sharing("Share the files it saves for you, by link or with people you choose"), ticked under Services in the console; without it these answer 403insufficient_scope. With your API key the files are your own, so nothing more is asked. - Only a kept file in your app's folder: 409
not_keptfor a temporary one, 409in_binin the bin, 403not_yoursfor a file only picked for your app, 403malwarefor one taken down, 429links_pausedfor a day after the person's links sent too much, 503links_not_readybefore the file host is switched on, 403contents_hidden(forGETandPOST) once the person keeps what's in their files from your app, since anyone with the address can open it (below).
Sharing your app's files with people
As Google's Drive sharing dialog ("invoked from your app to allow sharing of items on Drive"), your app opens Nostrad's own Share for a file in its folder, and the person chooses who gets it there. Your app never sees who: no email address, name or account reaches it.
- Open, in a popup or the system browser (never a web view inside your app),
https://accounts.nostrad.ai/share?client_id=<your client ID>&redirect_uri=<a return address registered on that client>&state=<a value you check on return>&file=<name>. The client ID and return addresses are those of Sign in with Nostrad. - The person logs in if needed, and their Drive opens at your app's folder with Share open for the file: people, access (Viewer, Commenter or Editor), an end date and a message, the same dialog as anywhere in their Drive.
- When they close it, Nostrad sends the browser back to your return address with
?state=<your value>and nothing else, as Google's dialog tells the app nothing. If it can't open, there is a page saying why with a way back, which returns?state=...&error=:not_connected(the person hasn't connected your app),insufficient_scope(no scopesharing, as for links),not_found(not a file in your app's folder),not_kept(a temporary file) orin_bin. - Each request can be finished once, by the account it was opened for, within 30 minutes. A request with an unknown client or a return address not registered on it gets a page here and is never sent back.
Someone who doesn't know the person sharing (they have never shared with each other, asked each other for access, or been in the same family, shared space or group) gets the share as a request, as a message request on X or Messenger: it waits in their Requests, and nothing of it opens until they accept. Each person can instead take such shares straight away, or not at all; with the second, Share says it can't share with them and shares nothing. Building a chat or messaging app on this? Your app keeps its own messages and is answerable for them; files sent this way still pass through each person's Requests.
Letting people save files to your folder
As Dropbox's Saver ("the easiest way to add files to your users' Dropboxes", which "opens in a pop-up window"), your app opens Nostrad's own Save window and the person uploads files from their device straight into your app's folder, so your app never holds them on the way.
- Open, in a popup or the system browser,
https://accounts.nostrad.ai/save?client_id=<your client ID>&redirect_uri=<a registered return address>&state=<your value>, with optionalpath=<a folder inside your app's folder>. The person must have connected your app with Sign in with Nostrad; no other scope is asked. - Their Drive opens at your app's folder (or that folder) with Save files for <your app> open: Choose files, as many times as they like, then Done, or Cancel. The files are theirs, kept in your folder and counted in their space.
- When they close it, Nostrad sends the browser back with
?state=<your value>if anything was saved, as the Saver'ssuccesspasses nothing, or?state=...&error=cancelif nothing was, as itscancel. Find the new files withGET /v1/changesorGET /v1/files. If it can't open:error=not_connected.
Showing a file without reading it
Your app opens Nostrad's own viewer for a file in its folder: https://accounts.nostrad.ai/view?client_id=&redirect_uri=&state=&file=<name>, in a popup or the system browser. The person sees the file in their Drive's viewer (pictures, video, sound, PDFs, text and Office files; anything else offers a download), and closing it sends the browser back with ?state=<your value>. Errors as for sharing: not_connected, not_found, in_bin. It is a window rather than a frame in your page: Dropbox's Embedder frames only a shared link, which anyone with the address can open, your app included.
When the person keeps what's in their files from your app
Each person has a switch for your app, Let <your app> open what's in my files, on until they turn it off. Off:
- Your app still lists, uploads, renames, moves and bins their files, saves new versions, opens Share, Save and View, and sees each file's record with its name and size, as Dropbox's Chooser gives an app a file's
nameandbytes;content_hashisnull. GET /files/<name>, a file as a job's input, andGETorPOST /v1/files/<name>/linkanswer 403contents_hidden, for files in your folder and files picked for it alike.- Check
can_openinGET /v1/storagebefore asking for contents, and show files with View instead.
The whole Drive (Nostrad's own apps)
The /v1/drive commands reach everything in a person's Drive, as Google's restricted scope "View and manage all your Drive files" does. Only an app Nostrad has marked can ask for the drive scope: its own sync and phone apps. Your app can't: use your app's folder and the file picker above. An API key never has it, and the token stops carrying it as soon as the person or Nostrad takes it away.
7. Selling inside your app
Sell things inside your app, such as coins, a level or a feature, to people who signed in with Nostrad. They pay from their Nostrad credit on a Nostrad page, as on Google Play or the App Store; you get 70% of the price and Nostrad keeps 30%. It works like Google Play Billing:
- Make the products under Monetize in the developer console, and an API key with Sales ticked for your server.
- Your app lists them (
GET /v1/products) and starts a purchase with the person's token (POST /v1/purchases), then sends their browser to thepurchase_urlit gets back. - They choose Buy. Nostrad sends their browser back to your
return_urlwithpurchase_tokenadded, if that address is one of your sign-in client's return addresses, and tells your server with a signed notification. - Your server checks the purchase (
GET /v1/purchases/<token>), delivers it, and acknowledges it within 3 days (POST /v1/purchases/<token>/acknowledge), or consumes a consumable so it can be bought again. A purchase not acknowledged in 3 days is refunded and taken back.
Refunds, refund requests, notifications, test purchases and every field are in Selling inside your app. The API definition is in openapi.json (OpenAPI 3.1).
8. Errors
A refused request answers JSON { "error": "...", "detail": "..." }. error is a code to branch on and is always there: the reason's own (such as over_limit or no_route), or else the status's type: invalid_request_error (400 and any other 4xx below), authentication_error (401), billing_error (402), permission_error (403), not_found_error (404), conflict_error (409), request_too_large (413), rate_limit_error (429), api_error (500, 502, 503) and timeout_error (504). detail is words for a person: don't parse it. New codes may be added.
Every refusal also has an x-should-retry header, true or false: whether sending the same request again can work. It's true for 408, 429 and 5xx, except where the answer keeps failing until something changes (the account's monthly limit, a model with no price yet, a supplier at its limit for the month), and false for everything else. The Retry column below says the same. Wait between tries, longer each time: retry-after seconds when it is given, otherwise 1 second, doubling up to 60.
A job that fails answers the job, with state: "failed", its error (words), error_type and retryable:
error_type | Meaning | retryable |
|---|---|---|
invalid_request | Something in the request the model didn't take; error says what | false: fix the request |
content_policy_violation | The model's content check blocked it. Charged its listed price | false |
nostrad_error | "Nostrad error": something went wrong on Nostrad's side, not with the request. Nothing was charged | true, after a wait |
A job read while it is queued, running or done has error_type and retryable null. Job webhooks and GET /v1/app/jobs carry the same two fields. If it fails while it's starting, that answer comes with an error status, 502 when it's Nostrad's fault and otherwise the status in the table below, so a program that stops at any error status has to read the body. The same job read later answers 200. Nothing is charged for a failed job, with one exception: a job blocked by a content check is charged its listed price, the same as a job that finished, and cost_cents shows the amount. To try a failed job again, start it again with a new Idempotency-Key: the same key answers the same failed job.
Every answer, a refusal too, has an x-request-id header (req_ and 24 letters and digits). Keep it with your logs: when you ask about a call that made no job, quote it; for a job, quote its job_id.
| Status | Meaning | What your app does | Retry |
|---|---|---|---|
| 400, 409, 413, 415, 422 | Something in the request: a missing input, a value out of range, too large, a file type not taken, or an Idempotency-Key used before with a different body (idempotency_key_reused). A field that's wrong answers 400 invalid_fields, with metadata.invalid_fields listing each one as { "type", "field", "description" }: type is required, invalid_value or additional_property_not_allowed, and field is where it is, such as params.duration | Fix the request; detail says what. Branch on type and field, not on the words | No |
| 401 | No token, or it ran out or was taken away; or an API key that is wrong, deleted or expired | Refresh the token; if that fails, sign the person in again. For a key: check it under API keys | No |
| 402 | Not enough credit. metadata carries limit_source nostrad_credits, scope account and remedy_hint, as OpenRouter's 402 does | Tell the person. The error ends with the page where they add it, https://accounts.nostrad.ai/account#credit: show it or link to it. They can also turn on Auto top-up there, so it doesn't happen again. For a key: the same, on your own account | No |
| 403 (limit) | The monthly limit for your app (or for the API key) is reached: error is over_limit, the words end $X of $Y used; resets <time>., and metadata carries limit_source, scope, limit_usd, spend_usd, resets_at and remedy_hint, as OpenRouter's budget errors do (details) | For your app's limit, the person changes it under Apps on accounts.nostrad.ai. For a key, raise the key's limit under API keys. Or wait for resets_at | No |
| 403 | A service the person (or the key) doesn't allow, access taken away, the model refused the content, an API key used from an address it isn't allowed from, a model that needs Sign in with Nostrad, an app that is still personal (only its developer can use it until Nostrad verifies it), or an adult model on an app that doesn't allow adult models | Show detail to the person | No |
| 403 (age) | An app rated 18+, or an adult model, for a person whose Nostrad account doesn't say they're 18 or over: error is age_restricted. For an API key, the key's owner | Show detail: it says where they add their date of birth, under Account details on accounts.nostrad.ai | No |
| 404 | An unknown model, or something that isn't this app's | Check the id | No |
| 410 | A file that has left Nostrad (a temporary file past its hours, or deleted); detail says why | Don't ask again | No |
| 429 | Too many storage requests, or more than about 600 job starts or 3,000 other requests in a minute for one account, all its keys together (rate_limited) | Wait retry-after seconds, longer after each refusal | Yes |
| 429 | The account paying already has as many jobs running as it may (this account already has 2 jobs running, the most it can run at once; start this one again when one of them ends; error concurrent_requests_limit, metadata with limit_source nostrad_jobs_at_once and limit). See Jobs at once | Start the job again when one of the running ones ends. Nothing was charged | Yes, when one ends |
| 429 | The account paying has reached its monthly spending limit (this account has reached its monthly spending limit of ...; error account_limit, the same metadata with limit_source nostrad_account_limit) | Show detail to the person: it says the limit, the day it comes back and what raises it. It isn't the same as running out of credit | No: it keeps failing until the day in detail |
| 403, 404, 409 (selling) | error names the reason, as Google Play does: needs_sign_in, sales_permission_needed, billing_unavailable, unavailable, already_owned, not_owned, already_refunded, refund_too_old, no_refund_request, no_notify_url; 400 developer_error for a request that isn't valid, and invalid_purchase_state for acknowledging a consumed purchase | See Selling errors | No |
| 500 | The Nostrad gateway hit an error of its own (api_error). Nothing was done or charged | Try again later; if it keeps happening, quote the x-request-id | Yes, after a wait |
| 502 | "Nostrad error": something went wrong on Nostrad's side, not with the request. Nothing was charged | Try again later, with a new Idempotency-Key | Yes, after a wait |
| 503 | The model is switched off or busy right now (no_route, try_again) | Try again later, or another model | Yes, after a wait |
| 503 | The model can't run until Nostrad changes something: no price for it yet (unpriced), your app's price below Nostrad's (price_below_base), or its supplier at Nostrad's limit for the month (route_budget) | Use another model. For price_below_base, raise your app's Price under App settings | No |
Getting help
- Is a model running? The console's Models page says whether each one is running now, and so does
availableinGET /v1/models. - What went wrong with a job? The console's Logs page shows each job of your app with its state and error.
- Anything else: an account, credit or a charge, a refund, or something these pages don't answer. Email support@nostrad.ai. Say your App ID, and for a job its
job_id; for a call that made no job, itsx-request-idand the time (UTC). Never send an API key, a client secret or a token: Nostrad never asks for one.
9. Example: a server that signs people in and runs a job
A whole web app in one file, ready to deploy as a Cloudflare Worker: a person signs in with Nostrad, picks an image model, types a prompt and sees the picture, paid from their own Nostrad balance. It uses only fetch, Web Crypto and one KV namespace for its storage (sign-ins in progress and each person's tokens), and it never sends a token to the browser: the browser holds only a random session cookie.
// worker.js: sign people in with Nostrad, then make an image for them.
// Needs: a KV namespace bound as STORE, NOSTRAD_CLIENT_ID (a variable) and NOSTRAD_CLIENT_SECRET (a secret).
const NOSTRAD = {
issuer: "https://accounts.nostrad.ai",
authorize: "https://accounts.nostrad.ai/authorize",
token: "https://accounts.nostrad.ai/oauth/token",
gateway: "https://gateway.nostrad.ai",
};
const CALLBACK = "/oauth/nostrad/callback"; // registered on the client as https://<your address>/oauth/nostrad/callback
const DAY = 86400;
const b64url = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf)))
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const random = (n) => b64url(crypto.getRandomValues(new Uint8Array(n)));
const escape = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => "&#" + c.charCodeAt(0) + ";");
const page = (body, status = 200, headers = {}) => new Response(
`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>My app</title>${body}`,
{ status, headers: { "content-type": "text/html; charset=utf-8", ...headers } });
const go = (to, headers = {}) => new Response(null, { status: 303, headers: { location: to, ...headers } });
const COOKIE = "; Path=/; HttpOnly; Secure; SameSite=Lax";
class SignInAgain extends Error {}
export default {
async fetch(request, env) {
const url = new URL(request.url);
const sid = /(?:^|;\s*)sid=([A-Za-z0-9_-]{43})/.exec(request.headers.get("cookie") ?? "")?.[1];
const session = sid ? await env.STORE.get("session:" + sid, "json") : null;
try {
if (url.pathname === "/login") return go(await signInAddress(env, url));
if (url.pathname === CALLBACK) return await callback(env, url);
if (url.pathname === "/logout") {
if (sid) await env.STORE.delete("session:" + sid);
return go("/", { "set-cookie": "sid=; Max-Age=0" + COOKIE });
}
if (!session) return page('<p><a href="/login">Sign in with Nostrad</a></p>');
const call = (path, init) => gateway(env, sid, session, path, init);
if (url.pathname === "/") return await home(call);
if (url.pathname === "/make" && request.method === "POST") return await make(call, await request.formData());
const job = /^\/jobs\/([A-Za-z0-9_-]{1,100})$/.exec(url.pathname);
if (job) return await showJob(call, job[1]);
const file = /^\/jobs\/([A-Za-z0-9_-]{1,100})\/(\d{1,3})$/.exec(url.pathname);
if (file) return await output(call, file[1], Number(file[2]));
return page("<p>Not found.</p>", 404);
} catch (e) {
if (e instanceof SignInAgain) return go("/login");
return page(`<p>${escape(e.message)}</p><p><a href="/">Back</a></p>`, 500);
}
},
};
// 1. Sign in: keep a code_verifier under a random state for ten minutes, send the browser to Nostrad.
async function signInAddress(env, url) {
const verifier = random(32), state = random(16);
const challenge = b64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
await env.STORE.put("flow:" + state, verifier, { expirationTtl: 600 });
return NOSTRAD.authorize + "?" + new URLSearchParams({
response_type: "code", client_id: env.NOSTRAD_CLIENT_ID, redirect_uri: url.origin + CALLBACK,
scope: "image", state, code_challenge: challenge, code_challenge_method: "S256", resource: NOSTRAD.gateway,
});
}
function tokenCall(env, fields) {
const basic = btoa(encodeURIComponent(env.NOSTRAD_CLIENT_ID) + ":" + encodeURIComponent(env.NOSTRAD_CLIENT_SECRET));
return fetch(NOSTRAD.token, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded", authorization: "Basic " + basic },
body: new URLSearchParams(fields),
}).then(async (r) => { if (!r.ok) throw new Error("Nostrad refused the sign-in (" + r.status + ")"); return r.json(); });
}
// 2. The return address: check state and iss, swap the code for tokens, keep them under a new session.
async function callback(env, url) {
const q = url.searchParams;
if (q.get("error")) return page(`<p>Not signed in (${escape(q.get("error"))}).</p><p><a href="/login">Try again</a></p>`, 400);
if (q.get("iss") !== NOSTRAD.issuer) return page("<p>That sign-in didn't come from Nostrad.</p>", 400);
const key = "flow:" + q.get("state");
const verifier = await env.STORE.get(key);
if (!verifier) return page('<p>That sign-in ran out. <a href="/login">Sign in again</a></p>', 400);
await env.STORE.delete(key);
const t = await tokenCall(env, { grant_type: "authorization_code", code: q.get("code"),
redirect_uri: url.origin + CALLBACK, code_verifier: verifier });
const sid = random(32);
await save(env, sid, { user: t.user_id, access: t.access_token, refresh: t.refresh_token, until: Date.now() + t.expires_in * 1000 });
return go("/", { "set-cookie": `sid=${sid}; Max-Age=${180 * DAY}` + COOKIE });
}
const save = (env, sid, s) => env.STORE.put("session:" + sid, JSON.stringify(s), { expirationTtl: 180 * DAY });
// 3. A gateway call with the person's token: refreshed when it has run out (keeping the new
// refresh token), and back to sign-in when the sign-in has ended.
async function gateway(env, sid, s, path, init = {}) {
if (Date.now() > s.until - 60_000) {
const t = await tokenCall(env, { grant_type: "refresh_token", refresh_token: s.refresh }).catch(() => null);
if (!t) { await env.STORE.delete("session:" + sid); throw new SignInAgain(); }
Object.assign(s, { access: t.access_token, refresh: t.refresh_token ?? s.refresh, until: Date.now() + t.expires_in * 1000 });
await save(env, sid, s);
}
const r = await fetch(NOSTRAD.gateway + path, { ...init, headers: { ...init.headers, authorization: "Bearer " + s.access } });
if (r.status === 401) { await env.STORE.delete("session:" + sid); throw new SignInAgain(); }
return r;
}
// 4. The page: the image models running now, and a prompt.
async function home(call) {
const { models } = await (await call("/v1/models")).json();
const running = models.filter((m) => m.modality === "image" && m.available);
if (!running.length) return page('<p>No image model is running right now.</p><p><a href="/logout">Sign out</a></p>');
return page(`<form method="post" action="/make">
<select name="model">${running.map((m) => `<option value="${escape(m.id)}">${escape(m.label)}</option>`).join("")}</select>
<input name="prompt" required maxlength="1000" placeholder="a lighthouse at dawn"> <button>Make</button>
</form><p><a href="/logout">Sign out</a></p>`);
}
// 5. Start the job. A refusal (no credit, a limit) has no job: show its words, which say what to do.
async function make(call, form) {
const r = await call("/v1/jobs", { method: "POST", headers: { "content-type": "application/json" },
body: JSON.stringify({ model: form.get("model"), inputs: { prompt: form.get("prompt") } }) });
const job = await r.json();
if (!job.job_id) return page(`<p>${escape(job.detail)}</p><p><a href="/">Back</a></p>`, r.status);
return go("/jobs/" + job.job_id);
}
// 6. The job's page: it reloads itself while the job runs.
async function showJob(call, id) {
const r = await call("/v1/jobs/" + id);
if (!r.ok) return page("<p>No such job.</p>", 404);
const job = await r.json();
if (job.state === "queued" || job.state === "processing") return page('<meta http-equiv="refresh" content="3"><p>Making it...</p>');
if (job.state === "failed") return page(`<p>${escape(job.error)}</p><p><a href="/">Back</a></p>`);
return page(job.outputs.map((o, i) => `<p><img src="/jobs/${id}/${i}" alt="" style="max-width:100%"></p>`).join("") +
`<p>${job.cost_cents === null ? "" : job.cost_cents + " credits. "}<a href="/">Make another</a></p>`);
}
// 7. A result's bytes, read with the person's token (a result address needs it), passed to the browser.
async function output(call, id, n) {
const job = await (await call("/v1/jobs/" + id)).json();
const out = job.outputs?.[n];
if (!out?.url) return page("<p>Not found.</p>", 404);
const f = await call(out.url);
return new Response(f.body, { status: f.status, headers: { "content-type": f.headers.get("content-type") ?? "application/octet-stream",
"x-content-type-options": "nosniff", "content-security-policy": "sandbox", "cache-control": "private, max-age=3600" } });
}
Its settings file, beside it:
// wrangler.jsonc
{
"name": "my-nostrad-app",
"main": "worker.js",
"compatibility_date": "2026-11-01",
"vars": { "NOSTRAD_CLIENT_ID": "<your Client ID>" },
"kv_namespaces": [{ "binding": "STORE", "id": "<the id from step 2>" }]
}
To put it live (you need a Cloudflare account and Node.js):
- Save the two files above as
worker.jsandwrangler.jsoncin a new folder, and open a terminal there. - Run
npx wrangler kv namespace create STOREand put theidit prints intowrangler.jsonc. - Run
npx wrangler deploy. It prints your app's address, such ashttps://my-nostrad-app.<your-subdomain>.workers.dev. - In the console, on the Sign in with Nostrad page, choose Create client, then Web server, with the return address
https://my-nostrad-app.<your-subdomain>.workers.dev/oauth/nostrad/callback. Put the Client ID intowrangler.jsonc. The client secret is shown once: keep that popup open for the next step. - Run
npx wrangler secret put NOSTRAD_CLIENT_SECRETand paste the secret when it asks. It goes into Cloudflare's secret store, never into a file. - Run
npx wrangler deployagain, open the address and choose Sign in with Nostrad.
Your app is personal until Nostrad verifies it, so only you can sign in to it at first. The names NOSTRAD_CLIENT_ID, NOSTRAD_CLIENT_SECRET and STORE are only the ones this example reads; use any.
10. Not available yet
- Public apps. An app is personal until Nostrad verifies it: only its creator can sign in or use it. To go public, fill in the website, privacy policy and terms under App settings (and a support email if people should see one) and choose Submit for verification on the same page. Nostrad checks them and approves the app, or says what to fix so you can submit it again. Until it's approved, another person's sign-in answers "This app is personal", and a job for anyone but you answers 403
this app is personal. - Sign-in on devices without a browser (a code typed on another device).
- Virus scanning of stored files. Files are served so a browser won't run them as a page (see Files and storage), but they aren't scanned, and a downloaded file can still be harmful when opened.
- Links to a file that work without a token, for showing a file in a page or handing it to a service. Today every file read carries the app's token; serve it from your own server.
- Thumbnails. Pictures carry their size; small previews aren't made yet.