Cross-App Delegated Authorization
JoeAuth implements an RFC 8693-inspired Cross-App Delegated Authorization subsystem so any registered confidential Source App (App A) can dynamically request scoped, short-lived Ed25519 (EdDSA) access tokens to call APIs exposed by one or more opted-in Target Apps (App B, App C, …) on behalf of a user—without admin delegation approval and without altering existing OAuth/OIDC login flows.
1. Access & Consent Architecture
Section titled “1. Access & Consent Architecture”Source & Target Allowed Scopes + Blacklist
Section titled “Source & Target Allowed Scopes + Blacklist”- Source App Opt-In (
request_delegationscope):- Enable
request_delegationunder Allowed Scopes in/developer(self-service, no Administrator approval required) so the confidential app can request delegated tokens for other apps.
- Enable
- Target App Opt-In (
delegationscope /delegation_mode+blocked_source_apps):- Enable
delegationunder Allowed Scopes (synchronized withdelegation_mode: "public") or configure the app’s Delegation panel /PUT /api/apps/:appId/delegation. disabled(default for all existing and new apps): No cross-app delegation permitted.public: Any app withrequest_delegationcan request delegation unless listed in the Target App’sblocked_source_appsblacklist (app_slug,client_id, or internalid).
- Enable
- Target-Defined Scopes:
- Each Target App registers its own arbitrary
scope_key(e.g.,data:push,profile:read),display_name,description, optionalmetadataJSON object, andis_activeflag.
- Each Target App registers its own arbitrary
User Consent & Revocation
Section titled “User Consent & Revocation”- Default-Deny: Every
(user_id, source_app_id, target_app_id)grant defaults to unauthorized until the user approves it. - Batch Selective Approval: A Source App can request access to 1–10 Target Apps (and up to 30 scopes per target) in a single
GET /authorize/delegateredirect without requiring prior OAuth login on each Target App. Users can toggle individual targets and scopes. - Anti-Enumeration Contract:
- Across all Source App APIs and callbacks (
/api/delegation/check,/authorize/delegate,delegation_refresh), declined, revoked, never-consented, and non-existent user states collapse into identical responses (approved: false, omitted fromgranted,error=access_denied, or403 { "error": "access_denied" }). - Developer/config errors (
401 invalid_client,400 invalid_target,400 invalid_scope) are strictly separated from user authorization outcomes (access_denied).
- Across all Source App APIs and callbacks (
2. Token Format, Dedicated Keys & Token-Confusion Protection
Section titled “2. Token Format, Dedicated Keys & Token-Confusion Protection”Dedicated Signing Keypair
Section titled “Dedicated Signing Keypair”- Configure optional
DELEGATION_JWT_PRIVATE_JWK,DELEGATION_JWT_PUBLIC_JWK, andDELEGATION_JWT_PREVIOUS_PUBLIC_JWKsecrets (generated withnpm run gen:keys; falls back toJWT_PRIVATE_JWK/JWT_PUBLIC_JWKif unset). GET /.well-known/jwks.jsonpublishes primary OAuth keys first followed by delegation public keys (Cache-Control: public, max-age=300).
Delegated JWT Header & Payload
Section titled “Delegated JWT Header & Payload”- Header:
{ "alg": "EdDSA", "typ": "delegated+jwt", "kid": "<delegation-kid>" } - Payload:
{ "iss": "https://auth.example.com", "sub": "usr_123", "aud": "ja_target_b", "act": { "sub": "ja_source_a" }, "scope": "data:push profile:read", "token_type": "delegated", "iat": 1764200000, "exp": 1764200600, "jti": "dlg_9f8e7d6c5b4a..."}- Token-Confusion Prevention: Standard SSO endpoints (
/api/oauth/userinfo,/api/oauth/introspect,/api/user/*) explicitly reject tokens withtyp: "delegated+jwt"ortoken_type: "delegated". Target App verifiers reject standard OIDC/OAuth tokens lackingtyp: "delegated+jwt"andtoken_type: "delegated".
3. App Identifiers (app_slug vs client_id) & API Reference
Section titled “3. App Identifiers (app_slug vs client_id) & API Reference”Applications can be referenced by their optional Custom App ID (app_slug), their generated client_id (ja_...), or their internal UUID id.
- Custom App ID (
app_slug): Optional, globally unique, first-come-first-served (2–48lowercase[a-z0-9_-], cannot start withja_). Duplicate slugs return409 APP_SLUG_TAKEN; invalid formats return400 INVALID_APP_SLUG. - Compact Target Shorthand: Delegation endpoints (
/api/delegation/check,/authorize/delegate,delegation_refresh) accept both object form and compactapp_slug:scope(orja_...:scope) strings—for example"example_app:service". - When a Target or Source App has
app_slugset, minted delegated JWTs setaud/act.subtoapp_slugand includetarget_client_id/act.client_idfor fallback matching.
A. Target Configuration & Metadata
Section titled “A. Target Configuration & Metadata”GET /api/apps/:appId/delegation
Section titled “GET /api/apps/:appId/delegation”- Auth: App Owner (developer session or API token with
apps:delegation), Admin/Superuser, or the app’s own confidential client credentials (Authorization: Basic ...orX-Client-Id/X-Client-Secret). - Response (
200 OK): Returnsapp_id,client_id,app_slug,delegation_mode("disabled"or"public"),blocked_source_apps(asapp_slug || client_id),token_ttl_seconds, andscopes[].
PUT /api/apps/:appId/delegation
Section titled “PUT /api/apps/:appId/delegation”- Auth: App Owner (developer session + CSRF or API token with
apps:delegation), Admin/Superuser (session + CSRF), or the app’s own confidential client credentials. - Body:
{ "delegation_mode": "public", "blocked_source_apps": ["untrusted_app"], "token_ttl_seconds": 600, "replace_scopes": false, "scopes": [ { "scope_key": "data:push", "display_name": "Push Data", "description": "Write inventory updates to Target App", "metadata": { "risk": "write" }, "is_active": true } ]}token_ttl_secondsis clamped to60–3600seconds (default600).
GET /api/delegation/targets/:targetAppId/metadata
Section titled “GET /api/delegation/targets/:targetAppId/metadata”- Auth: Confidential Source App client credentials (or authorized Admin/Owner/User session).
- Behavior: Returns Target App
name,description,homepage_url,logo_url,token_ttl_seconds, and activescopes[]ifdelegation_modeis enabled and the caller is not blacklisted.
B. Grant Pre-Check (POST /api/delegation/check)
Section titled “B. Grant Pre-Check (POST /api/delegation/check)”- Auth: Confidential Source App (
Basicauth or bodyclient_id+client_secret) · Rate Limit:TOKEN_RATE_LIMITERpersource_app_idand IP. - Request: Provide either
user_idor an activeuser_access_token(token_type === "user"issued for this Source App):
{ "user_id": "usr_123", "targets": [ { "app_id": "ja_target_b", "scopes": ["data:push", "profile:read"] }, { "app_id": "ja_target_c", "scopes": ["sync:write"] } ]}- Response (
200 OK):
{ "results": { "ja_target_b": { "approved": true, "granted_scopes": ["data:push"] }, "ja_target_c": { "approved": false, "granted_scopes": [] } }}- Errors:
401 invalid_client,400 invalid_target(unknown/disabled/blacklisted target),400 invalid_scope(unknown/inactive scope),429 rate_limited.
C. Interactive Consent Flow (GET /authorize/delegate & POST /authorize/delegate)
Section titled “C. Interactive Consent Flow (GET /authorize/delegate & POST /authorize/delegate)”- Rate Limit:
AUTH_RATE_LIMITERpersource_app_idand IP. - Query Params (
GET /authorize/delegate):client_id— Source Appclient_idorapp_slugredirect_uri— Must exact-match a registered redirect URI on the Source Apprequest— Base64URL-encoded JSON array of[{ "target_app_id": "ja_target_b", "scopes": ["data:push"] }]or compact strings like["example_app:service"]state— Required opaque CSRF token (1–256chars)code_challenge&code_challenge_method=S256— Required PKCE S256
- Redirects (
302 Found):- At least 1 target/scope approved:
{redirect_uri}?code=jdc_...&state={state}(60ssingle-use code). - Cancelled or 0 targets approved:
{redirect_uri}?error=access_denied&state={state}.
- At least 1 target/scope approved:
D. Token Exchange & Refresh (POST /api/delegation/token)
Section titled “D. Token Exchange & Refresh (POST /api/delegation/token)”- Auth: Confidential Source App (
Basicauth or bodyclient_id+client_secret) · Rate Limit:TOKEN_RATE_LIMITERpersource_app_idand IP. - Content-Type:
application/jsonorapplication/x-www-form-urlencoded.
- Authorization Code Exchange (
grant_type: "authorization_code"):- Inputs:
code,code_verifier,redirect_uri. - Atomically consumes the
60scode, verifies PKCES256, and returns only the approved targets:
- Inputs:
{ "granted": { "ja_target_b": { "access_token": "eyJ...", "token_type": "Bearer", "expires_in": 600, "scope": "data:push" } }}- Delegated Token Refresh (
grant_type: "delegation_refresh"):- Inputs:
user_id,target_app_id(supports compactexample_app:service), optionalscopes(array or space-delimited string; must be a subset of the active grant). - Re-checks Target
delegation_mode,blocked_source_appsblacklist, active user status, anduser_delegation_grants.status === 'active'. - Returns
{ "access_token": "eyJ...", "token_type": "Bearer", "expires_in": 600, "scope": "data:push" }, or403 { "error": "access_denied" }if missing or revoked.
- Inputs:
E. User Revocation & Optional Live Introspection
Section titled “E. User Revocation & Optional Live Introspection”GET /api/user/delegations— Authenticated user endpoint returning{ grants, grouped_by_source }for all active cross-app authorizations (displayed under/account).DELETE /api/user/delegations/:grantId— CSRF-protected revocation (status = 'revoked'), immediately blocking futuredelegation_refreshand/api/delegation/introspectcalls.POST /api/delegation/introspect— Confidential Target App endpoint (Basicor bodyclient_id+client_secret+token). Verifies the delegated JWT and checks live user status, Targetdelegation_mode,blocked_source_appsblacklist, and active grant, returning{ "active": true, ...claims }or{ "active": false }.
4. Target App Cloudflare Worker Verification Example
Section titled “4. Target App Cloudflare Worker Verification Example”Use JoeAuth’s stateless verifier helper (src/lib/delegation-verifier.ts) for zero-dependency verification using Cloudflare’s Cache API + in-memory JWKS cache (with automatic unknown-kid refresh):
import { authorizeDelegatedRequest, createDelegatedTokenVerifier } from './delegation-verifier';
const verifier = createDelegatedTokenVerifier({ issuer: 'https://auth.joe-univer.se', targetAppId: 'ja_your_target_client_id', cacheTtlSec: 300,});
export default { async fetch(request: Request): Promise<Response> { const auth = await authorizeDelegatedRequest(request, verifier, ['data:push']); if (!auth.ok) return auth.response;
// Verified delegated call: // auth.claims.sub -> User ID // auth.claims.act.sub -> Calling Source App client_id or app_slug // auth.scopes -> Approved scope list return Response.json({ ok: true, userId: auth.claims.sub, callerApp: auth.claims.act.sub, scopes: auth.scopes, }); },};