Developer Docs

Spark Account OAuth API

Let your application authenticate users with their Spark Account and read verified profile data using the standard OAuth 2.0 authorization-code flow.

Overview

Spark Account implements the OAuth 2.0 authorization code grant. The flow is three steps:

  1. 1 Redirect the user to the authorization endpoint.
  2. 2 Exchange the returned code for an access token.
  3. 3 Call the userinfo endpoint with that token to read the user's profile.
Get your credentials. Create an app under Account → OAuth Apps to get a client_id and client_secret, and register your redirect URIs.

Endpoints

PurposeMethodURL
AuthorizeGEThttps://sparkden.org/api/oauth/authorize
TokenPOSThttps://sparkden.org/api/oauth/token
User infoGEThttps://sparkden.org/api/oauth/userinfo
JWKS (id_token keys)GEThttps://sparkden.org/api/oauth/jwks
Send emailPOSThttps://sparkden.org/api/oauth/email
Account eventsPOSThttps://sparkden.org/api/oauth/events
Token introspection (RFC 7662)POSThttps://sparkden.org/api/oauth/introspect

Scopes

Request only what you need. Space-separate multiple scopes in the scope parameter.

ScopeGrants access to
profileName, username, avatar, bio, account creation date
emailEmail address and email-verified status
socialLinked website, GitHub, Twitter, and Discord
email.sendSend branded emails to the user through Spark Account — verified apps only
sparkcloud.readSee the member’s SparkCloud spaces, tiles and credit balance — verified apps only
sparkcloud.spacesCreate spaces in the member’s SparkCloud and manage the ones your app created — verified apps only
sparkcloud.embedEmbed spaces your app created in your own pages — verified apps only
sparkcloud.runRun code for the member in a sandbox or a space your app created — verified apps only
sparkcloud.aiCall Sparky’s AI models (SparkAI) for the member, billed to their credits — verified apps only

1. Authorization request

Send the user's browser to the authorization endpoint. After they approve, they're redirected back to your redirect_uri with a code (and your state).

https://sparkden.org/api/oauth/authorize?
  response_type=code
  &client_id=YOUR_CLIENT_ID
  &redirect_uri=https://yourapp.com/callback
  &scope=profile email
  &state=RANDOM_STRING
ParameterRequiredDescription
response_typeYesMust be code
client_idYesYour app's client ID
redirect_uriYesMust exactly match a registered URI
scopeNoSpace-separated scopes (defaults to profile)
stateRecommendedOpaque value echoed back for CSRF protection

2. Token exchange

Exchange the authorization code for an access token from your server. Credentials can be sent in the body (shown) or as HTTP Basic auth (Authorization: Basic base64(client_id:client_secret)).

curl -X POST https://sparkden.org/api/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code" \
  -d "code=THE_CODE_FROM_REDIRECT" \
  -d "redirect_uri=https://yourapp.com/callback" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET"

Response

{
  "access_token": "eyJhbGci...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "eyJhbGci...",
  "scope": "profile email",
  "id_token": "eyJhbGci..."   // OIDC identity token (RS256, verify via JWKS)
}

3. User info

Use the access token to fetch the user's profile. Fields returned depend on the granted scopes — email and email_verified are only included when the email scope was granted.

curl https://sparkden.org/api/oauth/userinfo \
  -H "Authorization: Bearer ACCESS_TOKEN"

Response

{
  "sub": "a1b2c3d4-...",
  "uid": "a1b2c3d4-...",
  "username": "janedoe",
  "email": "jane@example.com",      // only with email scope
  "email_verified": true,            // only with email scope
  "roles": ["ADULT", "VERIFIED", "SPARKCLOUD"],
  "role": "VERIFIED",
  "verified": true,
  "id_verified": true,
  "sparkcloud_access": true,
  "chat_member": true,
  "chat_admin": false,
  "name": "Jane Doe",
  "avatar_url": "https://...",
  "created_at": "2026-01-12T..."
}
FieldTypeDescription
sub / uid string Stable unique user ID (UUID)
username string Account username
email string Email address — only returned when email scope is granted
email_verified boolean Whether the email address is confirmed — only returned when email scope is granted
roles string[] All roles, e.g. STUDENT, ADULT, VERIFIED, SPARKCLOUD, CHAT_MEMBER, CHAT_ADMIN, ADMIN
role string Legacy single role (STUDENT, ADULT, VERIFIED, MODERATOR, or ADMIN)
verified boolean True if the user has passed identity verification
id_verified boolean Alias of verified — identity verification status
sparkcloud_access boolean True if the user may access SparkCloud
chat_member boolean True if the user is a full member of the community chat (SparkChat)
chat_admin boolean True if the user is a community chat admin
name string Display name (requires profile scope)
avatar_url string Profile picture URL (requires profile scope)

Student verification

Spark Account can verify a user's real-world identity. Your app can both read a user's verification status and require it before authorization.

Reading verification status

The userinfo response includes the user's verification state — check whichever you prefer:

  • verified / id_verified — true once the user has passed identity verification.
  • roles — the full set, e.g. STUDENT/ADULT (account type), VERIFIED, SPARKCLOUD, CHAT_MEMBER, CHAT_ADMIN, ADMIN. Gate access on the role you need (e.g. SPARKCLOUD).
  • sparkcloud_access — convenience boolean, true when roles includes SPARKCLOUD (or ADMIN).

Requiring verification

Enable "Require student verification" on your app (in the create or edit dialog under OAuth Apps) to block unverified users at the consent screen. They'll be prompted to verify their identity before they can authorize your app — so any token your app receives belongs to a verified user.

Sending email

Verified apps can send emails to their users through Spark Account — no SMTP setup, no separate email provider. Every message is wrapped in a clean, Spark-styled template that carries your app's branding and a clear "sent from [your app] via Spark Account" disclosure, so users always know who's emailing them and why.

Verified apps only. Your app must be approved by an admin (submit it for review) and the user must have granted the email.send scope during authorization. Unverified apps receive app_not_verified.

Branding

Set a logo URL and brand color on your app under Account → OAuth Apps. The logo appears at the top of every email (and on the consent screen); the brand color is used for the accent bar and call-to-action button. No branding set? Emails fall back to a neutral monogram and Spark orange.

Request

Authenticate with the user's access token. The email is always delivered to the token holder's account email address — you never need (or get) the address itself.

curl -X POST https://sparkden.org/api/oauth/email \
  -H "Authorization: Bearer ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "subject": "Your weekly project report",
    "title": "Your projects this week",
    "body": "Hi! You shipped 4 new builds this week.\n\nKeep it up — your streak is now 3 weeks.",
    "cta_url": "https://yourapp.com/dashboard",
    "cta_text": "View dashboard"
  }'
FieldRequiredDescription
subjectYesEmail subject line (max 150 characters)
bodyYesPlain-text message (max 5,000 characters). Use blank lines for paragraphs — HTML is not allowed and will be escaped.
titleNoHeading shown at the top of the email (defaults to the subject, max 150 characters)
cta_urlNohttp(s) link for an optional call-to-action button
cta_textNoButton label (defaults to "Open [app name]", max 60 characters)

Response

{ "ok": true }

Content rules & limits

  • Plain text only. Any HTML in subject, title, or body is escaped, not rendered. Blank lines become paragraph breaks.
  • One link. The optional cta_url button is the only clickable link — it must be a valid http(s) URL.
  • Rate limits. Per user, each app may send 5 emails/hour and 20 emails/day. Exceeding either returns rate_limited (HTTP 429).
  • Revocable. Users can stop your emails at any time by revoking your app's access from their account.
Use it for transactional mail — receipts, alerts, reports, security notices. Marketing blasts and spam will get your app's verified status revoked.

SparkCloud

With the sparkcloud.* scopes your app can use the member’s SparkCloud: run a snippet when they press “Run”, call Sparky’s AI models, give them a space for your course, lay out the exercise files, show the editor inside your own lesson page, and read their work back. Everything is billed to and limited by the member’s own SparkCloud credits and quotas, exactly as if they did it themselves.

Verified apps only, and confined to what you create. SparkCloud scopes must be registered on your app and your app must be verified; adding one to a verified app sends it back for review. Your app can read the member’s spaces with sparkcloud.read, but it can only start, stop, delete, write to, run code in or embed spaces it created. The member’s own projects are never reachable.

Asking for access

Request the scopes like any other. Members who don’t have a SparkCloud account yet are offered one on the consent screen (“Create my SparkCloud account”) and authorize in the same click. Members without SparkCloud access (students who haven’t verified) are sent to verify first.

GET https://sparkden.org/api/oauth/authorize
  ?response_type=code
  &client_id=YOUR_CLIENT_ID
  &redirect_uri=https://learn.example.com/callback
  &scope=profile sparkcloud.run sparkcloud.spaces sparkcloud.embed
  &state=RANDOM_STATE

Checking a token

POST /api/oauth/introspect (RFC 7662) takes token=… with your client credentials as HTTP Basic auth and returns { active, scope, sub, exp, … }. An app can only introspect tokens issued to itself; anything else, including revoked or expired tokens, comes back as { "active": false }.

Calling SparkCloud

Send the access token to https://cloud.sparkden.org/api/v1/connect as Authorization: Bearer, from your server: the token is a credential for the member’s SparkCloud and must not reach the browser. SparkCloud checks every token with Spark Account, so a member revoking your app stops it working within a minute.

MethodPathScopeWhat it does
GET/meany sparkcloud.*The member’s SparkCloud username, space quota and what your grant covers
GET/spacessparkcloud.readAll the member’s spaces; createdByThisApp marks yours
GET/spaces/:idread or spacesOne space’s status (with only sparkcloud.spaces: spaces your app created)
GET/tilessparkcloud.readThe member’s tiles, with public URLs for published ones
POST/spacessparkcloud.spacesCreate a space { name, diskGb? }. Uses the member’s quota and credits
POST/spaces/:id/startsparkcloud.spacesStart or wake one of your spaces; poll GET /spaces/:id for "running"
POST/spaces/:id/stopsparkcloud.spacesStop one of your spaces
DELETE/spaces/:idsparkcloud.spacesDelete one of your spaces
GET/spaces/:id/files?path=sparkcloud.spacesRead a file (text) or list a directory in the project
PUT/spaces/:id/filessparkcloud.spacesWrite a file { path, content } (up to 1 MB)
POST/spaces/:id/embedsparkcloud.embedAn iframe URL for one of your spaces { expiresInMinutes? }
POST/runsparkcloud.runRun code in a throwaway sandbox { language, code, stdin?, timeoutSeconds? }
POST/spaces/:id/runsparkcloud.runRun code inside one of your spaces, in its project directory
GET/ai/modelssparkcloud.aiModels the member can use, with per-1K-token prices (OpenAI list shape)
POST/ai/chat/completionssparkcloud.aiOpenAI-compatible chat completion, streaming supported, billed per token to the member

Running code

POST /run runs code in a fresh sandbox that is thrown away afterwards: no network, nothing persists, 256 MB of memory and up to 30 seconds. Languages: python, javascript, bash. A program that fails or times out is a normal result, not an error. Each run is billed to the member like a container: SparkCloud’s hourly container rate, prorated to the seconds it ran (the response’s creditsCharged), and refused with insufficient_credits (402) when their balance can’t cover it. To run code against files the member has been working on, use POST /spaces/:id/run on a space your app created (up to 120 seconds).

curl -X POST https://cloud.sparkden.org/api/v1/connect/run \
  -H "Authorization: Bearer ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"language": "python", "code": "print(sum(range(10)))"}'

Response

{
  "runtime": "sandbox",
  "language": "python",
  "exitCode": 0,
  "stdout": "45\n",
  "stderr": "",
  "timedOut": false,
  "truncated": false,
  "durationMs": 412
}

AI requests

With sparkcloud.ai your app can call the same AI models Sparky uses, as the member. The endpoints are OpenAI-compatible, so any OpenAI SDK works: set its base URL to https://cloud.sparkden.org/api/v1/connect/ai and use the member’s access token as the API key. Streaming ("stream": true) and tools work as with OpenAI. Each call is metered per token at the model’s listed price and billed to the member’s SparkCloud credits (AI grants first); their billing history shows your app’s name. Out of credits answers 402; too many requests, 429.

from openai import OpenAI

# The member's Spark Account access token is the API key.
client = OpenAI(base_url="https://cloud.sparkden.org/api/v1/connect/ai", api_key=ACCESS_TOKEN)

reply = client.chat.completions.create(
    model="MODEL_ID",  # from client.models.list(); omit for the default
    messages=[{"role": "user", "content": "Explain recursion to a 12-year-old"}],
)
print(reply.choices[0].message.content)

Embedding a space

POST /spaces/:id/embed returns an embedUrl to put in an <iframe>. Only your app’s registered redirect-URI origins may frame it, so register the site that shows the lesson as a redirect URI. The URL is a credential for that space until it expires (2 hours by default, at most 8), so mint a fresh one each time the page loads and never share it. Opening it starts or wakes the space if it was asleep. It works in every browser, Safari included, because it doesn’t depend on cookies.

# 1. Create a space for the lesson (once per member)
curl -X POST https://cloud.sparkden.org/api/v1/connect/spaces \
  -H "Authorization: Bearer ACCESS_TOKEN" -H "Content-Type: application/json" \
  -d '{"name": "Intro to Python"}'

# 2. Lay out the exercise (once the space reports "running")
curl -X PUT https://cloud.sparkden.org/api/v1/connect/spaces/SPACE_ID/files \
  -H "Authorization: Bearer ACCESS_TOKEN" -H "Content-Type: application/json" \
  -d '{"path": "lesson1/main.py", "content": "# Write your solution here\n"}'

# 3. Mint an embed URL each time the lesson page loads
curl -X POST https://cloud.sparkden.org/api/v1/connect/spaces/SPACE_ID/embed \
  -H "Authorization: Bearer ACCESS_TOKEN"

Errors

Errors keep their real HTTP status and carry error and error_description.

errorStatusWhat to do
sparkcloud_account_required403The member has no SparkCloud account. Send them through authorize again; the consent screen offers to create one.
sparkcloud_access_required403The member’s Spark Account lacks SparkCloud access (students get it after verifying).
insufficient_scope403The grant doesn’t include the scope this call needs. Re-authorize with it.
not_app_space403That space belongs to the member, not your app. Apps can only change spaces they created.
space_not_running409Start the space and poll until it reports "running".
quota_exceeded / insufficient_resources400 / 402The member is at their space quota, or out of credits or storage.
invalid_token401Expired, revoked or unknown token. Refresh it.

Refresh tokens

Access tokens expire after 1 hour. Use the refresh token to get a new pair without sending the user through the flow again. Refresh tokens are single-use — store the new one from each response.

Client credentials required. The refresh token grant requires your client_id and client_secret — either in the request body or as HTTP Basic auth. Requests without valid credentials are rejected with invalid_client.
curl -X POST https://sparkden.org/api/oauth/token \
  -d "grant_type=refresh_token" \
  -d "refresh_token=YOUR_REFRESH_TOKEN" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET"

Account events

The events endpoint lets a first-party app notify Spark Account of account lifecycle changes — for example, when your app suspends or deletes a user. Spark Account applies the change locally and re-fans it to every other connected app.

Trusted apps only. Valid credentials are not enough. The sending app must be verified and set up for account events by a Spark Account admin (the same setup that makes it receive outbound webhooks), and it can only report on members who have signed in to it. No app can suspend or delete a Spark Account admin. Anything else is refused with unauthorized_client (403), and every event, accepted or refused, is audited.
Back-channel only. This endpoint is for server-to-server use. Authenticate with your client_id and client_secret via HTTP Basic auth or request body. Never expose your client secret in frontend code.

Request

curl -X POST https://sparkden.org/api/oauth/events \
  -H "Content-Type: application/json" \
  -H "Authorization: Basic $(echo -n 'CLIENT_ID:CLIENT_SECRET' | base64)" \
  -d '{
    "type": "user.suspended",
    "sub": "a1b2c3d4-...",
    "reason": "Violated community guidelines"
  }'
FieldRequiredDescription
typeYesEvent type — see table below
subYesSpark Account user ID (UUID) of the affected user
reasonNoHuman-readable reason string (used with user.suspended)
client_idIf no Basic authYour app's client ID
client_secretIf no Basic authYour app's client secret

Event types

TypeDescription
user.suspendedThe user's account was suspended. Includes an optional reason string.
user.unsuspendedA previously suspended account has been reinstated.
user.deletedThe user's account was permanently deleted. You should remove their data.

Response

{ "ok": true }

Outbound webhooks

Register an Event Webhook URL on your OAuth app (via an admin) and Spark Account will POST account lifecycle events to it whenever a user is suspended, unsuspended, or deleted — whether triggered by an admin action or by another connected app.

Payload

// POST to your registered eventWebhookUrl
// Headers:
//   Content-Type: application/json
//   X-Spark-Event: user.suspended
//   X-Spark-Signature: sha256=abc123...

{
  "type": "user.suspended",
  "sub": "a1b2c3d4-...",
  "reason": "Violated community guidelines",
  "ts": 1748908800000
}
FieldTypeDescription
typestringEvent type (user.suspended, user.unsuspended, user.deleted)
substringSpark Account user ID (UUID) of the affected user
reasonstring | nullSuspension reason, if provided
tsnumberUnix timestamp in milliseconds

Verifying signatures

Every webhook request includes an X-Spark-Signature header of the form sha256=<hex>. Compute an HMAC-SHA256 of the raw request body using your client secret as the key and compare using a constant-time function. Reject requests where the signature doesn't match.

import crypto from 'crypto';

function verifySparkSignature(rawBody, signature, clientSecret) {
  const expected = 'sha256=' +
    crypto.createHmac('sha256', clientSecret)
          .update(rawBody)
          .digest('hex');
  return crypto.timingSafeEqual(
    Buffer.from(expected),
    Buffer.from(signature)
  );
}

// In your webhook handler:
app.post('/webhook', express.text({ type: '*/*' }), (req, res) => {
  const sig = req.headers['x-spark-signature'];
  if (!verifySparkSignature(req.body, sig, CLIENT_SECRET)) {
    return res.status(401).json({ error: 'invalid_signature' });
  }
  const event = JSON.parse(req.body);
  // handle event.type: 'user.suspended' | 'user.unsuspended' | 'user.deleted'
  res.json({ ok: true });
});
Respond quickly. Spark Account does not retry failed webhook deliveries. Return a 2xx status as soon as the signature is verified — do any heavy processing asynchronously.

Errors

Token and userinfo errors are returned as JSON with an error field. Authorization errors are appended to your redirect_uri as query parameters.

ErrorMeaning
invalid_requestMissing or malformed required parameters
invalid_clientClient ID / secret did not match
invalid_grantCode expired, already used, or mismatched redirect URI
access_deniedThe user declined to authorize your app
unsupported_grant_typegrant_type must be authorization_code or refresh_token
invalid_eventUnknown event type or missing sub field in events endpoint
unauthorized_clientYour app is not allowed to send account events for this user (events endpoint)
invalid_jsonRequest body could not be parsed as JSON
insufficient_scopeThe access token is missing the scope required for this endpoint (e.g. email.send)
app_not_verifiedEmail sending requires a verified app — submit your app for review first
rate_limitedEmail quota reached for this user (5/hour, 20/day per app) — HTTP 429
email_unavailableEmail delivery is temporarily unavailable — retry later (HTTP 503)