UNPKG

@trifrost/core

Version:

Blazingly fast, runtime-agnostic server framework for modern edge and node environments

44 lines (43 loc) 1.97 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Sym_TriFrostMiddlewareBearerAuth = void 0; exports.BearerAuth = BearerAuth; const constants_1 = require("../../types/constants"); const types_1 = require("./types"); /* Specific symbol attached to auth mware to identify them by */ exports.Sym_TriFrostMiddlewareBearerAuth = Symbol('TriFrost.Middleware.BearerAuth'); /** * HTTP Bearer Token Authentication middleware. * * This middleware extracts the `Authorization` header using the Bearer scheme, * retrieves the token, and calls the provided validate() function. If valid, * the `$auth` state is set on the context. * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#bearer_authentication * * @example * .use(BearerAuth({ * validate: (ctx, token) => token === ctx.env.API_TOKEN * })) */ function BearerAuth(opts) { if (typeof opts?.validate !== 'function') throw new Error('TriFrostMiddleware@BearerAuth: A validate function must be provided'); const mware = async function TriFrostBearerAuth(ctx) { const raw = ctx.headers.authorization; if (typeof raw !== 'string' || !raw.startsWith('Bearer ')) return ctx.status(401); const token = raw.slice(7).trim(); const result = await opts.validate(ctx, token); if (!result) return ctx.status(401); const authenticated = result === true ? { token } : result; return ctx.setState({ $auth: authenticated }); }; /* Add symbols for introspection/use further down the line */ Reflect.set(mware, constants_1.Sym_TriFrostName, 'TriFrostBearerAuth'); Reflect.set(mware, constants_1.Sym_TriFrostDescription, 'HTTP Bearer Token Authentication middleware'); Reflect.set(mware, types_1.Sym_TriFrostMiddlewareAuth, true); Reflect.set(mware, constants_1.Sym_TriFrostFingerPrint, exports.Sym_TriFrostMiddlewareBearerAuth); return mware; }