API docs
Search docs
Guides, operations and types

Device Flow

The Device Flow lets users authorize your application with their JilTV account, so it can act on their behalf. It is built for desktop applications, chat clients and command-line tools, and implements the OAuth 2.0 Device Authorization Grant (RFC 8628).

Choosing an authentication method

API keyDevice Flow
Acts forYou, the app's ownerEvery user who signs in
Runs onYour server, a bot you hostYour users' devices: desktop apps, chat clients, CLIs
Secret in the appYes, keep it server-sideNone. The client_id is public and safe to ship
LifetimeUntil revoked or expiry you chose1-hour access tokens, renewed with a refresh token
Revoked byYou, on DevelopersThe user (Settings, Connected apps) or your app (sign out)

Never ship an API key inside an app other people install. Anyone can pull it out of the binary, and it would act for you, not for them.

1. Register your application

  1. Open Developers and create an app. Its name, description and website are what users see when they approve it.
  2. Copy its client ID (app menu, Copy client ID). That's the app's ID, also returned as DeveloperApp.id.

There is no client secret: an installed app can't keep one. Security comes from the user approving the request on the JilTV website, where they are signed in. Apps reviewed by JilTV show a Verified badge on the consent page; unverified apps show a warning. Ask the JilTV team if you want your app reviewed.

Flow overview

Your app
JilTV API
User
  1. POST /v1/oauth/device/code
  2. device_code, user_code
  3. Shows the code, opens /activate
  4. Signs in, clicks Allow
  5. POST /v1/oauth/token
  6. authorization_pending
  7. access_token, refresh_token
  8. POST /v1/graphql

All three endpoints take application/x-www-form-urlencoded bodies (as in the RFCs; a flat JSON object of strings works too), answer JSON, and send Cache-Control: no-store. No cookies, no CSRF token, no Authorization header.

2. Request a device code

POST /v1/oauth/device/code

curl https://api.jiltv.app/v1/oauth/device/code \
  -d client_id=$JILTV_CLIENT_ID \
  -d scope=COSMETICS_WRITE
ParameterMeaning
client_idrequiredYour app's ID.
scopeoptionalSpace-separated scopes, e.g. COSMETICS_WRITE SETS_WRITE. Empty means read-only: you only learn who signed in.
Response
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store

{
  "device_code": "Xq0dHkS3b6m8YlA0Wz1jR4vT9cN2pE7uKfGhJiLoMnB",
  "user_code": "BCDF-GHJK",
  "verification_uri": "https://jiltv.app/activate",
  "verification_uri_complete": "https://jiltv.app/activate?code=BCDF-GHJK",
  "expires_in": 600,
  "interval": 5
}
FieldMeaning
device_codeSecret of this request. Keep it in memory, never show it. You poll with it.
user_codeWhat the user types: 8 letters, no vowels, no lookalikes. Show it exactly like this, with the dash.
verification_uriWhere the user enters the code.
verification_uri_completeSame page with the code filled in. Open this in the browser or render it as a QR code.
expires_inSeconds until the request expires (600).
intervalSeconds to wait between polls (5).

The request is limited to 20 per minute per IP address (429 with Retry-After above that). Start a new one only when the user clicks Sign in, not in the background.

3. Display the user code

Show the user code large and readable, with a button that opens verification_uri_complete in the default browser. On the page the user:

  1. signs in to JilTV if needed (they come back to the same page),
  2. checks the code (prefilled, or typed in; any case, the dash is optional),
  3. sees your app's name, owner, website, verified state and the scopes you asked for,
  4. clicks Allow or Deny.

Even with the code in the link, nothing is approved until the user clicks Allow. Tell users to compare the code in your app with the one on the page: that's what stops someone from tricking them into approving a request that isn't theirs.

4. Poll for tokens

While the code is shown, ask for the tokens every interval seconds: POST /v1/oauth/token

curl https://api.jiltv.app/v1/oauth/token \
  -d grant_type=urn:ietf:params:oauth:grant-type:device_code \
  -d client_id=$JILTV_CLIENT_ID \
  -d device_code=$DEVICE_CODE

Until the user answers you get:

Response
HTTP/1.1 400 Bad Request

{ "error": "authorization_pending", "error_description": "the user hasn't answered yet" }
errorStatusWhat to do
authorization_pending400Not answered yet. Wait interval seconds and poll again.
slow_down400You polled too fast. Add 5 seconds to your interval for the rest of this request, then poll again.
access_denied400The user clicked Deny. Stop and go back to the signed-out state.
expired_token400The 10 minutes are over, or you already got the tokens. Stop; the user has to start again.
invalid_grant400The device code belongs to another client. A bug in your app.
invalid_client401Unknown client_id, or the app was deleted.
invalid_request, unsupported_grant_type400A parameter is missing or misspelled.

Once the user allowed it, the next poll returns the tokens, exactly once:

Response
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store

{
  "access_token": "jtv_at_3vQ9mZ0bK7wR2xY5nL8cT1fH6jD4gS0aP9eU3iO7kWq",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "jtv_rt_8Hn2Lq5Vw0Zc3Xb6Nm9Ks1Df4Gj7Ha0Pe3Ri6Tu9Yo",
  "scope": "COSMETICS_WRITE"
}
FieldMeaning
access_tokenStarts with jtv_at_. Send it to the API as a bearer token. Valid for expires_in seconds (1 hour).
refresh_tokenStarts with jtv_rt_. Only for the token endpoint, never for API calls. Works once.
scopeWhat the user granted, space-separated.

5. Make authenticated requests

The access token works like an API key, for the user who approved: Authorization: Bearer jtv_at_… on /v1/graphql and the REST endpoints.

# Who signed in, and what may the token do?
curl https://api.jiltv.app/v1/graphql \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"query":"{ viewer { authMethod scopes user { id username displayName } } }"}'

# What they own and wear
curl https://api.jiltv.app/v1/graphql \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"query":"{ viewer { user { paint { id name } badge { id name } ownedPaints { paint { id name } } ownedBadges { badge { id name } } } } }"}'

# Wear a paint (paintId: null takes it off)
curl https://api.jiltv.app/v1/graphql \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"query":"mutation($id: ID) { equipPaint(paintId: $id) { paint { id name } } }","variables":{"id":"01J9…"}}'

viewer.authMethod is OAUTH and viewer.scopes lists what the token may do. Calls outside its scopes fail with missing_scope. Like API keys, tokens only reach the public API: no staff actions and none of the website's own (managing API keys and connected apps, profile, account deletion, billing, imports), even when an admin signed in.

When the token expired or was revoked, the API answers:

Response
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token"

{ "error": { "code": "invalid_api_key", "message": "API key or access token is invalid, expired or revoked" } }

Refresh then (step 6) and retry once. If the refresh fails with invalid_grant, the user is signed out.

6. Refresh tokens

curl
curl https://api.jiltv.app/v1/oauth/token \
  -d grant_type=refresh_token \
  -d client_id=$JILTV_CLIENT_ID \
  -d refresh_token=$REFRESH_TOKEN

The answer looks like the token response in step 4: a new access token and a new refresh token. Store both and forget the old refresh token; it is used up. Each refresh starts a new one-year window, so an app in regular use stays signed in indefinitely; one unused for a year has to sign in again.

  • Refresh shortly before expiry (about a minute early) or after a 401, not on every start.
  • One refresh at a time. Two parallel refreshes with the same token race, and the loser signs the user out.
  • Lost answers are fine. If the response never arrived (timeout, crash), retry with the same refresh token within 30 seconds: you get a fresh pair and the lost one stops working.
  • Reuse means theft. A used refresh token presented again later, or after its successor was used, revokes the whole sign-in. Your app and whoever copied the token both get invalid_grant, and the user has to sign in again.
  • invalid_grant always means: drop the tokens and show Sign in. Other failures (429, 5xx, network) are temporary: keep the tokens and try later.

7. Revoke tokens

When the user signs out of your app, revoke the tokens so they stop working at once (RFC 7009): POST /v1/oauth/revoke

curl
curl https://api.jiltv.app/v1/oauth/revoke \
  -d client_id=$JILTV_CLIENT_ID \
  -d token=$REFRESH_TOKEN
# 200 OK, empty body. Also 200 for tokens that are already invalid.

Either token works and ends the whole sign-in on that device. Users can also disconnect your app at any time under Settings, Connected apps; banned and deleted accounts stop working too. Your next call then gets a 401 and the refresh invalid_grant.

Token lifetimes and limits

WhatValue
Device code and user code10 minutes, one answer
Poll interval5 seconds, +5 after each slow_down
Access token1 hour
Refresh token1 year after it was issued, single use
Retry window for a lost refresh answer30 seconds
Sign-ins per user and app10 at once (one per device); signing in an 11th time ends the oldest
Device code and refresh requests20 per minute per IP address
API calls with an access tokenSame rate limits as an API key, counted per sign-in

Reference implementation

Sign-in, storage, automatic refresh, an API call and sign-out:

// Node 18+ or any runtime with fetch. Store tokens in the OS keychain, not in a file.
const API = 'https://api.jiltv.app';
const CLIENT_ID = process.env.JILTV_CLIENT_ID; // your app's ID, public
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function post(path, params) {
  const res = await fetch(API + path, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({ client_id: CLIENT_ID, ...params }),
  });
  const text = await res.text();
  return { ok: res.ok, status: res.status, body: text ? JSON.parse(text) : {} };
}

// --- sign in ---
export async function signIn(scope = 'COSMETICS_WRITE') {
  const { ok, body: d } = await post('/v1/oauth/device/code', { scope });
  if (!ok) throw new Error(d.error);
  showCode(d.user_code, d.verification_uri);     // big and readable
  openBrowser(d.verification_uri_complete);       // code prefilled, user still confirms

  let interval = d.interval * 1000;
  const deadline = Date.now() + d.expires_in * 1000;
  while (Date.now() < deadline) {
    await sleep(interval);
    const { ok, body } = await post('/v1/oauth/token', {
      grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
      device_code: d.device_code,
    });
    if (ok) return save(body);
    if (body.error === 'authorization_pending') continue;
    if (body.error === 'slow_down') { interval += 5000; continue; }
    throw new Error(body.error); // access_denied or expired_token: let the user start over
  }
  throw new Error('expired_token');
}

// --- tokens ---
let tokens = keychain.load(); // { access_token, refresh_token, expires_at } or null
let refreshing = null;

function save(t) {
  tokens = { access_token: t.access_token, refresh_token: t.refresh_token, expires_at: Date.now() + t.expires_in * 1000 };
  keychain.store(tokens);
  return tokens;
}

function refresh() {
  // One refresh at a time: every refresh token works exactly once.
  refreshing ??= post('/v1/oauth/token', { grant_type: 'refresh_token', refresh_token: tokens.refresh_token })
    .then(({ ok, body }) => {
      if (ok) return save(body);
      if (body.error === 'invalid_grant') { tokens = null; keychain.clear(); throw new Error('signed_out'); }
      throw new Error(body.error ?? 'refresh_failed'); // e.g. 429 or 5xx: keep the tokens, try later
    })
    .finally(() => { refreshing = null; });
  return refreshing;
}

// --- API calls ---
export async function gql(query, variables) {
  if (!tokens) throw new Error('signed_out');
  if (Date.now() > tokens.expires_at - 60_000) await refresh(); // refresh a minute early
  const call = () => fetch(API + '/v1/graphql', {
    method: 'POST',
    headers: { Authorization: `Bearer ${tokens.access_token}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ query, variables }),
  });
  let res = await call();
  if (res.status === 401) { await refresh(); res = await call(); } // revoked or expired early
  const { data, errors } = await res.json();
  if (errors?.length) throw new Error(errors[0].extensions?.code ?? errors[0].message);
  return data;
}

export const equipPaint = (paintId) =>
  gql('mutation($id: ID) { equipPaint(paintId: $id) { paint { id name } } }', { id: paintId });

// --- sign out ---
export async function signOut() {
  if (tokens) await post('/v1/oauth/revoke', { token: tokens.refresh_token });
  tokens = null;
  keychain.clear();
}

Security best practices

  • Store tokens in the OS credential store (Windows Credential Manager, macOS Keychain, libsecret), not in plain settings files.
  • Never log tokens or the device code, never put them in URLs, and send them only to the JilTV API.
  • Ask only for the scopes you use. Users see the list, and fewer scopes means less damage if a token leaks.
  • Show the user code clearly and ask users to compare it with the website.
  • Refresh one at a time, and handle invalid_grant by signing out.
  • Revoke on sign-out and when uninstalling, if you can.
  • Use HTTPS only. Don't disable certificate checks.
Search
Find emotes or users, or jump to a page