Overview
Cred is open-source OAuth2 credential delegation middleware for AI agents. When your agent needs to access a user’s Google Calendar, Slack workspace, or GitHub repos, Cred validates the agent’s identity, checks that the user consented, and returns a short-lived access token. Refresh tokens never leave the vault. You can run it self-hosted or fully local.
Two modes: Use @credninja/sdk with your own self-hosted Cred server for remote delegation, or use @credninja/oauth + @credninja/vault for fully local, self-contained operation. No hosted account required.
There are three actors in the Cred ecosystem:
Users
Authorize OAuth connections, grant delegation rights to apps, revoke access anytime.
Developers
Register apps, create agents, request delegated credentials via SDK.
Agents
Authenticate via cred_at_* tokens, request short-lived access tokens, call APIs directly.
Quick Start
1. Install the SDK
npm install @credninja/sdk2. Initialize the SDK
import { Cred } from '@credninja/sdk'; const cred = new Cred({ agentToken: process.env.CRED_AGENT_TOKEN, baseUrl: process.env.CRED_BASE_URL, });3. Request delegated credentials
try { const { accessToken } = await cred.delegate({ userId: 'user-123', service: 'google', appClientId: 'local', scopes: ['calendar.readonly'], }); // Use the access token with Google API const response = await fetch( 'https://www.googleapis.com/calendar/v3/calendars/primary/events', { headers: { Authorization: `Bearer ${accessToken}` } } ); } catch (error) { if (error instanceof ConsentRequiredError) { // Redirect user to consent URL return redirect(error.consentUrl); } throw error; }
See the full quickstart guide for a complete walkthrough.
OAuth 2.0 Flow
Cred implements the Authorization Code flow with PKCE (RFC 7636) for user consent. When a user authorizes an OAuth connection, Cred stores the refresh token encrypted in the vault.
Authorization Endpoint
GET /oauth/authorize
Redirects to consent screen. Params: client_id, redirect_uri, response_type=code, scope, code_challenge, code_challenge_method, state
Token Endpoint
POST /oauth/token
Exchange authorization code for access + refresh tokens. Supports authorization_code and refresh_token grant types.
Revocation Endpoint
POST /oauth/revoke
Revoke an access or refresh token. Cascades to invalidate all downstream delegations.
Credential Delegation
Cred’s delegation pipeline validates agent identity, checks user consent, and returns short-lived access tokens. Agents call third-party APIs directly with the delegated token.
7-Step Pipeline
- 1. Validate agent token - Verify cred_at_* token is valid and active
- 2. Lookup app - Find the application associated with the agent
- 3. Check consent - Verify user has authorized this app for the requested service
- 4. Validate scopes - Ensure requested scopes are subset of granted scopes
- 5. Check cached token - Return cached access token if still valid
- 6. Refresh if expired - Use refresh token to get new access token
- 7. Return token - Return short-lived access token to agent
POST https://cred.example.com/api/v1/delegate
Authorization: Bearer cred_at_...
Content-Type: application/json
{
"user_id": "user-123",
"service": "google",
"appClientId": "local",
"scopes": ["calendar.readonly"]
}Supported Services
Credential Vault
Users authorize OAuth connections through Cred. Refresh tokens are encrypted with AES-256-GCM and stored in the vault. They are decrypted only in-memory during token refresh and never exposed to agents or developers.
Encryption
AES-256-GCM with unique random IV per token. Authentication tags verify integrity. Self-hosted deployments control their own vault passphrase and storage path.
Isolation
Per-account cryptographic isolation using PBKDF2-derived keys. Cross-account access requires possession of the account DEK.
Revocation
Users can revoke any OAuth connection from /user/authorizations. Revocation cascades to invalidate all associated delegation grants.
Agent Authentication
Agents authenticate using bearer tokens (`cred_at_*`). In the OSS self-hosted server, you configure the shared agent token in the server environment.
# .env
AGENT_TOKEN=cred_at_your_agent_token
# Agent request
Authorization: Bearer cred_at_your_agent_tokenKeep the agent token on the agent side only. The self-hosted server compares it in constant time and never exposes refresh tokens to the agent.
Guard Policies
@credninja/guard is a composable policy engine that runs before any token is issued. Add rate limits, scope restrictions, time windows, and custom rules to control how agents access delegated credentials.
Install
npm install @credninja/guardWire into Server
import { createServer } from '@credninja/server';
import {
CredGuard,
rateLimitPolicy,
scopeFilterPolicy,
timeWindowPolicy,
} from '@credninja/guard';
const guard = new CredGuard({
policies: [
rateLimitPolicy({ maxRequests: 10, windowMs: 60_000 }),
scopeFilterPolicy({
allowedScopes: {
google: ['calendar.readonly', 'gmail.readonly'],
github: ['repo', 'read:user'],
},
}),
timeWindowPolicy({
allowedHours: { start: 9, end: 17 },
timezone: 'America/New_York',
}),
],
});
const { app } = createServer({ ...config, guard });Built-in Policies
rateLimitPolicy
Sliding-window rate limit per agent per provider. Configurable max requests and window duration.
scopeFilterPolicy
Restrict which OAuth scopes agents can request. Deny-by-default: scopes not explicitly listed are blocked. Optional narrowing mode reduces scopes instead of denying.
timeWindowPolicy
Restrict when delegations can occur. IANA timezone-aware. Configure allowed hours and days of week.
urlAllowlistPolicy
Restrict which URLs agents can call with delegated tokens. String prefix and regex matching.
maxTtlPolicy
Cap token lifetime. Per-provider overrides supported.
Policy Chain
Policies run in registration order. First DENY short-circuits. No policies registered means ALLOW (opt-in guardrails). Errors fail closed (DENY by default).
Custom Policies
import type { CredPolicy, GuardContext, PolicyResult } from '@credninja/guard';
const noWeekends: CredPolicy = {
name: 'no-weekends',
evaluate(ctx: GuardContext): PolicyResult {
const day = new Date(ctx.timestamp).getDay();
if (day === 0 || day === 6) {
return { decision: 'DENY', reason: 'No weekend access', policy: this.name };
}
return { decision: 'ALLOW', policy: this.name };
},
};MCP Tool Wrapper
Guard also wraps MCP tool handlers, applying the same policy chain to cred_use and cred_delegate tools.
const guardedHandler = guard.wrapMcpTool(handleUse);Every guard decision produces an Ed25519-compatible audit event. See the full Guard README for API reference.
API Reference
Developer Authentication
User Authentication (OAuth Flow)
These endpoints are used during app-initiated OAuth consent. Users authenticate here when redirected by an app requesting access.
OAuth
Delegation
Apps
Agents
User Authorizations
SDK
The official TypeScript SDK handles delegation requests, consent flow handling, and DID agent identity.
npm install @credninja/sdkimport { Cred, ConsentRequiredError } from '@credninja/sdk';
const cred = new Cred({
agentToken: process.env.CRED_AGENT_TOKEN,
appClientId: process.env.CRED_APP_CLIENT_ID,
});
// Request delegated credentials
try {
const { accessToken, expiresAt } = await cred.delegate({
userId: 'user-123',
service: 'slack',
scopes: ['channels:read', 'chat:write'],
});
// Use accessToken with Slack API directly
} catch (error) {
if (error instanceof ConsentRequiredError) {
// User hasn't authorized this app yet
// Redirect to error.consentUrl
}
}Python SDK
pip install cred-authfrom cred import Cred, ConsentRequiredError
cred = Cred(
agent_token=os.environ["CRED_AGENT_TOKEN"],
app_client_id=os.environ["CRED_APP_CLIENT_ID"],
)
try:
result = cred.delegate(
user_id="user-123",
service="github",
scopes=["repo", "read:user"],
)
# Use result.access_token with GitHub API
except ConsentRequiredError as e:
# Redirect user to e.consent_urlAudit & Compliance
Cred maintains an append-only audit log for all delegation requests, token issuances, and consent changes. Credential values are redacted from logs.
Delegation Receipts
JWS/Ed25519 signed receipts for each delegation event. Cryptographically verifiable audit trail that proves when and what was delegated.
Audit Log Retention
Delegation logs retained for 30 days. Includes timing data, status, agent identity, and redacted scope information.
User Authorizations
Users can view and revoke OAuth connections granted to apps at /user/authorizations.
Verify Receipt
import { verifyDelegationReceipt } from '@credninja/sdk';
const isValid = verifyDelegationReceipt(receipt);