File size: 8,915 Bytes
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/**
 * ╔═══════════════════════════════════════════════════════════════════════════╗
 * β•‘                    JWT AUTHENTICATION MIDDLEWARE                          β•‘
 * ╠═══════════════════════════════════════════════════════════════════════════╣
 * β•‘  Security Gate for WidgeTDC API                                          β•‘
 * β•‘  β€’ JWT token validation                                                   β•‘
 * β•‘  β€’ Role-based access control                                              β•‘
 * β•‘  β€’ API key fallback for service-to-service communication                 β•‘
 * β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
 */

import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

// ═══════════════════════════════════════════════════════════════════════════
// Types
// ═══════════════════════════════════════════════════════════════════════════

export interface JWTPayload {
    sub: string;        // User ID
    email?: string;
    name?: string;
    roles: string[];    // ['admin', 'user', 'agent', 'service']
    iat: number;        // Issued at
    exp: number;        // Expiration
}

export interface AuthenticatedRequest extends Request {
    user?: JWTPayload;
    authMethod?: 'jwt' | 'api-key' | 'bypass';
}

// ═══════════════════════════════════════════════════════════════════════════
// Configuration
// ═══════════════════════════════════════════════════════════════════════════

const JWT_SECRET = process.env.JWT_SECRET || 'widgetdc-dev-secret-change-in-production';
const API_KEY = process.env.API_KEY || 'widgetdc-dev-api-key';
const AUTH_ENABLED = process.env.AUTH_ENABLED !== 'false'; // Default: enabled
const DEV_BYPASS = process.env.NODE_ENV === 'development' && process.env.AUTH_BYPASS === 'true';

// Routes that don't require authentication
const PUBLIC_ROUTES = [
    '/health',
    '/api/health',
    '/api/mcp/route',  // MCP uses its own auth
    '/api/mcp/ws',     // WebSocket has its own handshake
];

// ═══════════════════════════════════════════════════════════════════════════
// Middleware Functions
// ═══════════════════════════════════════════════════════════════════════════

/**
 * Main authentication middleware
 * Checks JWT token or API key
 */
export function authenticate(req: AuthenticatedRequest, res: Response, next: NextFunction): void {
    // Skip auth in dev bypass mode
    if (DEV_BYPASS) {
        req.user = {
            sub: 'dev-user',
            email: 'dev@widgetdc.local',
            name: 'Development User',
            roles: ['admin', 'user', 'agent', 'service'],
            iat: Date.now() / 1000,
            exp: Date.now() / 1000 + 86400
        };
        req.authMethod = 'bypass';
        return next();
    }

    // Skip auth for public routes
    if (PUBLIC_ROUTES.some(route => req.path.startsWith(route))) {
        return next();
    }

    // Skip if auth is disabled
    if (!AUTH_ENABLED) {
        req.authMethod = 'bypass';
        return next();
    }

    // Try JWT token first (Authorization: Bearer <token>)
    const authHeader = req.headers.authorization;
    if (authHeader?.startsWith('Bearer ')) {
        const token = authHeader.substring(7);

        try {
            const payload = jwt.verify(token, JWT_SECRET) as JWTPayload;
            req.user = payload;
            req.authMethod = 'jwt';
            return next();
        } catch (error: any) {
            if (error.name === 'TokenExpiredError') {
                res.status(401).json({ error: 'Token expired', code: 'TOKEN_EXPIRED' });
                return;
            }
            // Token invalid, try API key
        }
    }

    // Try API key (X-API-Key header or query param)
    const apiKey = req.headers['x-api-key'] || req.query.api_key;
    if (apiKey === API_KEY) {
        req.user = {
            sub: 'api-service',
            roles: ['service'],
            iat: Date.now() / 1000,
            exp: Date.now() / 1000 + 86400
        };
        req.authMethod = 'api-key';
        return next();
    }

    // No valid auth found
    res.status(401).json({
        error: 'Authentication required',
        code: 'AUTH_REQUIRED',
        hint: 'Provide Bearer token or X-API-Key header'
    });
}

/**
 * Role-based authorization middleware factory
 * Usage: app.use('/admin', requireRole('admin'))
 */
export function requireRole(...roles: string[]) {
    return (req: AuthenticatedRequest, res: Response, next: NextFunction): void => {
        if (!req.user) {
            res.status(401).json({ error: 'Not authenticated', code: 'NOT_AUTHENTICATED' });
            return;
        }

        const hasRole = roles.some(role => req.user!.roles.includes(role));
        if (!hasRole) {
            res.status(403).json({
                error: 'Insufficient permissions',
                code: 'FORBIDDEN',
                required: roles,
                actual: req.user.roles
            });
            return;
        }

        next();
    };
}

/**
 * Optional authentication - populates req.user if token present, but doesn't require it
 */
export function optionalAuth(req: AuthenticatedRequest, res: Response, next: NextFunction): void {
    const authHeader = req.headers.authorization;

    if (authHeader?.startsWith('Bearer ')) {
        const token = authHeader.substring(7);

        try {
            const payload = jwt.verify(token, JWT_SECRET) as JWTPayload;
            req.user = payload;
            req.authMethod = 'jwt';
        } catch {
            // Invalid token, continue without user
        }
    }

    next();
}

// ═══════════════════════════════════════════════════════════════════════════
// Token Generation (for login endpoints)
// ═══════════════════════════════════════════════════════════════════════════

/**
 * Generate a JWT token for a user
 */
export function generateToken(payload: Omit<JWTPayload, 'iat' | 'exp'>, expiresIn: string = '24h'): string {
    return jwt.sign(payload, JWT_SECRET, { expiresIn } as jwt.SignOptions);
}

/**
 * Generate a refresh token (longer lived)
 */
export function generateRefreshToken(userId: string): string {
    return jwt.sign(
        { sub: userId, type: 'refresh' },
        JWT_SECRET,
        { expiresIn: '7d' }
    );
}

/**
 * Verify a refresh token and return user ID
 */
export function verifyRefreshToken(token: string): string | null {
    try {
        const payload = jwt.verify(token, JWT_SECRET) as any;
        if (payload.type === 'refresh') {
            return payload.sub;
        }
        return null;
    } catch {
        return null;
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Export
// ═══════════════════════════════════════════════════════════════════════════

export default {
    authenticate,
    requireRole,
    optionalAuth,
    generateToken,
    generateRefreshToken,
    verifyRefreshToken
};