@prism-engineer/router
Version:
Type-safe Express.js router with automatic client generation
332 lines • 14.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const vitest_1 = require("vitest");
const createAuthScheme_1 = require("../../createAuthScheme");
(0, vitest_1.describe)('Authentication - Auth Scheme Creation', () => {
(0, vitest_1.beforeEach)(() => {
vitest_1.vi.clearAllMocks();
});
(0, vitest_1.it)('should create a basic auth scheme with name and validate function', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'basic',
validate: async (req) => {
return { user: { id: '1', name: 'John' } };
}
});
(0, vitest_1.expect)(authScheme).toBeDefined();
(0, vitest_1.expect)(authScheme.name).toBe('basic');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create a bearer token auth scheme', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'bearer',
validate: async (req) => {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
throw new Error('Invalid authorization header');
}
return { user: { id: '1', token: authHeader.slice(7) } };
}
});
(0, vitest_1.expect)(authScheme.name).toBe('bearer');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create an API key auth scheme', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'apiKey',
validate: async (req) => {
const apiKey = req.headers['x-api-key'];
if (!apiKey) {
throw new Error('API key required');
}
return { client: { id: '1', apiKey } };
}
});
(0, vitest_1.expect)(authScheme.name).toBe('apiKey');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create a session-based auth scheme', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'session',
validate: async (req) => {
const sessionId = req.headers.cookie?.match(/sessionId=([^;]+)/)?.[1];
if (!sessionId) {
throw new Error('Session required');
}
return { session: { id: sessionId, userId: '1' } };
}
});
(0, vitest_1.expect)(authScheme.name).toBe('session');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create a custom auth scheme with complex validation', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'custom',
validate: async (req) => {
const signature = req.headers['x-signature'];
const timestamp = req.headers['x-timestamp'];
if (!signature || !timestamp) {
throw new Error('Missing authentication headers');
}
// Simulate signature validation
if (signature !== 'valid-signature') {
throw new Error('Invalid signature');
}
return {
client: {
id: '1',
verified: true,
timestamp: parseInt(timestamp)
}
};
}
});
(0, vitest_1.expect)(authScheme.name).toBe('custom');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create auth scheme with typed context', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'typed',
validate: async (req) => {
return {
user: {
id: '1',
role: 'admin',
permissions: ['read', 'write', 'delete']
}
};
}
});
(0, vitest_1.expect)(authScheme.name).toBe('typed');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create auth scheme with minimal configuration', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'minimal',
validate: async () => ({ authenticated: true })
});
(0, vitest_1.expect)(authScheme.name).toBe('minimal');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create auth scheme with async validation', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'async',
validate: async (req) => {
// Simulate async database lookup
await new Promise(resolve => setTimeout(resolve, 1));
const token = req.headers.authorization;
if (!token) {
throw new Error('Token required');
}
return { user: { id: '1', verified: true } };
}
});
(0, vitest_1.expect)(authScheme.name).toBe('async');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create auth scheme with promise-based validation', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'promise',
validate: (req) => {
return Promise.resolve({ user: { id: '1' } });
}
});
(0, vitest_1.expect)(authScheme.name).toBe('promise');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create auth scheme with error handling', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'error-handling',
validate: async (req) => {
try {
const auth = req.headers.authorization;
if (!auth) {
throw new Error('No authorization header');
}
return { user: { id: '1' } };
}
catch (error) {
throw new Error(`Authentication failed: ${error.message}`);
}
}
});
(0, vitest_1.expect)(authScheme.name).toBe('error-handling');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create auth scheme with multiple validation steps', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'multi-step',
validate: async (req) => {
// Step 1: Check header presence
const authHeader = req.headers.authorization;
if (!authHeader) {
throw new Error('Authorization header required');
}
// Step 2: Validate format
if (!authHeader.startsWith('Bearer ')) {
throw new Error('Invalid authorization format');
}
// Step 3: Extract and validate token
const token = authHeader.slice(7);
if (token.length < 10) {
throw new Error('Invalid token length');
}
// Step 4: Return context
return {
user: {
id: '1',
token,
validated: true
}
};
}
});
(0, vitest_1.expect)(authScheme.name).toBe('multi-step');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create auth scheme with environment-based validation', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'env-based',
validate: async (req) => {
const isDevelopment = process.env.NODE_ENV === 'development';
if (isDevelopment) {
// Relaxed validation for development
return { user: { id: 'dev-user', role: 'developer' } };
}
// Strict validation for production
const token = req.headers.authorization;
if (!token || !token.startsWith('Bearer ')) {
throw new Error('Valid bearer token required');
}
return { user: { id: '1', role: 'user' } };
}
});
(0, vitest_1.expect)(authScheme.name).toBe('env-based');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create auth scheme with request context validation', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'context-aware',
validate: async (req) => {
const userAgent = req.headers['user-agent'];
const clientIp = req.ip || req.connection?.remoteAddress;
return {
user: { id: '1' },
context: {
userAgent,
clientIp,
timestamp: Date.now()
}
};
}
});
(0, vitest_1.expect)(authScheme.name).toBe('context-aware');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create auth scheme with role-based context', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'role-based',
validate: async (req) => {
const role = req.headers['x-user-role'];
const permissions = {
admin: ['read', 'write', 'delete', 'manage'],
editor: ['read', 'write'],
viewer: ['read']
};
return {
user: {
id: '1',
role: role || 'viewer',
permissions: permissions[role] || permissions.viewer
}
};
}
});
(0, vitest_1.expect)(authScheme.name).toBe('role-based');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create auth scheme with external service validation', () => {
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'external-service',
validate: async (req) => {
const token = req.headers.authorization?.replace('Bearer ', '');
// Simulate external service call
const mockExternalValidation = async (token) => {
if (token === 'valid-external-token') {
return { userId: '1', scope: 'read:profile' };
}
throw new Error('Invalid token');
};
try {
const result = await mockExternalValidation(token);
return {
user: {
id: result.userId,
scope: result.scope,
provider: 'external'
}
};
}
catch {
throw new Error('External validation failed');
}
}
});
(0, vitest_1.expect)(authScheme.name).toBe('external-service');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should create auth scheme with caching logic', () => {
const cache = new Map();
const authScheme = (0, createAuthScheme_1.createAuthScheme)({
name: 'cached',
validate: async (req) => {
const token = req.headers.authorization;
// Check cache first
if (cache.has(token)) {
return cache.get(token);
}
// Simulate expensive validation
await new Promise(resolve => setTimeout(resolve, 1));
const context = { user: { id: '1', cached: true } };
// Cache result
cache.set(token, context);
return context;
}
});
(0, vitest_1.expect)(authScheme.name).toBe('cached');
(0, vitest_1.expect)(typeof authScheme.validate).toBe('function');
});
(0, vitest_1.it)('should handle auth scheme creation with undefined name', () => {
(0, vitest_1.expect)(() => {
(0, createAuthScheme_1.createAuthScheme)({
name: undefined,
validate: async () => ({ user: { id: '1' } })
});
}).toThrow();
});
(0, vitest_1.it)('should handle auth scheme creation with empty name', () => {
(0, vitest_1.expect)(() => {
(0, createAuthScheme_1.createAuthScheme)({
name: '',
validate: async () => ({ user: { id: '1' } })
});
}).toThrow();
});
(0, vitest_1.it)('should handle auth scheme creation with undefined validate function', () => {
(0, vitest_1.expect)(() => {
(0, createAuthScheme_1.createAuthScheme)({
name: 'test',
validate: undefined
});
}).toThrow();
});
(0, vitest_1.it)('should handle auth scheme creation with non-function validate', () => {
(0, vitest_1.expect)(() => {
(0, createAuthScheme_1.createAuthScheme)({
name: 'test',
validate: 'not a function'
});
}).toThrow();
});
});
//# sourceMappingURL=auth-scheme-creation.test.js.map