Documentation

Give servers and CI jobs their own access

A service client is a server, script or CI job that works on one project with its own credentials. It authenticates with a private key or client secret to obtain a 10-minute access token, without requiring a person to approve each run.

What a service client is

  • Project-owned: Service clients belong to the project, which keeps them when the person or agent who created them leaves. Their API calls count as agent requests toward your organization's hourly cap.
  • Access levels: Set to Read only, Propose, or Manage at creation—the same levels used for signed-in agents. Read only lists and reads data; Propose also uploads media and queues playlist or screen changes for human review; Manage publishes, modifies, and spends directly. If the project requires review for agent changes, service clients are capped at Propose (see Read only, Propose, and Manage).
  • Capabilities: Any subset of screens, content, playlists, advertising, reports, and project within the creator's own capabilities.
  • No administrative escalation: A service client can never create or manage other service clients, members, invitations, or agent sign-ins.
  • Two authentication methods: Authenticate with a registered public key (private_key_jwt, recommended) or a client secret (client_secret_basic). Each client can hold up to two keys and two secrets simultaneously for zero-downtime rotation.

An organization can have up to 50 active service clients across all of its projects. Client IDs start with scl_ and client secrets start with sr_cs_.

Create a key

Generate an Ed25519 key pair on the machine that will run the client. The private key stays on that machine; screenRIG stores only the public key.

openssl genpkey -algorithm ed25519 -out screenrig-client.pem
chmod 600 screenrig-client.pem

EC P-256 keys and RSA keys of at least 2048 bits are also supported.

Create the client

In the dashboard

Open Access and click New service client. Enter a name, choose Read only, Propose, or Manage, select the capabilities, and either paste the public key as a JWK or click Generate a client secret. You can print the public JWK for a PEM key with Node.js:

node -e 'const c=require("node:crypto");const k=c.createPublicKey(require("node:fs").readFileSync("screenrig-client.pem"));console.log(JSON.stringify(k.export({format:"jwk"})))'

With the CLI

Creating a service client from the CLI requires Manage identity access with the identity scope, the agent's own Manage grant with the project capability on the target project, and a verified responsible person who is an administrator of that project's organization. (For a newly enrolled agent, the invited person must accept the enrollment invitation first; project Manage access alone does not authorize credential changes.)

--key-file accepts a JWK or PEM file and uploads only its public half:

screenrig service-client create --name "Nightly report" --access read \
  --capability reports --key-file screenrig-client.pem
  • --access accepts read, propose, or manage (defaults to read).
  • --capability is repeatable and defaults to all six capabilities (bounded by your own).
  • To use a client secret instead of a key, pass --secret-file PATH. The CLI writes the secret to that new file with mode 0600; it is shown once and cannot be retrieved again.

Run screenrig service-client show scl_ID to inspect the client's key IDs (kid) and secret IDs. Keys without an explicit kid are identified by their RFC 7638 thumbprint.

Uploader clients

To give an agency's automation agent access strictly to chosen playlists and media folders, add --uploader --folder-id mfd_FOLDER[,mfd_FOLDER] --playlist-id pl_PLAYLIST[,pl_PLAYLIST] to service-client create.

An uploader client holds only the content and playlists capabilities and defaults to Propose unless --access specifies otherwise. It can upload media into its assigned folders (screenrig media upload FILE --folder mfd_FOLDER) and add, replace, or remove pages on its assigned playlists (screenrig playlist page add|replace|remove). Any other request returns outside_upload_scope along with the allowed upload_scope. The project owner can update a client's folders and playlists later, and changes apply immediately to existing tokens. See Uploaders.

Get an access token

Request a token from the token endpoint using the client_credentials grant. The response contains access_token, token_type: Bearer, expires_in (600 seconds), and scope. Service clients do not receive refresh tokens—simply request a new token when the current one expires.

With a client secret, authenticate via HTTP Basic (sending the secret in the request body is rejected):

curl -s https://api.screenrig.ai/oauth/token \
  -u "$SCREENRIG_CLIENT_ID:$SCREENRIG_CLIENT_SECRET" \
  -d grant_type=client_credentials

With a private key, send a signed JWT client assertion:

curl -s https://api.screenrig.ai/oauth/token \
  -d grant_type=client_credentials \
  -d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \
  -d client_assertion="$ASSERTION"

Sign the assertion JWT with your private key using these fields:

FieldValue
Header algEdDSA, ES256, or RS256 matching your key
Header kidThe registered key's kid
iss and subThe service client ID
audhttps://api.screenrig.ai or https://api.screenrig.ai/oauth/token (single string)
iat, expAt most 5 minutes apart
jtiA fresh unique value for every assertion (reused values are rejected)

The jku, x5u, jwk, and x5c JWT headers are rejected.

Request narrower access

Two optional form parameters let you narrow an individual token:

  • scope: Pass access:read or access:propose to request a lower access level than the client's grant, and list specific capability names to keep only those (for example, scope=access:read reports). Requesting anything beyond the client's grant returns invalid_scope.
  • resource: https://api.screenrig.ai/api (default) for the REST API, or https://api.screenrig.ai/mcp for the remote server.

Call the API

Include the access token as a bearer token. Every request acts on the client's assigned project:

curl -s https://api.screenrig.ai/api/screens \
  -H "Authorization: Bearer $TOKEN"

Node.js: cached token with a private key

This helper signs client assertions using Node's built-in node:crypto, caches the access token in memory, and refreshes it one minute before expiry. Set CLIENT_KEY_ID to the key's kid from service-client show:

import { createPrivateKey, randomUUID, sign } from "node:crypto";
import { readFileSync } from "node:fs";

const ISSUER = "https://api.screenrig.ai";
const { SCREENRIG_CLIENT_ID: clientId, SCREENRIG_CLIENT_KEY_FILE: keyFile, CLIENT_KEY_ID: kid } = process.env;
const key = createPrivateKey(readFileSync(keyFile));
const part = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
let cached;

function assertion() {
  const now = Math.floor(Date.now() / 1000);
  const input = `${part({ alg: "EdDSA", typ: "JWT", kid })}.${part({ iss: clientId, sub: clientId, aud: ISSUER, iat: now, exp: now + 60, jti: randomUUID() })}`;
  return `${input}.${sign(null, Buffer.from(input), key).toString("base64url")}`;
}

export async function accessToken() {
  if (cached && cached.expiresAt - 60_000 > Date.now()) return cached.token;
  const response = await fetch(`${ISSUER}/oauth/token`, {
    method: "POST",
    body: new URLSearchParams({
      grant_type: "client_credentials",
      client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
      client_assertion: assertion(),
    }),
  });
  const body = await response.json();
  if (!response.ok) throw new Error(`screenRIG token request refused: ${body.error}: ${body.error_description ?? ""}`);
  cached = { token: body.access_token, expiresAt: Date.now() + body.expires_in * 1000 };
  return cached.token;
}

Python: cached token with a client secret

import base64, json, os, time, urllib.parse, urllib.request

ISSUER = "https://api.screenrig.ai"
_cached = {"token": None, "expires_at": 0.0}


def access_token() -> str:
    if _cached["token"] and _cached["expires_at"] - 60 > time.time():
        return _cached["token"]
    pair = f'{os.environ["SCREENRIG_CLIENT_ID"]}:{os.environ["SCREENRIG_CLIENT_SECRET"]}'
    request = urllib.request.Request(
        f"{ISSUER}/oauth/token",
        data=urllib.parse.urlencode({"grant_type": "client_credentials"}).encode(),
        headers={"Authorization": "Basic " + base64.b64encode(pair.encode()).decode()},
    )
    with urllib.request.urlopen(request, timeout=10) as response:
        body = json.load(response)
    _cached.update(token=body["access_token"], expires_at=time.time() + body["expires_in"])
    return body["access_token"]

Run the CLI as a service client

Configure the CLI once with a dedicated config file. The config file stores the client ID and the path to its private key (recommended) or secret file—never the raw key or secret itself:

screenrig --config /run/screenrig/ci.json login --client-id scl_ID \
  --client-key-file /run/secrets/screenrig-client.pem
screenrig --config /run/screenrig/ci.json screen list

For a client secret, pass --client-secret-file FILE instead of --client-key-file. Subsequent commands using that config file authenticate automatically, reading the key or secret file on each invocation (so rotating the file requires no re-login), keeping tokens in memory only, and writing nothing back to the config file. Run screenrig logout to remove the client entry.

Because each CLI command requests its own access token, high-volume jobs making more than a few hundred commands per hour should reuse a cached token directly through the API.

Rotate and revoke

ActionDashboard (Access → client)CLI
Add a second keyAdd keyscreenrig service-client add-key scl_ID --key-file new.pem
Remove a keyRemove keyscreenrig service-client remove-key scl_ID --kid KID
Add a second secretGenerate secretscreenrig service-client add-secret scl_ID --secret-file new-secret
Remove a secretRemove secretscreenrig service-client remove-secret scl_ID --secret-id css_ID
Change access or capabilitiesAccess → Save accessUse the dashboard
Revoke the clientRevokescreenrig service-client revoke scl_ID --yes
  • Zero-downtime rotation: Add the new key or secret, deploy it to your workload, and then remove the old credential. Tokens issued with a removed credential stop working within seconds. A client must always retain at least one active key or secret.
  • Narrowing access: Reducing a client's access level or capabilities invalidates its existing tokens; the next token reflects the updated grant. Briefly after a credential removal or scope reduction, token requests may return 503 temporarily_unavailable with Retry-After—retry after the indicated delay.
  • Revocation and project status: Revocation is permanent: all keys and secrets are deleted, active tokens stop working within seconds, and the entry remains on the Access page for audit visibility. Deleting a project revokes all of its service clients. A client gets tokens only while its project is active; a cancelled or deleted project issues none.

Errors and limits

ResponseCauseResolution
401 invalid_clientWrong or removed secret, invalid or replayed assertion, unknown kid, revoked client, or cancelled/deleted projectVerify credentials with service-client show and generate a fresh jti per assertion
400 invalid_scopeRequested scope exceeds the client's access level or capabilitiesRequest a narrower scope or update the client's permissions
400 invalid_targetresource is not one of the two supported targetsUse the default API target or the remote server target
429 rate_limitedExceeded 600 tokens per client or 1,200 token requests per IP per hourCache and reuse each token until it expires
503 temporarily_unavailableTry again shortlyWait for Retry-After and retry
401 from /apiAccess token expired or was revokedRequest a new token once; stop if it fails again
403 forbidden when managing clientsMissing identity authority, no current project membership with project capability, or responsible person is not an organization adminHave the invited person accept enrollment; confirm identity Manage access, the agent's project Manage grant, and the responsible person's organization admin role
403 insufficient_access from /apiAccess level cannot perform the action, or project requires review for agent changesUse a Manage client; when review is required, playlist and screen changes route to Reviews
429 rate_limited from /apiOrganization reached its plan's hourly agent request capWait Retry-After seconds and retry once (no charge is incurred)