API Reference

Complete reference for the @quantumshield/qauth TypeScript SDK.

QAuthServer

class

Server-side class for creating and validating QAuth tokens. Generates Ed25519 signing keys on construction.

Constructor

new QAuthServer(config: QAuthConfig)
ParameterTypeDescription
configQAuthConfigServer configuration with issuer and audience URLs.

.getPublicKeys()

returns IssuerKeys
getPublicKeys(): IssuerKeys

Returns the public keys for this server instance. Share these with QAuthValidator instances on API servers.

qauthserver.ts
1const server = new QAuthServer({
2 issuer: 'https://auth.example.com',
3 audience: 'https://api.example.com',
4});
5const keys = server.getPublicKeys();
6// => { keyId: '...', ed25519PublicKey: Uint8Array, encryptionKey: Uint8Array }

.createToken()

returns string
createToken(options: TokenOptions): string

Creates a new QAuth token signed with Ed25519. The token contains the payload claims encrypted and signed.

ParameterTypeDescription
options.subjectstring | Uint8ArrayThe token subject (usually user ID).
options.policyRefstringPolicy document URN reference.
options.audience?string | string[]Token audience(s). Defaults to server config audience.
options.validitySeconds?numberToken validity in seconds. Defaults to 3600 (1 hour).
options.clientKey?Uint8ArrayClient's public key for proof-of-possession binding.
options.deviceKey?Uint8ArrayDevice public key for device binding.
options.claims?Record<string, unknown>Custom claims to embed in the token.
qauthserver.ts
1const token = server.createToken({
2 subject: 'user-123',
3 policyRef: 'urn:qauth:policy:default',
4 validitySeconds: 3600,
5 claims: { email: 'user@example.com', roles: ['admin'] },
6});

.validateToken()

returns TokenPayload
validateToken(token: string): TokenPayload

Validates a QAuth token by verifying the signature, checking expiration, not-before, issuer, and audience.

ParameterTypeDescription
tokenstringThe QAuth token string to validate.

Throws: Error if the token is invalid, expired, or has wrong issuer/audience.

qauthserver.ts
1try {
2 const payload = server.validateToken(token);
3 console.log('User:', payload.sub);
4 console.log('Expires:', new Date(payload.exp * 1000));
5} catch (err) {
6 console.error('Token invalid:', err.message);
7}

QAuthClient

class

Client-side class for proof-of-possession. Generates an Ed25519 keypair for signing request proofs.

Constructor

new QAuthClient()

.getPublicKey()

returns Uint8Array
getPublicKey(): Uint8Array

Returns the client's public key. Send this to the server during authentication to enable proof validation.

qauthclient.ts
1const client = new QAuthClient();
2const publicKey = client.getPublicKey();
3// Send to server during signup/login

.createProof()

returns string
createProof(method: string, uri: string, token: string, body?: Uint8Array | string): string

Creates a proof-of-possession for an API request. The proof binds the token to the specific HTTP request (method, URI, body).

ParameterTypeDescription
methodstringHTTP method (GET, POST, PUT, DELETE, etc.).
uristringRequest URI path (e.g., '/api/resource').
tokenstringThe QAuth access token.
body?Uint8Array | stringRequest body (for POST/PUT requests).
qauthclient.ts
1const proof = client.createProof('GET', '/api/users/me', token);
2
3// Include in request
4fetch('/api/users/me', {
5 headers: {
6 'Authorization': `QAuth ${token}`,
7 'X-QAuth-Proof': proof,
8 },
9});

QAuthValidator

class

Standalone token validator using pre-shared issuer public keys. Deploy on API servers that need to validate tokens without access to the signing private key.

Constructor

new QAuthValidator(keys: IssuerKeys, config: QAuthConfig)
ParameterTypeDescription
keysIssuerKeysIssuer's public keys obtained from QAuthServer.getPublicKeys().
configQAuthConfigExpected issuer and audience for validation.

.validate()

returns TokenPayload
validate(token: string): TokenPayload

Validates a token against the pre-shared public keys. Checks signature, expiration, not-before, issuer, and audience.

ParameterTypeDescription
tokenstringThe QAuth token string to validate.

Throws: Error if validation fails.

qauthvalidator.ts
1const validator = new QAuthValidator(publicKeys, {
2 issuer: 'https://auth.example.com',
3 audience: 'https://api.example.com',
4});
5const payload = validator.validate(token);

ProofValidator

class

Validates proof-of-possession proofs. Verifies that the request was made by the holder of the client's private key.

Constructor

new ProofValidator(clientPublicKey: Uint8Array)
ParameterTypeDescription
clientPublicKeyUint8ArrayThe client's Ed25519 public key (32 bytes).

.validate()

returns boolean
validate(proof: string, method: string, uri: string, token: string, body?: Uint8Array | string): boolean

Validates a proof of possession. Checks timestamp (60-second window), method/URI binding, body hash, token hash, and signature.

ParameterTypeDescription
proofstringThe base64URL-encoded proof string from X-QAuth-Proof header.
methodstringThe HTTP method of the request.
uristringThe URI of the request.
tokenstringThe QAuth token from Authorization header.
body?Uint8Array | stringThe request body, if present.
proofvalidator.ts
1const proofValidator = new ProofValidator(clientPublicKey);
2const isValid = proofValidator.validate(
3 proof, 'POST', '/api/data', token, requestBody
4);
5if (!isValid) {
6 return res.status(401).json({ error: 'Invalid proof' });
7}

PolicyEngine

class

Evaluates authorization policies. Load policy documents and evaluate them against request contexts. Supports glob patterns, conditions, and priority ordering.

Constructor

new PolicyEngine()

.loadPolicy()

returns void
loadPolicy(policy: Policy): void

Loads a policy document into the engine. Policies are stored by ID and can be updated by loading a new policy with the same ID.

ParameterTypeDescription
policyPolicyThe policy document to load.
policyengine.ts
1const engine = new PolicyEngine();
2engine.loadPolicy({
3 id: 'urn:qauth:policy:api',
4 version: '1.0',
5 issuer: 'https://auth.example.com',
6 rules: [
7 { id: 'allow-read', effect: 'allow', resources: ['*'], actions: ['read'] },
8 ],
9});

.evaluate()

returns EvaluationResult
evaluate(policyId: string, context: EvaluationContext): EvaluationResult

Evaluates a loaded policy against the given context. Rules are sorted by priority (highest first). Returns the first matching rule's effect, or 'deny' if no rule matches (default deny).

ParameterTypeDescription
policyIdstringThe policy ID to evaluate.
contextEvaluationContextThe request context (subject, resource, request).
policyengine.ts
1const result = engine.evaluate('urn:qauth:policy:api', {
2 subject: { id: 'user-123', attributes: { role: 'admin' } },
3 resource: { path: 'api/admin/users' },
4 request: { action: 'delete' },
5});
6if (result.effect === 'allow') {
7 // Proceed
8}

Interfaces

QAuthConfig

types.ts
1interface QAuthConfig {
2 issuer: string; // Token issuer URL (e.g., 'https://auth.example.com')
3 audience: string; // Expected audience URL (e.g., 'https://api.example.com')
4}

TokenOptions

types.ts
1interface TokenOptions {
2 subject: string | Uint8Array; // User identifier
3 policyRef: string; // Policy document URN
4 audience?: string | string[]; // Override audience (default: config.audience)
5 validitySeconds?: number; // Token TTL (default: 3600)
6 clientKey?: Uint8Array; // Client public key for PoP binding
7 deviceKey?: Uint8Array; // Device public key
8 claims?: Record<string, unknown>; // Custom payload claims
9}

TokenPayload

types.ts
1interface TokenPayload {
2 sub: string; // Subject (user ID)
3 iss: string; // Issuer URL
4 aud: string[]; // Audience URLs
5 exp: number; // Expiration (Unix timestamp)
6 iat: number; // Issued at (Unix timestamp)
7 nbf: number; // Not before (Unix timestamp)
8 jti: string; // Unique token ID
9 rid: string; // Revocation ID
10 pol: string; // Policy reference
11 cst: Record<string, unknown>; // Custom claims
12}

IssuerKeys

types.ts
1interface IssuerKeys {
2 keyId: string; // Key identifier (hex)
3 ed25519PublicKey: Uint8Array; // 32-byte Ed25519 public key
4 ed25519PrivateKey?: Uint8Array; // Private key (only on server)
5 encryptionKey: Uint8Array; // 32-byte encryption key
6}

Policy

types.ts
1interface Policy {
2 id: string; // Unique policy ID (URN)
3 version: string; // Policy version
4 issuer: string; // Policy issuer
5 name?: string; // Human-readable name
6 description?: string; // Policy description
7 rules: PolicyRule[]; // Authorization rules
8}

PolicyRule

types.ts
1interface PolicyRule {
2 id?: string; // Rule identifier
3 effect: 'allow' | 'deny'; // Rule effect
4 resources: string[]; // Resource patterns (glob)
5 actions: string[]; // Allowed/denied actions
6 conditions?: PolicyConditions; // Optional conditions
7 priority?: number; // Higher = evaluated first
8}

PolicyConditions

types.ts
1interface PolicyConditions {
2 time?: {
3 after?: string; // ISO 8601 time (e.g., '09:00')
4 before?: string; // ISO 8601 time (e.g., '17:00')
5 days?: string[]; // Allowed days (e.g., ['mon', 'tue'])
6 timezone?: string; // Timezone (e.g., 'America/New_York')
7 };
8 ip?: {
9 allow_ranges?: string[]; // Allowed CIDR ranges
10 deny_ranges?: string[]; // Denied CIDR ranges
11 };
12 mfa?: {
13 required?: boolean; // Require MFA verification
14 methods?: string[]; // Required MFA methods
15 };
16 custom?: Record<string, unknown>; // Custom conditions
17}

EvaluationContext

types.ts
1interface EvaluationContext {
2 subject?: {
3 id?: string;
4 roles?: string[];
5 groups?: string[];
6 attributes?: Record<string, unknown>;
7 };
8 resource?: {
9 path: string;
10 owner?: string;
11 type?: string;
12 attributes?: Record<string, unknown>;
13 };
14 request?: {
15 action: string;
16 method?: string;
17 ip?: string;
18 mfa_verified?: boolean;
19 };
20}

EvaluationResult

types.ts
1interface EvaluationResult {
2 effect: 'allow' | 'deny'; // Authorization decision
3 matched_rule: string | null; // ID of the matching rule
4 reason: string; // Human-readable explanation
5}

Utility Functions

getVersion()
string

Returns the SDK version (e.g., '0.1.0').

getProtocolVersion()
string

Returns the QAuth protocol version (e.g., '1.0').

initQAuth()
Promise<void>

No-op for the pure JS implementation. Included for API compatibility.

isInitialized()
boolean

Always returns true for the pure JS implementation.

toBytes(data: string | Uint8Array)
Uint8Array

Converts a string to UTF-8 bytes.

bytesToHex(bytes: Uint8Array)
string

Converts bytes to a hex string.

hexToBytes(hex: string)
Uint8Array

Converts a hex string to bytes.