Quickstart: Sign in with Nostrad
From nothing to a downloaded image, by hand, before you have written any server. With Sign in with Nostrad each person who uses your app pays, from their own Nostrad balance, within the monthly limit they choose for your app when they sign in. Your app never handles their payment and never holds an API key. Here, that person is you.
The other way in is an API key: nobody signs in and you pay for every call. Both reach the same models; the documentation compares them.
This needs credit. Step 7 runs a real job and charges your Nostrad balance, so add some first. A job is refused with 402 if the balance can't cover the most it could cost. Each model's price is under Models in the console.
Each step has the commands for curl (macOS, Linux, Git Bash, with openssl) and for PowerShell (Windows). Keep one shell open from step 2 to the end: it holds your code_verifier. The same steps as one JavaScript file are at the end.
1. Make a sign-in client
- Open the developer console and log in with your Nostrad account.
- Create app (or open one), then Services: tick Make images.
- Sign in with Nostrad → Create client: a name, kind Phone, desktop or browser-only (no secret: it uses PKCE alone), and this return address, exactly:
It is a page of this documentation that shows you the code Nostrad sends back, so you can copy it into your shell.https://accounts.nostrad.ai/developer/docs/quickstart/signin/return/ - Integration: copy the Client ID. It is public.
2. Make a code_verifier, its code_challenge and a state
The code_verifier is a random secret that stays in your shell (PKCE, RFC 7636): only you can swap the code for tokens. The state lets you check that the code that comes back is from your own sign-in.
CLIENT_ID="<your Client ID>"
RETURN="https://accounts.nostrad.ai/developer/docs/quickstart/signin/return/"
VERIFIER=$(openssl rand -base64 32 | tr '+/' '-_' | tr -d '=')
CHALLENGE=$(printf '%s' "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 | tr '+/' '-_' | tr -d '=')
STATE=$(openssl rand -hex 16)
echo "state: $STATE"
$clientId = "<your Client ID>"
$return = "https://accounts.nostrad.ai/developer/docs/quickstart/signin/return/"
$b64url = { param([byte[]]$b) [Convert]::ToBase64String($b).TrimEnd("=").Replace("+", "-").Replace("/", "_") }
$bytes = New-Object byte[] 32
[Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
$verifier = & $b64url $bytes
$challenge = & $b64url ([Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::ASCII.GetBytes($verifier)))
[Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
$state = & $b64url $bytes
"state: $state"
3. Sign in and choose Continue
Open this address in your browser, built as the console's Integration page shows it:
echo "https://accounts.nostrad.ai/authorize?response_type=code&client_id=$CLIENT_ID&redirect_uri=https%3A%2F%2Faccounts.nostrad.ai%2Fdeveloper%2Fdocs%2Fquickstart%2Fsignin%2Freturn%2F&scope=image&state=$STATE&code_challenge=$CHALLENGE&code_challenge_method=S256&resource=https%3A%2F%2Fgateway.nostrad.ai"
Start-Process "https://accounts.nostrad.ai/authorize?response_type=code&client_id=$clientId&redirect_uri=https%3A%2F%2Faccounts.nostrad.ai%2Fdeveloper%2Fdocs%2Fquickstart%2Fsignin%2Freturn%2F&scope=image&state=$state&code_challenge=$challenge&code_challenge_method=S256&resource=https%3A%2F%2Fgateway.nostrad.ai"
Log in if asked. On the page Connect your Nostrad account to your app, keep Make images ticked, set a monthly limit (5 dollars is plenty), and choose Continue.
4. Copy the code
Nostrad brings your browser back to the return page, which shows the code and the state. Check that the state is the one your shell printed in step 2, then copy the code. It works once, for 10 minutes. The page saves nothing and sends nothing; the code is useless without your code_verifier, which never left your shell.
5. Swap the code for tokens
No secret: this client sends its client_id and the code_verifier instead.
CODE="<the code>"
curl https://accounts.nostrad.ai/oauth/token --data-urlencode grant_type=authorization_code --data-urlencode client_id=$CLIENT_ID --data-urlencode code=$CODE --data-urlencode redirect_uri=$RETURN --data-urlencode code_verifier=$VERIFIER
$code = "<the code>"
$t = Invoke-RestMethod https://accounts.nostrad.ai/oauth/token -Method Post -Body @{ grant_type = "authorization_code"; client_id = $clientId; code = $code; redirect_uri = $return; code_verifier = $verifier }
$t.scope
$h = @{ Authorization = "Bearer $($t.access_token)" }
The answer holds an access_token (for 1 hour), a refresh_token (until it goes six months unused), the scope you allowed and a user_id, which stays the same for this person in your app, so save your data under it. With curl, keep the two tokens in your shell:
TOKEN="<access_token from the answer>"
REFRESH="<refresh_token from the answer>"
6. List the models
curl https://gateway.nostrad.ai/v1/models -H "Authorization: Bearer $TOKEN"
(Invoke-RestMethod https://gateway.nostrad.ai/v1/models -Headers $h).models | Where-Object available | Select-Object id, label
The access token reaches only the services you allowed. The commands below use stability:stable-diffusion-3.5-large as an example. Put in the id of an image model that shows available: true: it may not be this one.
7. Run an image job, wait for it, download it
curl https://gateway.nostrad.ai/v1/jobs -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" -d '{"model": "stability:stable-diffusion-3.5-large", "inputs": {"prompt": "a lighthouse at dawn"}}'
curl https://gateway.nostrad.ai/v1/jobs/<job_id> -H "Authorization: Bearer $TOKEN"
curl https://gateway.nostrad.ai/files/<file name from outputs[0].url> -H "Authorization: Bearer $TOKEN" -o lighthouse.png
$body = @{ model = "stability:stable-diffusion-3.5-large"; inputs = @{ prompt = "a lighthouse at dawn" } } | ConvertTo-Json
$job = try { Invoke-RestMethod https://gateway.nostrad.ai/v1/jobs -Method Post -Headers $h -ContentType "application/json" -Body $body } catch { $_.ErrorDetails.Message | ConvertFrom-Json }
while ($job.state -in "queued", "processing") { Start-Sleep 3; $job = Invoke-RestMethod "https://gateway.nostrad.ai/v1/jobs/$($job.job_id)" -Headers $h }
$job.state
$job.error
$name = ($job.outputs[0].url -split "/")[-1]
Invoke-WebRequest "https://gateway.nostrad.ai$($job.outputs[0].url)" -Headers $h -OutFile $name -UseBasicParsing
With curl, run the second command every few seconds until state is done or failed. The job is charged to the person who signed in (you), within the limit chosen on the consent page; cost_cents shows how much. A failed job says why in error and costs nothing, unless a content check blocked it: that's charged the listed price. A refusal, or a job that fails while it's starting, comes with an error status and says why in detail or error: PowerShell treats that status as a failed command, which is why the job command has try and catch.
8. Refresh the token
An access token lasts an hour. Swap the refresh token for new ones, and keep the new refresh token each time:
curl https://accounts.nostrad.ai/oauth/token --data-urlencode grant_type=refresh_token --data-urlencode client_id=$CLIENT_ID --data-urlencode refresh_token=$REFRESH
$t = Invoke-RestMethod https://accounts.nostrad.ai/oauth/token -Method Post -Body @{ grant_type = "refresh_token"; client_id = $clientId; refresh_token = $t.refresh_token }
$h = @{ Authorization = "Bearer $($t.access_token)" }
All of it as one JavaScript file
Save it as signin.mjs and run node signin.mjs <your Client ID> (Node 20 or later). It prints the address to open, asks for the code, then does steps 5 to 8.
// signin.mjs: Sign in with Nostrad by hand, then list the models, run an image job, save it, refresh.
import { createHash, randomBytes } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { createInterface } from "node:readline/promises";
const ACCOUNTS = "https://accounts.nostrad.ai";
const GATEWAY = "https://gateway.nostrad.ai";
const RETURN = `${ACCOUNTS}/developer/docs/quickstart/signin/return/`;
const clientId = process.argv[2];
if (!clientId) throw new Error("give your Client ID: node signin.mjs <Client ID>");
// 2. A code_verifier, its code_challenge (S256) and a state.
const verifier = randomBytes(32).toString("base64url");
const challenge = createHash("sha256").update(verifier).digest("base64url");
const state = randomBytes(16).toString("hex");
// 3. Sign in and choose Continue.
console.log("Open this address, log in and choose Continue:\n" + `${ACCOUNTS}/authorize?` + new URLSearchParams({
response_type: "code", client_id: clientId, redirect_uri: RETURN, scope: "image", state,
code_challenge: challenge, code_challenge_method: "S256", resource: GATEWAY,
}));
// 4. Copy the code; the return page's state must be this one.
console.log(`The return page's state must be ${state}`);
const ask = createInterface({ input: process.stdin, output: process.stdout });
const code = (await ask.question("Paste the code: ")).trim();
ask.close();
// 5. Swap the code for tokens (no secret: client_id and the code_verifier).
async function token(fields) {
const r = await fetch(`${ACCOUNTS}/oauth/token`, { method: "POST", body: new URLSearchParams({ client_id: clientId, ...fields }) });
const answer = await r.json();
if (!r.ok) throw new Error(`token ${r.status}: ${answer.error_description ?? answer.error}`);
return answer;
}
let t = await token({ grant_type: "authorization_code", code, redirect_uri: RETURN, code_verifier: verifier });
console.log(`allowed: ${t.scope}`);
async function call(path, init = {}) {
const r = await fetch(GATEWAY + path, { ...init, headers: { authorization: `Bearer ${t.access_token}`, ...init.headers } });
if (!r.ok) {
const answer = await r.json().catch(() => ({}));
throw new Error(`${r.status}: ${answer.detail ?? answer.error ?? r.statusText}`);
}
return r;
}
// 6. List the models.
const { models } = await (await call("/v1/models")).json();
console.log(models.filter((m) => m.available).map((m) => m.id).join("\n"));
// 7. Run an image job, wait for it, download it.
let job = await (await call("/v1/jobs", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ model: "stability:stable-diffusion-3.5-large", inputs: { prompt: "a lighthouse at dawn" } }),
})).json();
while (job.state === "queued" || job.state === "processing") {
await new Promise((done) => setTimeout(done, 3000));
job = await (await call(`/v1/jobs/${job.job_id}`)).json();
}
if (job.state === "failed") throw new Error(job.error);
const name = job.outputs[0].url.split("/").pop();
await writeFile(name, Buffer.from(await (await call(job.outputs[0].url)).arrayBuffer()));
console.log(`saved ${name}; it cost ${job.cost_cents} cents`);
// 8. Refresh the token.
t = await token({ grant_type: "refresh_token", refresh_token: t.refresh_token });
console.log(`refreshed: ${(await (await call("/v1/models")).json()).models.length} models`);
In a real app
- The return address is your program's own, registered on the client under Sign in with Nostrad (for a program being built,
http://localhostis allowed). The documentation's Sign in with Nostrad section has every value, and its example is a whole server. - Keep the tokens on your server, tied to that person's session, or in the device's secure store for a phone or desktop app. Never in a web page.
- A Web server client has a secret: add it to the token requests with
-u "<Client ID>:$NOSTRAD_CLIENT_SECRET", from your server's secret store. - Another person signs in the same way and pays from their own balance. Your app is personal until Nostrad verifies it: until then only you can sign in to it. To go public, use Submit for verification under App settings.
- Anyone can take their access away on their account's Apps page; the tokens then answer 401.
If something is refused
| Where | Usually |
|---|---|
| The return page says Not allowed | You chose Cancel, or the address in step 3 was changed: build it again |
| Sign-in page: the return address isn't registered | The client's return address isn't exactly the one in step 1 |
Token: invalid_grant | The code was used already, is older than 10 minutes, or the code_verifier isn't the one from the same shell: do steps 2 to 5 again |
| Gateway: 401 | The access token ran out: refresh it (step 8) |
Refresh: invalid_grant | The sign-in has ended: it went six months unused, or it was revoked or removed under Apps. Sign in again (steps 2 to 5) |
| Gateway: 402 | The person's balance is used up. Send them to https://accounts.nostrad.ai/account#credit to add credit |
Gateway: 403, over_limit | The monthly limit they chose for the app is reached; the words end with what is used and when it resets. They raise it under Apps on accounts.nostrad.ai |
| Gateway: 403 | A service you didn't allow, or access was taken away |
| Gateway: 502 | "Nostrad error": not your request; nothing was charged. Try again later |
Every status is in the documentation's error table.