auth-server-helper/lib/Gateway.ts

211 lines
5.7 KiB
TypeScript
Raw Normal View History

/*
* Copyright (C) Sapphirecode - All Rights Reserved
* This file is part of Auth-Server-Helper which is released under MIT.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, December 2020
*/
2020-12-28 16:53:08 +01:00
import { IncomingMessage, ServerResponse } from 'http';
2020-12-13 12:26:40 +01:00
import { run_regex } from '@sapphirecode/utilities';
2020-12-19 15:40:49 +01:00
import authority from './Authority';
2022-01-04 21:32:04 +01:00
import { AuthRequest, AccessSettings } from './AuthHandler';
2022-01-05 12:32:04 +01:00
import { debug } from './debug';
const logger = debug ('gateway');
2020-12-12 15:53:47 +01:00
2020-12-28 16:53:08 +01:00
type AnyFunc = (...args: unknown[]) => unknown;
type Gateway = (
req: IncomingMessage,
res: ServerResponse, next: AnyFunc
) => unknown;
2020-12-06 15:51:59 +01:00
2022-01-04 21:32:04 +01:00
interface RefreshSettings extends AccessSettings {
leave_open?: never;
redirect_to?: never;
2022-01-05 08:11:18 +01:00
data?: never;
2022-01-04 21:32:04 +01:00
}
2020-12-06 15:51:59 +01:00
interface GatewayOptions {
redirect_url?: string;
2020-12-13 12:26:40 +01:00
cookie_name?: string;
2022-01-04 21:32:04 +01:00
refresh_cookie_name?: string;
refresh_settings?: RefreshSettings;
}
interface AuthCookies {
access_cookie: string | null;
refresh_cookie: string | null;
2020-12-06 15:51:59 +01:00
}
class GatewayClass {
2020-12-06 21:06:40 +01:00
private _options: GatewayOptions;
2020-12-06 15:51:59 +01:00
public constructor (options: GatewayOptions = {}) {
2022-01-05 12:32:04 +01:00
logger ('creating new gateway');
2022-01-04 21:32:04 +01:00
if (
typeof options.cookie_name === 'string'
&& options.cookie_name === options.refresh_cookie_name
)
throw new Error ('access and refresh cookies cannot have the same name');
2020-12-06 21:06:40 +01:00
this._options = options;
2020-12-06 15:51:59 +01:00
}
public deny (res: ServerResponse): void {
2022-01-05 12:32:04 +01:00
logger ('denied http request');
res.statusCode = 403;
2022-01-03 14:46:12 +01:00
res.end ();
}
public redirect (res: ServerResponse): void {
2022-01-05 12:32:04 +01:00
logger ('redirecting http request to %s', this._options.redirect_url);
2022-01-03 14:46:12 +01:00
if (typeof this._options.redirect_url !== 'string') {
2022-01-05 12:32:04 +01:00
logger ('no redirect url defined');
2022-01-03 14:46:12 +01:00
this.deny (res);
return;
}
2020-12-06 15:51:59 +01:00
res.statusCode = 302;
2020-12-06 21:06:40 +01:00
res.setHeader ('Location', this._options.redirect_url);
2020-12-06 15:51:59 +01:00
res.end ();
}
public get_header_auth (req: IncomingMessage): string | null {
2022-01-05 12:32:04 +01:00
logger ('extracting authorization header');
2020-12-28 16:53:08 +01:00
const auth_header = req.headers.authorization;
const auth = (/(?<type>\w+) (?<data>.*)/u).exec (auth_header || '');
2020-12-13 12:26:40 +01:00
if (auth === null)
return null;
2020-12-28 16:53:08 +01:00
if (auth.groups?.type !== 'Bearer')
2020-12-13 12:26:40 +01:00
return null;
2022-01-05 12:32:04 +01:00
logger ('found bearer token');
2020-12-28 16:53:08 +01:00
return auth.groups?.data;
2020-12-13 12:26:40 +01:00
}
2022-01-04 21:32:04 +01:00
public get_cookie_auth (req: IncomingMessage): AuthCookies {
2022-01-05 12:32:04 +01:00
logger ('extracting tokens from cookies');
2022-01-04 21:32:04 +01:00
const result: AuthCookies = {
access_cookie: null,
refresh_cookie: null
};
const cookie_regex = /(?:^|;)\s*(?<name>[^;=]+)=(?<value>[^;]+)/gu;
2020-12-13 12:26:40 +01:00
run_regex (
2022-01-04 21:32:04 +01:00
cookie_regex,
2020-12-28 16:53:08 +01:00
req.headers.cookie,
(res: RegExpMatchArray) => {
2022-01-05 12:32:04 +01:00
logger ('parsing cookie %s', res.groups?.name);
2020-12-28 16:53:08 +01:00
if (res.groups?.name === this._options.cookie_name)
2022-01-04 21:32:04 +01:00
result.access_cookie = res.groups?.value as string;
else if (res.groups?.name === this._options.refresh_cookie_name)
result.refresh_cookie = res.groups?.value as string;
2020-12-13 12:26:40 +01:00
}
);
2022-01-04 21:32:04 +01:00
2022-01-05 12:32:04 +01:00
logger ('parsed cookies: %O', result);
2022-01-04 21:32:04 +01:00
return result;
2020-12-13 12:26:40 +01:00
}
public authenticate (req: IncomingMessage): boolean {
2022-01-05 12:32:04 +01:00
logger ('authenticating incoming request');
2022-01-04 21:32:04 +01:00
const cookies = this.get_cookie_auth (req);
2020-12-13 12:26:40 +01:00
let auth = this.get_header_auth (req);
if (auth === null)
2022-01-04 21:32:04 +01:00
auth = cookies.access_cookie;
2022-01-05 12:32:04 +01:00
if (auth === null) {
logger ('found no auth token');
2020-12-12 15:53:47 +01:00
return false;
2022-01-05 12:32:04 +01:00
}
2020-12-12 15:53:47 +01:00
2021-01-03 15:32:29 +01:00
const ver = authority.verify (auth);
2022-01-05 12:32:04 +01:00
logger ('setting connection info');
2021-01-05 15:59:06 +01:00
const con = req.connection as unknown as Record<string, unknown>;
con.auth = { token_id: ver.id, token_data: ver.data };
2021-01-03 15:32:29 +01:00
2022-01-05 12:32:04 +01:00
logger ('token valid: %s', ver.authorized);
2021-01-03 15:32:29 +01:00
return ver.authorized;
2020-12-06 15:51:59 +01:00
}
2022-01-04 21:32:04 +01:00
public async try_refresh (
req: IncomingMessage,
res: ServerResponse
): Promise<boolean> {
if (
typeof this._options.refresh_cookie_name === 'undefined'
|| typeof this._options.refresh_settings === 'undefined'
)
return false;
2022-01-05 12:32:04 +01:00
logger ('trying to apply refresh token');
2022-01-04 21:32:04 +01:00
const refresh = this.get_cookie_auth (req).refresh_cookie;
2022-01-05 12:32:04 +01:00
if (refresh === null) {
logger ('could not find refresh token');
2022-01-04 21:32:04 +01:00
return false;
2022-01-05 12:32:04 +01:00
}
2022-01-04 21:32:04 +01:00
const ver = authority.verify (refresh);
if (ver.type === 'refresh_token' && ver.valid) {
2022-01-05 12:32:04 +01:00
logger ('refresh token valid, generating new tokens');
2022-01-04 21:32:04 +01:00
const auth_request = new AuthRequest (
req,
res,
''
, this._options.cookie_name,
this._options.refresh_cookie_name
);
const refresh_result = await auth_request.allow_access ({
...this._options.refresh_settings,
2022-01-05 08:11:18 +01:00
data: ver.data,
leave_open: true
2022-01-04 21:32:04 +01:00
});
2022-01-05 12:32:04 +01:00
logger ('setting connection info');
2022-01-04 21:32:04 +01:00
const con = req.connection as unknown as Record<string, unknown>;
con.auth = {
token_id: refresh_result.access_token_id,
token_data: this._options.refresh_settings.data
};
2022-01-05 12:32:04 +01:00
logger ('tokens refreshed');
2022-01-04 21:32:04 +01:00
return true;
}
2022-01-05 12:32:04 +01:00
logger ('refresh token invalid');
2022-01-04 21:32:04 +01:00
return false;
}
public async process_request (
2020-12-28 16:53:08 +01:00
req: IncomingMessage,
res: ServerResponse,
2020-12-06 21:06:40 +01:00
next: AnyFunc
2022-01-04 21:32:04 +01:00
): Promise<unknown> {
2022-01-05 12:32:04 +01:00
logger ('processing incoming http request');
if (this.authenticate (req)) {
logger ('authentification successful, calling next handler');
2020-12-06 21:06:40 +01:00
return next ();
2022-01-05 12:32:04 +01:00
}
if (await this.try_refresh (req, res)) {
logger ('refresh successful, calling next handler');
2022-01-04 21:32:04 +01:00
return next ();
2022-01-05 12:32:04 +01:00
}
logger ('could not verify session, redirecting to auth gateway');
2020-12-06 21:06:40 +01:00
return this.redirect (res);
2020-12-06 15:51:59 +01:00
}
}
export default function create_gateway (options: GatewayOptions): Gateway {
const g = new GatewayClass (options);
2020-12-28 16:53:08 +01:00
return g.process_request.bind (g);
2020-12-06 15:51:59 +01:00
}
2020-12-28 16:53:08 +01:00
2021-01-05 22:10:41 +01:00
export {
AnyFunc,
Gateway,
GatewayOptions,
2022-01-05 08:11:18 +01:00
GatewayClass,
RefreshSettings
2021-01-05 22:10:41 +01:00
};