diff --git a/src/auth.ts b/src/auth.ts index dac35a0..74fea29 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -203,6 +203,13 @@ export const onStart = (authFile = 'auth.json') => new Promise((resolve, reject) return await createNewUser('ass', nanoid(), true); } + // Check if the CLI key is set + if (!json.cliKey || json.cliKey.length === 0) { + log.debug('CLI key is not set, generating new key'); + json.cliKey = nanoid(32); + fs.writeJsonSync(file, json, { spaces: '\t' }); + } + // Add users to the map return json.users.forEach((user) => users.push(user)); }) @@ -224,6 +231,14 @@ export const findFromToken = (token: string) => { */ export const verifyValidToken = (req: Request) => { return req.headers.authorization && findFromToken(req.headers.authorization); + +/** + * Verifies that the CLI key in the request matches the one in auth.json + * @since v0.14.0 + */ +export const verifyCliKey = (req: Request) => { + const cliKey: string = fs.readJsonSync(path('auth.json')).cliKey; + return req.headers.authorization != null && req.headers.authorization === cliKey; }; // todo: move inside of onStart (currently broken) diff --git a/src/routers/api.ts b/src/routers/api.ts index 13f9f93..fb45e92 100644 --- a/src/routers/api.ts +++ b/src/routers/api.ts @@ -5,7 +5,7 @@ */ import { Router, Request, Response, NextFunction } from 'express'; -import { findFromToken, setUserPassword, users, createNewUser } from '../auth'; +import { findFromToken, setUserPassword, users, createNewUser, verifyCliKey } from '../auth'; import { log } from '../utils'; import { data } from '../data'; import { User } from '../types/auth'; @@ -21,7 +21,7 @@ const RouterApi = Router(); */ const adminAuthMiddleware = (req: Request, res: Response, next: NextFunction) => { const user = findFromToken(req.headers.authorization ?? ''); - (user && user.admin) ? next() : res.sendStatus(401); + (verifyCliKey(req) || (user && user.admin)) ? next() : res.sendStatus(401); }; /** diff --git a/src/types/auth.d.ts b/src/types/auth.d.ts index 6234ac8..acabc7a 100644 --- a/src/types/auth.d.ts +++ b/src/types/auth.d.ts @@ -49,6 +49,11 @@ export interface Users { */ migrated?: boolean + /** + * Access key for the CLI + */ + cliKey?: string + /** * Extra metadata. Frontends can use this to store extra data. */