Starchild Auth SDK API reference
Complete reference for authentication, Agent APIs, credits, errors, endpoints, and local testing in starchild-auth-sdk 0.4.1.
Constructor
import { StarchildAuth, StarchildAuthError } from 'starchild-auth-sdk'
const auth = new StarchildAuth({
clientId: 'YOUR-CLIENT-ID',
scope: 'profile chat',
autoLogin: true,
})
Defaults point at production. Override base URLs only when running the full Starchild backend locally.
| Option | Default | Purpose |
|---|---|---|
clientId |
Required | OAuth Client ID |
scope |
profile |
Space-separated scopes: profile chat credit:read credit:write |
origin |
https://iamstarchild.com |
Login popup and account-binding site |
apiBase |
https://go-api.iamstarchild.com/v1 |
Refresh and logout endpoints |
chatApiBase |
https://ai-api.iamstarchild.com |
Userinfo and Agent REST APIs |
clawdApiBase |
https://preview.iamstarchild.com |
Chat stream, jobs, and model endpoints |
clawdWsBase |
wss://preview.iamstarchild.com |
Sync, terminal, and metrics WebSockets |
creditApiBase |
https://credit.iamstarchild.com |
Credits API |
autoLogin |
true |
Restore a saved session |
refreshInterval |
720000 |
Refresh interval in milliseconds |
onLogin |
None | Receives { accessToken, refreshToken, expiresIn, userInfo } |
onLogout |
None | Runs after logout |
onTokenRefresh |
None | Receives a new access token |
onTokenRefreshFailed |
None | Runs when refresh fails |
Authentication methods
| Method | Returns | Description |
|---|---|---|
login() |
Promise<LoginResult> |
Opens the Starchild authorization popup. Call from a user gesture. |
logout() |
Promise<void> |
Clears the local session and revokes it server-side. |
isLoggedIn() |
boolean |
Checks whether an access token is present. |
getToken() |
string \| null |
Returns the current access token. Read it at request time. |
getRefreshToken() |
string \| null |
Returns the in-memory refresh token copy. Treat it like a password. |
getUserInfo() |
UserInfo \| null |
Returns cached user information. |
fetchUserInfo() |
Promise<UserInfo> |
Re-fetches user information from the server. |
isGuest() |
boolean |
Returns whether the current user is a guest. |
getBindAccountUrl() |
string |
Returns the Starchild Linked accounts URL. |
bindAccount() |
Window \| null |
Opens account binding in a new tab. Returns null if blocked. |
refreshToken() |
Promise<string> |
Refreshes the access token. Prefer this over handling refresh tokens yourself. |
destroy() |
void |
Removes SDK listeners and timers. |
User information and session lifetime
type UserInfo = {
userInfoId: string
agentName: string
agentAvatar: string
isGuest: boolean
}
Access tokens last 15 minutes and refresh automatically every 12 minutes and on visibilitychange. Refresh tokens last 7 days and use localStorage key starchild_rt_{clientId}. Never log, transmit, or place a refresh token in a URL.
Namespaces
Flat methods remain available. Namespaced aliases group the same capabilities:
| Namespace | Examples |
|---|---|
auth.profile |
fetchUserInfo, getUserInfo, isGuest, bindAccount, getBindAccountUrl |
auth.chat |
send / sendMessage, reconnect / reconnectStream, cancelRun, model methods, WebSocket factories |
auth.threads |
create, list, get, delete, search, pin, updateTitle |
auth.messages |
list, delete |
auth.containers |
list, status, metrics, deploy, start, stop, restart, wake, rename, delete |
auth.skills |
catalog, search, detail |
auth.media |
uploadImage, transcribeAudio, synthesizeSpeech |
auth.shares |
create, list, get, delete, fork |
auth.feedback |
rate, delete |
auth.jobs |
list, create, get, pause, resume, restart |
auth.wallet |
getPortfolio, list, create, delete, exportPrivateKey, createOnrampSession |
auth.credit |
Balance, charges, top-ups, daily usage, pending, transaction status, Stripe, gift cards, Points, KYC, referral, migration, and WOO bonus methods |
For example, auth.chat.send('hello') is the namespaced equivalent of auth.sendMessage('hello').
Chat and SSE
sendMessage() and reconnectStream() return a raw Response. Check .ok and read the SSE body yourself. Events include agent_start, text_delta, tool_use, tool_output, agent_end, error, and agent:interrupted. Use reconnectStream(sessionKey) after a dropped stream and cancelRun(threadId) to stop a run.
const response = await auth.chat.send('Hello')
if (!response.ok) throw new Error(`Chat failed: ${response.status}`)
const reader = response.body?.getReader()
Clawd endpoints require the fly-force-instance-id header. The SDK resolves the user's container and injects it automatically. Curl and custom HTTP clients must set it explicitly.
Container deletion returns 403 for OAuth tokens by design.
Credits
credit:read enables balance and history methods. credit:write enables top-ups, gift cards, and Points exchange, and implies credit:read. Credit operations can include Stripe checkout, pending and transaction status, KYC, referrals, migration rewards, and WOO bonus. Use an Idempotency-Key for Points exchange and other retryable writes where documented.
Error handling
JSON helpers throw the exported StarchildAuthError on non-2xx responses:
try {
await auth.credit.getBalance()
} catch (error) {
if (error instanceof StarchildAuthError) {
if (error.insufficientScope) await auth.login()
console.error(error.status, error.code, error.detail, error.path)
}
}
The error exposes status, code, detail, path, insufficientScope, and response. A 403 with Insufficient scope means the token lacks an approved scope. A 401 means the token is invalid or expired. Re-authorize with the required scopes instead of treating the two cases as the same.
Endpoints
| Service | Base URL | Use |
|---|---|---|
| Auth and token | https://go-api.iamstarchild.com/v1 |
Refresh and logout |
| Userinfo and Agent REST | https://ai-api.iamstarchild.com |
Userinfo, threads, messages, containers, skills |
| Clawd | https://preview.iamstarchild.com |
Chat streams, jobs, models, WebSockets |
| Credits | https://credit.iamstarchild.com |
Balance, charges, top-ups, and credit account operations |
Server-side use
Popup login works only in a real browser. For server-side or script use, obtain a token in the browser, then inject it without opening a popup:
const auth = new StarchildAuth({ clientId: 'YOUR-CLIENT-ID', autoLogin: false })
;(auth as any)._accessToken = token
const user = await auth.fetchUserInfo()
Keep tokens in server-side secret storage and verify every token with /v1/oauth/userinfo. Do not use browser identity fields as authorization without server verification.
Local testing
Use two origins deliberately:
- The Starchild web app may run at
http://localhost:6066. This is a Starchild origin and is already handled server-side. - Your third-party app runs on its own origin, such as
http://localhost:3333. Register that exact origin in the OAuth app. Do not registerlocalhost:6066as the third-party app.
Browser-versus-Node behavior:
| Operation | Browser | Node or curl |
|---|---|---|
login() popup |
Required | Not available |
| Calls with an existing bearer token | Yes | Yes |
| CORS enforcement | Browser applies it | Scripts do not apply browser CORS |
| CORS testing | DevTools and page requests | Simulate OPTIONS with an Origin header |
If a new approved origin still fails CORS, check its scheme and port, approval and active status, then allow roughly five minutes for the allowlist refresh.
Security checklist
- Request only the scopes the app needs.
- Keep access tokens out of long-lived application state.
- Never log or transmit refresh tokens.
- Verify every protected request on the server.
- Gate payments and irreversible actions for guest accounts if required.
- Treat
StarchildAuthError.insufficientScopeseparately from401expiry. - Use CSP and sanitize rendered user fields.