UNPKG

homebridge-config-ui-x

Version:

A web based management, configuration and control platform for Homebridge.

245 lines • 10.5 kB
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; import { Body, Controller, Get, Header, Inject, Post, Request, Res, UnauthorizedException, UseGuards, } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { AuthGuard } from '@nestjs/passport'; import { ApiBearerAuth, ApiExcludeEndpoint, ApiOperation, ApiTags } from '@nestjs/swagger'; import { PluginsSettingsUiTicketService } from '../../modules/custom-plugins/plugins-settings-ui/plugins-settings-ui-ticket.service.js'; import { PluginsService } from '../../modules/plugins/plugins.service.js'; import { API_PREFIX } from '../api.constants.js'; import { ConfigService } from '../config/config.service.js'; import { Logger } from '../logger/logger.service.js'; import { AuthDto, RefreshTokenDto } from './auth.dto.js'; import { AuthService } from './auth.service.js'; import { CustomGuard } from './guards/custom.guard.js'; let AuthController = class AuthController { authService; configService; pluginsService; pluginUiTicketService; logger; jwtService; constructor(authService, configService, pluginsService, pluginUiTicketService, logger, jwtService) { this.authService = authService; this.configService = configService; this.pluginsService = pluginsService; this.pluginUiTicketService = pluginUiTicketService; this.logger = logger; this.jwtService = jwtService; } async signIn(body, req, res) { const result = await this.authService.signIn(body.username, body.password, body.otp, req.ip); this.setRefreshCookie(res, result.access_token, req.protocol === 'https'); return result; } getSettings(req) { const settings = this.configService.uiSettings(req.user); if (req.user && !this.pluginsService.isPluginManagementInProgress) { const cachedPlugins = this.pluginsService.getCachedInstalledPlugins(); if (cachedPlugins) { settings.env.hasInstalledPlugins = cachedPlugins.some(p => p.name !== this.configService.name); } else { void this.pluginsService.getInstalledPlugins().catch((e) => { this.logger.error(`Failed to warm installed-plugins cache for /auth/settings: ${e.message}.`); }); } } return settings; } getCustomWallpaper() { return this.configService.streamCustomWallpaper(); } async getToken(req, res) { const result = await this.authService.generateNoAuthToken(); this.setRefreshCookie(res, result.access_token, req.protocol === 'https'); return result; } checkAuth() { return { status: 'OK' }; } async refreshToken(req, body = {}, res) { const result = await this.authService.refreshToken(req.user, body.reason); this.setRefreshCookie(res, result.access_token, req.protocol === 'https'); return result; } async restoreSession(req, res) { const payload = this.readRefreshCookie(req.headers?.cookie); if (!payload) { throw new UnauthorizedException(); } const result = await this.authService.refreshToken(payload, 'session-restore'); this.setRefreshCookie(res, result.access_token, req.protocol === 'https'); return result; } logout(req, res) { const username = req.user?.username ?? this.readLogoutUsername(req.headers.authorization); const pluginNames = username ? this.pluginUiTicketService.revokeUser(username) : []; res.header('Set-Cookie', this.buildClearedCookies(req.protocol === 'https', pluginNames)); return { status: 'OK' }; } readRefreshCookie(cookieHeader) { if (!cookieHeader) { return null; } for (const part of cookieHeader.split(';')) { const eq = part.indexOf('='); if (eq === -1) { continue; } if (part.slice(0, eq).trim() !== 'hb-refresh') { continue; } const value = part.slice(eq + 1).trim(); if (!value) { return null; } try { return this.jwtService.verify(value); } catch { return null; } } return null; } readLogoutUsername(authorization) { const [scheme, token] = authorization?.split(' ') ?? []; if (scheme?.toLowerCase() !== 'bearer' || !token) { return undefined; } try { const payload = this.jwtService.verify(token, { ignoreExpiration: true }); return typeof payload?.username === 'string' ? payload.username : undefined; } catch { return undefined; } } setRefreshCookie(res, token, secure) { res.header('Set-Cookie', this.buildRefreshCookie(token, secure)); } buildRefreshCookie(token, secure) { const maxAge = this.configService.ui.sessionTimeout || 28800; const secureFlag = secure ? '; Secure' : ''; return `hb-refresh=${token}; HttpOnly; SameSite=Strict; Path=${API_PREFIX}/auth/session; Max-Age=${maxAge}${secureFlag}`; } buildClearedCookies(secure, pluginNames = []) { const secureFlag = secure ? '; Secure' : ''; return [ `hb-refresh=; HttpOnly; SameSite=Strict; Path=${API_PREFIX}/auth/session; Max-Age=0${secureFlag}`, ...pluginNames.map(pluginName => `hb-plugin-ui=; HttpOnly; SameSite=Strict; Path=${API_PREFIX}/plugins/settings-ui/${encodeURIComponent(pluginName)}/; Max-Age=0${secureFlag}`), ]; } }; __decorate([ ApiOperation({ summary: 'Exchange a username and password for an authentication token.' }), Post('login'), __param(0, Body()), __param(1, Request()), __param(2, Res({ passthrough: true })), __metadata("design:type", Function), __metadata("design:paramtypes", [AuthDto, Object, Object]), __metadata("design:returntype", Promise) ], AuthController.prototype, "signIn", null); __decorate([ Get('/settings'), ApiOperation({ summary: 'Return settings required to load the UI before authentication.' }), UseGuards(CustomGuard), __param(0, Request()), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", void 0) ], AuthController.prototype, "getSettings", null); __decorate([ ApiExcludeEndpoint(), Get('/wallpaper/:hash'), Header('Content-Type', 'image/jpeg'), Header('Cache-Control', 'public,max-age=31536000,immutable'), __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], AuthController.prototype, "getCustomWallpaper", null); __decorate([ ApiOperation({ summary: 'This method can be used to obtain an access token ONLY when authentication has been disabled.' }), Post('/noauth'), __param(0, Request()), __param(1, Res({ passthrough: true })), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], AuthController.prototype, "getToken", null); __decorate([ ApiBearerAuth(), ApiOperation({ summary: 'Check to see if an authentication token is still valid.' }), UseGuards(AuthGuard()), Get('/check'), __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], AuthController.prototype, "checkAuth", null); __decorate([ ApiBearerAuth(), ApiOperation({ summary: 'Refresh the authentication token to extend the session.' }), UseGuards(AuthGuard()), Post('/refresh'), __param(0, Request()), __param(1, Body()), __param(2, Res({ passthrough: true })), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, RefreshTokenDto, Object]), __metadata("design:returntype", Promise) ], AuthController.prototype, "refreshToken", null); __decorate([ ApiOperation({ summary: 'Exchange the HttpOnly session cookie for an access token.', description: 'Called on page load so the access token never has to be persisted in browser storage.', }), Post('/session'), __param(0, Request()), __param(1, Res({ passthrough: true })), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", Promise) ], AuthController.prototype, "restoreSession", null); __decorate([ ApiOperation({ summary: 'Clear the session cookies.' }), ApiBearerAuth(), UseGuards(CustomGuard), Post('/logout'), __param(0, Request()), __param(1, Res({ passthrough: true })), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", void 0) ], AuthController.prototype, "logout", null); AuthController = __decorate([ ApiTags('Authentication'), Controller('auth'), __param(0, Inject(AuthService)), __param(1, Inject(ConfigService)), __param(2, Inject(PluginsService)), __param(3, Inject(PluginsSettingsUiTicketService)), __param(4, Inject(Logger)), __param(5, Inject(JwtService)), __metadata("design:paramtypes", [AuthService, ConfigService, PluginsService, PluginsSettingsUiTicketService, Logger, JwtService]) ], AuthController); export { AuthController }; //# sourceMappingURL=auth.controller.js.map