Skip to content

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.


Source & Target Allowed Scopes + Blacklist

Section titled “Source & Target Allowed Scopes + Blacklist”
  1. Source App Opt-In (request_delegation scope):
    • Enable request_delegation under Allowed Scopes in /developer (self-service, no Administrator approval required) so the confidential app can request delegated tokens for other apps.
  2. Target App Opt-In (delegation scope / delegation_mode + blocked_source_apps):
    • Enable delegation under Allowed Scopes (synchronized with delegation_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 with request_delegation can request delegation unless listed in the Target App’s blocked_source_apps blacklist (app_slug, client_id, or internal id).
  3. Target-Defined Scopes:
    • Each Target App registers its own arbitrary scope_key (e.g., data:push, profile:read), display_name, description, optional metadata JSON object, and is_active flag.
  • 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/delegate redirect 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 from granted, error=access_denied, or 403 { "error": "access_denied" }).
    • Developer/config errors (401 invalid_client, 400 invalid_target, 400 invalid_scope) are strictly separated from user authorization outcomes (access_denied).

2. Token Format, Dedicated Keys & Token-Confusion Protection

Section titled “2. Token Format, Dedicated Keys & Token-Confusion Protection”
  • Configure optional DELEGATION_JWT_PRIVATE_JWK, DELEGATION_JWT_PUBLIC_JWK, and DELEGATION_JWT_PREVIOUS_PUBLIC_JWK secrets (generated with npm run gen:keys; falls back to JWT_PRIVATE_JWK / JWT_PUBLIC_JWK if unset).
  • GET /.well-known/jwks.json publishes primary OAuth keys first followed by delegation public keys (Cache-Control: public, max-age=300).
  • 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 with typ: "delegated+jwt" or token_type: "delegated". Target App verifiers reject standard OIDC/OAuth tokens lacking typ: "delegated+jwt" and token_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–48 lowercase [a-z0-9_-], cannot start with ja_). Duplicate slugs return 409 APP_SLUG_TAKEN; invalid formats return 400 INVALID_APP_SLUG.
  • Compact Target Shorthand: Delegation endpoints (/api/delegation/check, /authorize/delegate, delegation_refresh) accept both object form and compact app_slug:scope (or ja_...:scope) strings—for example "example_app:service".
  • When a Target or Source App has app_slug set, minted delegated JWTs set aud / act.sub to app_slug and include target_client_id / act.client_id for fallback matching.
  • Auth: App Owner (developer session or API token with apps:delegation), Admin/Superuser, or the app’s own confidential client credentials (Authorization: Basic ... or X-Client-Id / X-Client-Secret).
  • Response (200 OK): Returns app_id, client_id, app_slug, delegation_mode ("disabled" or "public"), blocked_source_apps (as app_slug || client_id), token_ttl_seconds, and scopes[].
  • 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_seconds is clamped to 60–3600 seconds (default 600).

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 active scopes[] if delegation_mode is 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 (Basic auth or body client_id + client_secret) · Rate Limit: TOKEN_RATE_LIMITER per source_app_id and IP.
  • Request: Provide either user_id or an active user_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_LIMITER per source_app_id and IP.
  • Query Params (GET /authorize/delegate):
    • client_id — Source App client_id or app_slug
    • redirect_uri — Must exact-match a registered redirect URI on the Source App
    • request — 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–256 chars)
    • code_challenge & code_challenge_method=S256 — Required PKCE S256
  • Redirects (302 Found):
    • At least 1 target/scope approved: {redirect_uri}?code=jdc_...&state={state} (60s single-use code).
    • Cancelled or 0 targets approved: {redirect_uri}?error=access_denied&state={state}.

D. Token Exchange & Refresh (POST /api/delegation/token)

Section titled “D. Token Exchange & Refresh (POST /api/delegation/token)”
  • Auth: Confidential Source App (Basic auth or body client_id + client_secret) · Rate Limit: TOKEN_RATE_LIMITER per source_app_id and IP.
  • Content-Type: application/json or application/x-www-form-urlencoded.
  1. Authorization Code Exchange (grant_type: "authorization_code"):
    • Inputs: code, code_verifier, redirect_uri.
    • Atomically consumes the 60s code, verifies PKCE S256, and returns only the approved targets:
{
"granted": {
"ja_target_b": {
"access_token": "eyJ...",
"token_type": "Bearer",
"expires_in": 600,
"scope": "data:push"
}
}
}
  1. Delegated Token Refresh (grant_type: "delegation_refresh"):
    • Inputs: user_id, target_app_id (supports compact example_app:service), optional scopes (array or space-delimited string; must be a subset of the active grant).
    • Re-checks Target delegation_mode, blocked_source_apps blacklist, active user status, and user_delegation_grants.status === 'active'.
    • Returns { "access_token": "eyJ...", "token_type": "Bearer", "expires_in": 600, "scope": "data:push" }, or 403 { "error": "access_denied" } if missing or revoked.

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 future delegation_refresh and /api/delegation/introspect calls.
  • POST /api/delegation/introspect — Confidential Target App endpoint (Basic or body client_id + client_secret + token). Verifies the delegated JWT and checks live user status, Target delegation_mode, blocked_source_apps blacklist, 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,
});
},
};