# SSO 555 OpenID Connect & OAuth 2.0 Full Integration Specification > This document contains the complete, authoritative, machine-readable specification for integrating SSO 555 authentication into any web, mobile, or backend application. --- ## 1. Protocol Architecture & Invariants SSO 555 is a certified Headless OpenID Connect (OIDC) and OAuth 2.0 Identity Provider (IdP). - **Issuer URL**: `https://sso555.com` - **Supported Flow**: Authorization Code Flow (`response_type=code`, `grant_type=authorization_code`) - **Key Signing Algorithm**: Asymmetric `RS256` (RSA Signature with SHA-256) - **Keystore**: Published at `https://sso555.com/.well-known/jwks.json` - **Supported Scopes**: `openid`, `profile`, `email` - **Token Lifetimes**: - Authorization Code: 5 minutes (300 seconds, single-use) - Access Token: 10 minutes (600 seconds, RS256) - Refresh Token: 30 days - **Standard Quotas**: 5 client applications per developer, up to 10 redirect URIs per application --- ## 2. Security Guardrails & Invariants When generating or reviewing integration code, the following security invariants MUST be strictly enforced: 1. **PKCE S256 Enforcement**: - Proof Key for Code Exchange (RFC 7636) is mandatory for all Public clients (React, Vue, Svelte, Vite, mobile apps, CLI/desktop AI agents). - Code challenge method MUST be `S256`. The `plain` transformation is strictly rejected. - Code verifier must be a cryptographically secure random string between 43 and 128 characters from the unreserved character set `[A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~"`. 2. **Client Secret Seclusion**: - Confidential clients receive a secret key formatted as `sec_<48-hex-chars>`. - Client secrets MUST only be stored and used on secure backend servers. - Client secrets MUST NEVER be bundled in browser JavaScript, mobile binaries, or transmitted via GET URL query strings. 3. **Strict URI Rules (Anti-Open-Redirect & Anti-Phishing)**: - Redirect URIs must be an exact character match with the registered URIs in the Developer Console. - Wildcards (`*`) and URI fragments (`#`) are strictly rejected (RFC 6749 ยง3.1.2). - Production URIs must use `https://`. Local testing permits `http://localhost:*`, `http://127.0.0.1:*`, or `http://[::1]:*`. - Anti-phishing restriction: Registering official ecosystem domains (`sso555.com`, `admin.sso555.com`, `develop.sso555.com`, `help.sso555.com`, `policies.sso555.com`, `drama555.cc`, `me555.cc`, etc.) as redirect URIs is strictly forbidden by the IdP. 4. **Cryptographic Token Verification**: - Backend APIs MUST verify JWT signatures using the public keys from `https://sso555.com/.well-known/jwks.json`. - Never decode or trust unverified JWT payloads. - Validate standard claims: `iss == "https://sso555.com"`, `aud == `, and `exp > now()`. --- ## 3. Endpoints Specification ### 3.1 OpenID Configuration - **Method**: `GET` - **URL**: `https://sso555.com/.well-known/openid-configuration` - **Response**: Standard OIDC discovery metadata containing issuer, authorization_endpoint, token_endpoint, jwks_uri, and supported claims. ### 3.2 JWKS Keystore - **Method**: `GET` - **URL**: `https://sso555.com/.well-known/jwks.json` - **Response**: ```json { "keys": [ { "kty": "RSA", "use": "sig", "alg": "RS256", "kid": "sso-key-2026", "n": "", "e": "AQAB" } ] } ``` ### 3.3 Authorization Endpoint - **Method**: `GET` - **URL**: `https://sso555.com/oidc/authorize` - **Parameters**: - `client_id` (string, required): Registered client ID (e.g. `sso_client_pub_...` or `sso_client_sec_...`). - `redirect_uri` (string, required): Absolute callback URL matching registered URI. - `response_type` (string, required): Strictly `code`. - `scope` (string, required): `openid profile email`. - `state` (string, required): Cryptographically random string for CSRF protection. - `code_challenge` (string, required for public clients): Base64URL-encoded SHA-256 hash of `code_verifier`. - `code_challenge_method` (string, required if challenge provided): Strictly `S256`. - `display` (string, optional): Set to `popup` for modal / popup authentication windows. - `nonce` (string, optional): Cryptographic nonce for replay protection. ### 3.4 Token Exchange Endpoint - **Method**: `POST` - **URL**: `https://sso555.com/oidc/token` - **Content-Type**: `application/x-www-form-urlencoded` - **Request Body (Public Client with PKCE)**: ``` grant_type=authorization_code &client_id= &code= &redirect_uri= &code_verifier= ``` - **Request Body (Confidential Client)**: ``` grant_type=authorization_code &client_id= &client_secret= &code= &redirect_uri= ``` - **Successful Response (HTTP 200)**: ```json { "access_token": "eyJhbGciOiJSUzI1NiIs...", "id_token": "eyJhbGciOiJSUzI1NiIs...", "token_type": "Bearer", "expires_in": 600, "scope": "openid profile email" } ``` ### 3.5 UserInfo Endpoint - **Method**: `GET` or `POST` - **URL**: `https://sso555.com/oidc/userinfo` - **Headers**: `Authorization: Bearer ` - **Response (HTTP 200)**: ```json { "sub": "usr_9f81a7b2c0", "email": "user@example.com", "email_verified": true, "name": "Jane Developer", "role": "user" } ``` ### 3.6 Popup Callback Endpoint - **Method**: `GET` - **URL**: `https://sso555.com/oidc/popup-callback` - **Purpose**: Helper for popup/modal login. Broadcasts `{ type: 'SSO_AUTH_SUCCESS', code, state }` to opener via `postMessage` and closes popup. ### 3.7 Single Logout (SLO) Endpoint - **Method**: `GET` or `POST` - **URL**: `https://sso555.com/oidc/end_session` - **Parameters**: - `post_logout_redirect_uri` (string, optional): Registered redirect URL to navigate to after session termination. --- ## 4. Standard Token Claims (Decoded ID Token) ```json { "iss": "https://sso555.com", "sub": "usr_9f81a7b2c0", "aud": "sso_client_pub_example", "exp": 1791500000, "iat": 1791496400, "email": "developer@example.com", "email_verified": true, "name": "Alex Smith", "role": "user" } ``` --- ## 5. Standard Error Codes & Handling | Error Code | HTTP Status | Cause | Mitigation | | :--- | :--- | :--- | :--- | | `invalid_request` | 400 | Missing required parameter (e.g. `code_challenge` on public client) | Verify all required query parameters. | | `unauthorized_client` | 400 | Client ID does not exist or client type unauthorized | Confirm Client ID registered in Developer Console. | | `access_denied` | 403 | End-user cancelled login or denied consent | Handle rejection gracefully in UI. | | `invalid_grant` | 400 | Authorization code expired (>5m, 300s) or already used | Restart authorization flow; codes are single-use. | | `redirect_uri_mismatch` | 400 | `redirect_uri` does not match registered URIs | Check scheme, domain, port, and path against console. | | `rate_limit_exceeded` | 429 | Sliding-window request quota exceeded | Back off and inspect `Retry-After` header. | --- ## 6. Implementation Reference Snippets ### 6.1 TypeScript / JavaScript: PKCE Helper Functions ```typescript function generateRandomString(length: number): string { const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'; const array = new Uint8Array(length); window.crypto.getRandomValues(array); return Array.from(array, byte => charset[byte % charset.length]).join(''); } async function generateCodeChallenge(verifier: string): Promise { const encoder = new TextEncoder(); const data = encoder.encode(verifier); const digest = await window.crypto.subtle.digest('SHA-256', data); return btoa(String.fromCharCode(...new Uint8Array(digest))) .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=+$/, ''); } ``` ### 6.2 Python: Asymmetric RS256 Token Verification (PyJWT + Remote JWKS) ```python import jwt from jwt import PyJWKClient # Keystore client automatically caches public keys from /.well-known/jwks.json jwks_client = PyJWKClient("https://sso555.com/.well-known/jwks.json") def verify_sso_bearer_token(bearer_token: str, expected_client_id: str) -> dict: clean_token = bearer_token.replace("Bearer ", "").strip() signing_key = jwks_client.get_signing_key_from_jwt(clean_token) payload = jwt.decode( clean_token, signing_key.key, algorithms=["RS256"], audience=expected_client_id, issuer="https://sso555.com", options={"require": ["exp", "iss", "aud", "sub"]} ) return payload # Validated claims dict ``` ### 6.3 Next.js / Node.js: Server-Side Authorization Code Exchange ```typescript import { NextRequest, NextResponse } from 'next/server'; export async function GET(request: NextRequest) { const { searchParams } = new URL(request.url); const code = searchParams.get('code'); const state = searchParams.get('state'); // 1. Verify CSRF state against stored session cookie const storedState = request.cookies.get('sso_oauth_state')?.value; if (!code || !state || state !== storedState) { return NextResponse.json({ error: 'Invalid state or code' }, { status: 400 }); } // 2. Exchange authorization code for tokens const body = new URLSearchParams({ grant_type: 'authorization_code', client_id: process.env.SSO_CLIENT_ID!, client_secret: process.env.SSO_CLIENT_SECRET!, code, redirect_uri: process.env.SSO_REDIRECT_URI!, }); const res = await fetch('https://sso555.com/oidc/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString(), }); if (!res.ok) { const errorData = await res.json().catch(() => ({})); return NextResponse.json({ error: 'Token exchange failed', details: errorData }, { status: res.status }); } const tokens = await res.json(); const response = NextResponse.redirect(new URL('/dashboard', request.url)); // Set secure HTTP-only session cookie response.cookies.set('sso_session', tokens.access_token, { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', maxAge: tokens.expires_in || 600, }); return response; } ``` --- ## 7. Developer Self-Service REST API (`/api/developer/apps`) Autonomous agents, CI pipelines, and developer portals can manage OIDC client registrations programmatically via the REST API on `sso-service`. - **Base URL**: `https://sso555.com/api/developer/apps` - **Authentication**: User session cookie (`sso_user`, `sso_ctx`) or Bearer token (`Authorization: Bearer `). - **CSRF Protection**: For cookie-authenticated mutating requests (`POST`, `PATCH`, `DELETE`), include header `X-XSRF-TOKEN: `. ### 7.1 Register Client Application (`POST /api/developer/apps`) #### Request Body (`CreateDeveloperAppDto`) ```json { "name": "My Agent Service", "clientType": "public", "redirectUris": [ "http://127.0.0.1:4000/callback", "https://myapp.example.com/auth/callback" ], "description": "Autonomous coding assistant connecting via local loopback", "origin": "https://myapp.example.com" } ``` #### Field Validation Rules | Field | Type | Required | Constraints | | :--- | :--- | :---: | :--- | | `name` | string | **Yes** | 2 to 50 characters, trimmed, sanitized. | | `clientType` | string | No | `'public'` (default) or `'confidential'`. | | `redirectUris` | string[] | **Yes** | 1 to 10 URIs. Max 2048 characters each. | | `description` | string | No | Max 255 characters. | | `origin` | string | No | Max 255 characters. CORS origin for public browser clients. | #### Redirect URI Validation Constraints The IdP enforces strict RFC 6749 and security constraints on every redirect URI: 1. **Characters**: Must be a valid URI. No whitespace, ASCII control characters, or unescaped characters. 2. **Fragments**: URI fragments (`#`) are strictly rejected. 3. **Wildcards**: Wildcard patterns (`*`) are strictly rejected. 4. **Scheme**: - Production URIs must use `https://`. - Local testing allows `http://localhost`, `http://127.0.0.1`, or `http://[::1]` with optional port. 5. **Ecosystem Domain Reservation**: External clients cannot register redirect URIs pointing to official SSO ecosystem domains (`sso555.com`, `admin.sso555.com`, `develop.sso555.com`, `help.sso555.com`, `policies.sso555.com`, `drama555.cc`, `me555.cc`, etc.). #### Successful Response (`HTTP 201 Created`) ```json { "app": { "id": "sso_client_pub_01h8x9p3q4r5s6t7u8v9w0", "clientId": "sso_client_pub_01h8x9p3q4r5s6t7u8v9w0", "name": "My Agent Service", "description": "Autonomous coding assistant connecting via local loopback", "clientType": "public", "redirectUris": [ "http://127.0.0.1:4000/callback", "https://myapp.example.com/auth/callback" ], "scopes": "openid profile email", "grantTypes": ["authorization_code"], "isActive": true, "createdAt": "2026-10-17T12:00:00.000Z", "updatedAt": "2026-10-17T12:00:00.000Z" }, "plaintextSecret": null } ``` *Note: For confidential clients (`clientType: "confidential"`), `plaintextSecret` is returned as a 48-hex character string (`sec_<48-hex>`) strictly ONCE. The IdP securely hashes secrets with SHA-256 before persisting.* ### 7.2 Application Management Endpoints - **List Applications**: `GET /api/developer/apps` - Returns `{ apps: DeveloperAppResponse[], quota: { used: number, maxApps: 5, remaining: number } }`. - **Get Application**: `GET /api/developer/apps/:clientId` - **Update Metadata**: `PATCH /api/developer/apps/:clientId` - Accepts `name`, `redirectUris`, `description`, `origin`. - **Rotate Secret**: `POST /api/developer/apps/:clientId/rotate-secret` - Regenerates secret for confidential client; immediately revokes old secret. Returns `{ plaintextSecret: "sec_..." }`. - **Delete Application**: `DELETE /api/developer/apps/:clientId` - Permanently removes client and revokes all issued tokens. --- ## 8. AI Agent, LLM & MCP Server Integration Guidance ### 8.1 Autonomous Desktop & CLI Agents: RFC 8252 Loopback Flow For command-line coding assistants, desktop agent daemons, and IDE extensions (e.g. Antigravity, Cursor, Claude Code, Copilot): ```typescript import http from 'node:http'; import { randomBytes, createHash } from 'node:crypto'; import { exec } from 'node:child_process'; async function authenticateCliAgent() { // 1. Generate cryptographic PKCE verifier and state const verifier = randomBytes(32).toString('base64url'); const challenge = createHash('sha256').update(verifier).digest('base64url'); const state = randomBytes(16).toString('base64url'); // 2. Start temporary local loopback server const server = http.createServer(async (req, res) => { const url = new URL(req.url!, 'http://127.0.0.1:4000'); if (url.pathname === '/callback') { const code = url.searchParams.get('code'); const returnedState = url.searchParams.get('state'); if (returnedState !== state || !code) { res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Authentication failed: state mismatch or missing code.'); server.close(); return; } // 3. Exchange code for tokens const tokenRes = await fetch('https://sso555.com/oidc/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'authorization_code', client_id: 'sso_client_pub_YOUR_CLIENT_ID', redirect_uri: 'http://127.0.0.1:4000/callback', code, code_verifier: verifier, }), }); const tokens = await tokenRes.json(); res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('

Authentication successful!

You can close this tab and return to your CLI agent.

'); server.close(); console.log('Access Token acquired:', tokens.access_token); } }); server.listen(4000, '127.0.0.1', () => { const authUrl = `https://sso555.com/oidc/authorize?client_id=sso_client_pub_YOUR_CLIENT_ID&redirect_uri=http://127.0.0.1:4000/callback&response_type=code&scope=openid profile email&code_challenge=${challenge}&code_challenge_method=S256&state=${state}`; // Open system browser exec(`open "${authUrl}"`); }); } ``` ### 8.2 Model Context Protocol (MCP) Server: Bearer Token Verification When deploying an MCP server or backend tool that acts as a protected Resource Server, authenticate inbound tool requests using SSO 555 RS256 Bearer tokens: ```typescript import { createRemoteJWKSet, jwtVerify } from 'jose'; // Cached remote keystore const JWKS = createRemoteJWKSet(new URL('https://sso555.com/.well-known/jwks.json')); export async function verifyMcpToolRequest(authHeader: string | undefined, expectedClientId: string) { if (!authHeader || !authHeader.startsWith('Bearer ')) { throw new Error('Missing or malformed Authorization header'); } const token = authHeader.replace(/^Bearer\s+/, '').trim(); // Verify RS256 signature, expiry, issuer, and audience const { payload } = await jwtVerify(token, JWKS, { issuer: 'https://sso555.com', audience: expectedClientId, }); return { userId: payload.sub, email: payload.email, name: payload.name, scopes: (payload.scope as string)?.split(' ') || [], }; } ``` ### 8.3 In-Browser Agents & Web Embeds: Modal Popup Flow For web apps and browser extensions that avoid full-page redirects: - Launch authorization popup window with parameter `display=popup`: `https://sso555.com/oidc/authorize?client_id=...&redirect_uri=https://sso555.com/oidc/popup-callback&display=popup&...` - The IdP renders a streamlined popup UI without full site navigation. - Upon completion, `/oidc/popup-callback` sends a `postMessage({ type: 'SSO_AUTH_SUCCESS', code, state })` to `window.opener` and self-terminates.