Error response enhancements, CoreID auth client backend
This commit is contained in:
@@ -61,7 +61,7 @@ export class Authentication extends Unit {
|
||||
|
||||
Route.group(`/auth/${name}`, () => {
|
||||
this.providers[name].routes()
|
||||
}).pre(request => request.make<Middleware>(middleware, request).apply())
|
||||
}).pre(middleware)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import {Inject, Injectable} from '../../di'
|
||||
import {Awaitable, Maybe} from '../../util'
|
||||
import {Awaitable, HTTPStatus, Maybe} from '../../util'
|
||||
import {Authenticatable, AuthenticatableRepository} from '../types'
|
||||
import {Logging} from '../../service/Logging'
|
||||
import {UserAuthenticatedEvent} from '../event/UserAuthenticatedEvent'
|
||||
import {UserFlushedEvent} from '../event/UserFlushedEvent'
|
||||
import {Bus} from '../../support/bus'
|
||||
import {HTTPError} from '../../http/HTTPError'
|
||||
|
||||
/**
|
||||
* Base-class for a context that authenticates users and manages security.
|
||||
@@ -95,6 +96,20 @@ export abstract class SecurityContext {
|
||||
return this.authenticatedUser
|
||||
}
|
||||
|
||||
/** Get the current user or throw an authorization error. */
|
||||
user(): Authenticatable {
|
||||
if ( !this.hasUser() ) {
|
||||
throw new HTTPError(HTTPStatus.UNAUTHORIZED)
|
||||
}
|
||||
|
||||
const user = this.getUser()
|
||||
if ( !user ) {
|
||||
throw new HTTPError(HTTPStatus.UNAUTHORIZED)
|
||||
}
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if there is a currently authenticated user.
|
||||
*/
|
||||
|
||||
@@ -30,8 +30,13 @@ export * from './repository/orm/ORMUserRepository'
|
||||
export * from './config'
|
||||
|
||||
export * from './server/types'
|
||||
export * from './server/models/OAuth2TokenModel'
|
||||
export * from './server/repositories/ConfigClientRepository'
|
||||
export * from './server/repositories/ConfigScopeRepository'
|
||||
export * from './server/repositories/ClientRepositoryFactory'
|
||||
export * from './server/repositories/ScopeRepositoryFactory'
|
||||
export * from './server/repositories/ORMTokenRepository'
|
||||
export * from './server/repositories/TokenRepositoryFactory'
|
||||
export * from './server/repositories/CacheRedemptionCodeRepository'
|
||||
export * from './server/repositories/RedemptionCodeRepositoryFactory'
|
||||
export * from './server/OAuth2Server'
|
||||
|
||||
@@ -26,8 +26,8 @@ export class AuthRequiredMiddleware extends Middleware {
|
||||
if ( !this.security.hasUser() ) {
|
||||
this.session.set('@extollo:auth.intention', this.request.url)
|
||||
|
||||
if ( this.routing.hasNamedRoute('@auth.login') ) {
|
||||
return redirect(this.routing.getNamedPath('@auth.login').toRemote)
|
||||
if ( this.routing.hasNamedRoute('@auth:login') ) {
|
||||
return redirect(this.routing.getNamedPath('@auth:login').toRemote)
|
||||
} else {
|
||||
return error(new NotAuthorizedError(), HTTPStatus.FORBIDDEN)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {Inject, Injectable} from '../../di'
|
||||
import {SecurityContext} from '../context/SecurityContext'
|
||||
import {redirect} from '../../http/response/RedirectResponseFactory'
|
||||
import {RequestLocalStorage} from '../../http/RequestLocalStorage'
|
||||
import {Session} from '../../http/session/Session'
|
||||
|
||||
export interface LoginProviderConfig {
|
||||
default: boolean,
|
||||
@@ -61,6 +62,13 @@ export abstract class LoginProvider<TConfig extends LoginProviderConfig> {
|
||||
}
|
||||
|
||||
protected redirectToIntendedRoute(): ResponseObject {
|
||||
return redirect('/') // FIXME
|
||||
const intent = this.request
|
||||
.get()
|
||||
.make<Session>(Session)
|
||||
.safe('@extollo:auth.intention')
|
||||
.or('/')
|
||||
.string()
|
||||
|
||||
return redirect(intent)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,6 +90,7 @@ export class CoreIDLoginProvider extends OAuth2LoginProvider<OAuth2LoginProvider
|
||||
}
|
||||
|
||||
/** Update values on the Authenticatable from user data. */
|
||||
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
||||
protected updateUser(user: any, data: any): void {
|
||||
user.firstName = data.first_name
|
||||
user.lastName = data.last_name
|
||||
|
||||
@@ -3,22 +3,98 @@ import {Injectable} from '../../di'
|
||||
import {ResponseObject, Route} from '../../http/routing/Route'
|
||||
import {Request} from '../../http/lifecycle/Request'
|
||||
import {Session} from '../../http/session/Session'
|
||||
import {OAuth2Client, ClientRepository, OAuth2Scope, ScopeRepository} from './types'
|
||||
import {
|
||||
ClientRepository,
|
||||
OAuth2Client,
|
||||
OAuth2FlowType,
|
||||
OAuth2Scope,
|
||||
RedemptionCodeRepository,
|
||||
ScopeRepository,
|
||||
} from './types'
|
||||
import {HTTPError} from '../../http/HTTPError'
|
||||
import {HTTPStatus, Maybe} from '../../util'
|
||||
import {view} from '../../http/response/ViewResponseFactory'
|
||||
import {SecurityContext} from '../context/SecurityContext'
|
||||
import {redirect} from '../../http/response/RedirectResponseFactory'
|
||||
import {AuthRequiredMiddleware} from '../middleware/AuthRequiredMiddleware'
|
||||
|
||||
@Injectable()
|
||||
export class OAuth2Server extends Controller {
|
||||
public static routes(): void {
|
||||
Route.get('/oauth2/authorize')
|
||||
.alias('@oauth2:authorize')
|
||||
.pre(AuthRequiredMiddleware)
|
||||
.passingRequest()
|
||||
.calls<OAuth2Server>(OAuth2Server, x => x.promptForAuthorization.bind(x))
|
||||
.calls<OAuth2Server>(OAuth2Server, x => x.promptForAuthorization)
|
||||
|
||||
Route.post('/oauth2/authorize')
|
||||
.alias('@oauth2:authorize:submit')
|
||||
.pre(AuthRequiredMiddleware)
|
||||
.passingRequest()
|
||||
.calls<OAuth2Server>(OAuth2Server, x => x.authorizeAndRedirect)
|
||||
|
||||
Route.post('/oauth2/redeem')
|
||||
.alias('@oauth2:authorize:redeem')
|
||||
.passingRequest()
|
||||
.calls<OAuth2Server>(OAuth2Server, x => x.redeemToken)
|
||||
}
|
||||
|
||||
async redeemToken(request: Request): Promise<ResponseObject> {
|
||||
const authParts = String(request.getHeader('Authorization')).split(':')
|
||||
if ( authParts.length !== 2 ) {
|
||||
throw new HTTPError(HTTPStatus.BAD_REQUEST)
|
||||
}
|
||||
|
||||
const clientRepo = <ClientRepository> request.make(ClientRepository)
|
||||
const [clientId, clientSecret] = authParts
|
||||
const client = await clientRepo.find(clientId)
|
||||
if ( !client || client.secret !== clientSecret ) {
|
||||
throw new HTTPError(HTTPStatus.UNAUTHORIZED)
|
||||
}
|
||||
|
||||
const codeRepo = <RedemptionCodeRepository> request.make(RedemptionCodeRepository)
|
||||
const codeString = request.safe('code').string()
|
||||
const code = await codeRepo.find(codeString)
|
||||
if ( !code ) {
|
||||
throw new HTTPError(HTTPStatus.BAD_REQUEST)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
async authorizeAndRedirect(request: Request): Promise<ResponseObject> {
|
||||
// Look up the client in the client repo
|
||||
const session = <Session> request.make(Session)
|
||||
const clientId = session.safe('oauth2.authorize.clientId').string()
|
||||
const client = await this.getClient(request, clientId)
|
||||
|
||||
const flowType = session.safe('oauth2.authorize.flow').in(client.allowedFlows)
|
||||
if ( flowType === OAuth2FlowType.code ) {
|
||||
return this.authorizeCodeFlow(request, client)
|
||||
}
|
||||
}
|
||||
|
||||
protected async authorizeCodeFlow(request: Request, client: OAuth2Client): Promise<ResponseObject> {
|
||||
const session = <Session> request.make(Session)
|
||||
const security = <SecurityContext> request.make(SecurityContext)
|
||||
const codeRepository = <RedemptionCodeRepository> request.make(RedemptionCodeRepository)
|
||||
|
||||
const user = security.user()
|
||||
const scope = session.get('oauth2.authorize.scope')
|
||||
const redirectUri = session.safe('oauth2.authorize.redirectUri').in(client.allowedRedirectUris)
|
||||
|
||||
// FIXME store authorization
|
||||
|
||||
const code = await codeRepository.issue(user, client, scope)
|
||||
const uri = new URL(redirectUri)
|
||||
uri.searchParams.set('code', code.code)
|
||||
return redirect(uri)
|
||||
}
|
||||
|
||||
async promptForAuthorization(request: Request): Promise<ResponseObject> {
|
||||
// Look up the client in the client repo
|
||||
const client = await this.getClient(request)
|
||||
const clientId = request.safe('client_id').string()
|
||||
const client = await this.getClient(request, clientId)
|
||||
|
||||
// Make sure the requested flow type is valid for this client
|
||||
const session = <Session> request.make(Session)
|
||||
@@ -43,12 +119,12 @@ export class OAuth2Server extends Controller {
|
||||
return view('@extollo:oauth2:authorize', {
|
||||
clientName: client.display,
|
||||
scopeDescription: scope?.description,
|
||||
redirectDomain: (new URL(redirectUri)).host,
|
||||
})
|
||||
}
|
||||
|
||||
protected async getClient(request: Request): Promise<OAuth2Client> {
|
||||
protected async getClient(request: Request, clientId: string): Promise<OAuth2Client> {
|
||||
const clientRepo = <ClientRepository> request.make(ClientRepository)
|
||||
const clientId = request.safe('client_id').string()
|
||||
const client = await clientRepo.find(clientId)
|
||||
if ( !client ) {
|
||||
throw new HTTPError(HTTPStatus.BAD_REQUEST, 'Invalid client configuration', {
|
||||
|
||||
30
src/auth/server/models/OAuth2TokenModel.ts
Normal file
30
src/auth/server/models/OAuth2TokenModel.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import {Field, FieldType, Model} from '../../../orm'
|
||||
import {OAuth2Token} from '../types'
|
||||
|
||||
export class OAuth2TokenModel extends Model<OAuth2TokenModel> implements OAuth2Token {
|
||||
public static table = 'oauth2_tokens'
|
||||
|
||||
public static key = 'oauth2_token_id'
|
||||
|
||||
@Field(FieldType.serial, 'oauth2_token_id')
|
||||
protected oauth2TokenId!: number
|
||||
|
||||
public get id(): string {
|
||||
return String(this.oauth2TokenId)
|
||||
}
|
||||
|
||||
@Field(FieldType.varchar, 'user_id')
|
||||
public userId!: string
|
||||
|
||||
@Field(FieldType.varchar, 'client_id')
|
||||
public clientId!: string
|
||||
|
||||
@Field(FieldType.timestamp)
|
||||
public issued!: Date
|
||||
|
||||
@Field(FieldType.timestamp)
|
||||
public expires!: Date
|
||||
|
||||
@Field(FieldType.varchar)
|
||||
public scope?: string
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import {isOAuth2RedemptionCode, OAuth2Client, OAuth2RedemptionCode, RedemptionCodeRepository} from '../types'
|
||||
import {Inject, Injectable} from '../../../di'
|
||||
import {Cache, Maybe, uuid4} from '../../../util'
|
||||
import {Authenticatable} from '../../types'
|
||||
|
||||
@Injectable()
|
||||
export class CacheRedemptionCodeRepository extends RedemptionCodeRepository {
|
||||
@Inject()
|
||||
protected readonly cache!: Cache
|
||||
|
||||
async find(codeString: string): Promise<Maybe<OAuth2RedemptionCode>> {
|
||||
const cacheKey = `@extollo:oauth2:redemption:${codeString}`
|
||||
if ( await this.cache.has(cacheKey) ) {
|
||||
const code = await this.cache.safe(cacheKey).then(x => x.json())
|
||||
if ( isOAuth2RedemptionCode(code) ) {
|
||||
return code
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async issue(user: Authenticatable, client: OAuth2Client, scope?: string): Promise<OAuth2RedemptionCode> {
|
||||
const code = {
|
||||
scope,
|
||||
clientId: client.id,
|
||||
userId: user.getUniqueIdentifier(),
|
||||
code: uuid4(),
|
||||
}
|
||||
|
||||
const cacheKey = `@extollo:oauth2:redemption:${code.code}`
|
||||
await this.cache.put(cacheKey, JSON.stringify(code))
|
||||
return code
|
||||
}
|
||||
}
|
||||
88
src/auth/server/repositories/ORMTokenRepository.ts
Normal file
88
src/auth/server/repositories/ORMTokenRepository.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import {isOAuth2Token, OAuth2Client, OAuth2Token, oauth2TokenString, OAuth2TokenString, TokenRepository} from '../types'
|
||||
import {Inject, Injectable} from '../../../di'
|
||||
import {Maybe} from '../../../util'
|
||||
import {OAuth2TokenModel} from '../models/OAuth2TokenModel'
|
||||
import {Config} from '../../../service/Config'
|
||||
import * as jwt from 'jsonwebtoken'
|
||||
import {Authenticatable} from '../../types'
|
||||
|
||||
@Injectable()
|
||||
export class ORMTokenRepository extends TokenRepository {
|
||||
@Inject()
|
||||
protected readonly config!: Config
|
||||
|
||||
async find(id: string): Promise<Maybe<OAuth2Token>> {
|
||||
const idNum = parseInt(id, 10)
|
||||
if ( !isNaN(idNum) ) {
|
||||
return OAuth2TokenModel.query<OAuth2TokenModel>()
|
||||
.whereKey(idNum)
|
||||
.first()
|
||||
}
|
||||
}
|
||||
|
||||
async issue(user: Authenticatable, client: OAuth2Client, scope?: string): Promise<OAuth2Token> {
|
||||
const expiration = this.config.safe('outh2.token.lifetimeSeconds')
|
||||
.or(60 * 60 * 6)
|
||||
.integer() * 1000
|
||||
|
||||
const token = new OAuth2TokenModel()
|
||||
token.scope = scope
|
||||
token.userId = String(user.getUniqueIdentifier())
|
||||
token.clientId = client.id
|
||||
token.issued = new Date()
|
||||
token.expires = new Date(Math.floor(Date.now() + expiration))
|
||||
await token.save()
|
||||
|
||||
return token
|
||||
}
|
||||
|
||||
async encode(token: OAuth2Token): Promise<OAuth2TokenString> {
|
||||
const secret = this.config.safe('oauth2.secret').string()
|
||||
const payload = {
|
||||
id: token.id,
|
||||
userId: token.userId,
|
||||
clientId: token.clientId,
|
||||
iat: Math.floor(token.issued.valueOf() / 1000),
|
||||
exp: Math.floor(token.expires.valueOf() / 1000),
|
||||
...(token.scope ? { scope: token.scope } : {}),
|
||||
}
|
||||
|
||||
const generated = await new Promise<string>((res, rej) => {
|
||||
jwt.sign(payload, secret, {}, (err, gen) => {
|
||||
if (err || err === null || !gen) {
|
||||
rej(err || new Error('Unable to encode JWT.'))
|
||||
} else {
|
||||
res(gen)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
return oauth2TokenString(generated)
|
||||
}
|
||||
|
||||
async decode(token: OAuth2TokenString): Promise<Maybe<OAuth2Token>> {
|
||||
const secret = this.config.safe('oauth2.secret').string()
|
||||
const decoded = await new Promise<any>((res, rej) => {
|
||||
jwt.verify(token, secret, {}, (err, payload) => {
|
||||
if ( err ) {
|
||||
rej(err)
|
||||
} else {
|
||||
res(payload)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
const value = {
|
||||
id: decoded.id,
|
||||
userId: decoded.userId,
|
||||
clientId: decoded.clientId,
|
||||
issued: new Date(decoded.iat * 1000),
|
||||
expires: new Date(decoded.exp * 1000),
|
||||
...(decoded.scope ? { scope: decoded.scope } : {}),
|
||||
}
|
||||
|
||||
if ( isOAuth2Token(value) ) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import {
|
||||
AbstractFactory,
|
||||
Container,
|
||||
DependencyRequirement,
|
||||
PropertyDependency,
|
||||
isInstantiable,
|
||||
DEPENDENCY_KEYS_METADATA_KEY,
|
||||
DEPENDENCY_KEYS_PROPERTY_METADATA_KEY, Instantiable, FactoryProducer,
|
||||
} from '../../../di'
|
||||
import {Collection, ErrorWithContext} from '../../../util'
|
||||
import {Config} from '../../../service/Config'
|
||||
import {RedemptionCodeRepository} from '../types'
|
||||
import {CacheRedemptionCodeRepository} from './CacheRedemptionCodeRepository'
|
||||
|
||||
/**
|
||||
* A dependency injection factory that matches the abstract RedemptionCodeRepository class
|
||||
* and produces an instance of the configured repository driver implementation.
|
||||
*/
|
||||
@FactoryProducer()
|
||||
export class RedemptionCodeRepositoryFactory extends AbstractFactory<RedemptionCodeRepository> {
|
||||
protected get config(): Config {
|
||||
return Container.getContainer().make<Config>(Config)
|
||||
}
|
||||
|
||||
produce(): RedemptionCodeRepository {
|
||||
return new (this.getRedemptionCodeRepositoryClass())()
|
||||
}
|
||||
|
||||
match(something: unknown): boolean {
|
||||
return something === RedemptionCodeRepository
|
||||
}
|
||||
|
||||
getDependencyKeys(): Collection<DependencyRequirement> {
|
||||
const meta = Reflect.getMetadata(DEPENDENCY_KEYS_METADATA_KEY, this.getRedemptionCodeRepositoryClass())
|
||||
if ( meta ) {
|
||||
return meta
|
||||
}
|
||||
return new Collection<DependencyRequirement>()
|
||||
}
|
||||
|
||||
getInjectedProperties(): Collection<PropertyDependency> {
|
||||
const meta = new Collection<PropertyDependency>()
|
||||
let currentToken = this.getRedemptionCodeRepositoryClass()
|
||||
|
||||
do {
|
||||
const loadedMeta = Reflect.getMetadata(DEPENDENCY_KEYS_PROPERTY_METADATA_KEY, currentToken)
|
||||
if ( loadedMeta ) {
|
||||
meta.concat(loadedMeta)
|
||||
}
|
||||
currentToken = Object.getPrototypeOf(currentToken)
|
||||
} while (Object.getPrototypeOf(currentToken) !== Function.prototype && Object.getPrototypeOf(currentToken) !== Object.prototype)
|
||||
|
||||
return meta
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the instantiable class of the configured client repository backend.
|
||||
* @protected
|
||||
* @return Instantiable<RedemptionCodeRepository>
|
||||
*/
|
||||
protected getRedemptionCodeRepositoryClass(): Instantiable<RedemptionCodeRepository> {
|
||||
const RedemptionCodeRepositoryClass = this.config.get('oauth2.repository.client', CacheRedemptionCodeRepository)
|
||||
|
||||
if ( !isInstantiable(RedemptionCodeRepositoryClass) || !(RedemptionCodeRepositoryClass.prototype instanceof RedemptionCodeRepository) ) {
|
||||
const e = new ErrorWithContext('Provided client repository class does not extend from @extollo/lib.RedemptionCodeRepository')
|
||||
e.context = {
|
||||
configKey: 'oauth2.repository.client',
|
||||
class: RedemptionCodeRepositoryClass.toString(),
|
||||
}
|
||||
}
|
||||
|
||||
return RedemptionCodeRepositoryClass
|
||||
}
|
||||
}
|
||||
74
src/auth/server/repositories/TokenRepositoryFactory.ts
Normal file
74
src/auth/server/repositories/TokenRepositoryFactory.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import {
|
||||
AbstractFactory,
|
||||
Container,
|
||||
DependencyRequirement,
|
||||
PropertyDependency,
|
||||
isInstantiable,
|
||||
DEPENDENCY_KEYS_METADATA_KEY,
|
||||
DEPENDENCY_KEYS_PROPERTY_METADATA_KEY, Instantiable, FactoryProducer,
|
||||
} from '../../../di'
|
||||
import {Collection, ErrorWithContext} from '../../../util'
|
||||
import {Config} from '../../../service/Config'
|
||||
import {TokenRepository} from '../types'
|
||||
import {ORMTokenRepository} from './ORMTokenRepository'
|
||||
|
||||
/**
|
||||
* A dependency injection factory that matches the abstract TokenRepository class
|
||||
* and produces an instance of the configured repository driver implementation.
|
||||
*/
|
||||
@FactoryProducer()
|
||||
export class TokenRepositoryFactory extends AbstractFactory<TokenRepository> {
|
||||
protected get config(): Config {
|
||||
return Container.getContainer().make<Config>(Config)
|
||||
}
|
||||
|
||||
produce(): TokenRepository {
|
||||
return new (this.getTokenRepositoryClass())()
|
||||
}
|
||||
|
||||
match(something: unknown): boolean {
|
||||
return something === TokenRepository
|
||||
}
|
||||
|
||||
getDependencyKeys(): Collection<DependencyRequirement> {
|
||||
const meta = Reflect.getMetadata(DEPENDENCY_KEYS_METADATA_KEY, this.getTokenRepositoryClass())
|
||||
if ( meta ) {
|
||||
return meta
|
||||
}
|
||||
return new Collection<DependencyRequirement>()
|
||||
}
|
||||
|
||||
getInjectedProperties(): Collection<PropertyDependency> {
|
||||
const meta = new Collection<PropertyDependency>()
|
||||
let currentToken = this.getTokenRepositoryClass()
|
||||
|
||||
do {
|
||||
const loadedMeta = Reflect.getMetadata(DEPENDENCY_KEYS_PROPERTY_METADATA_KEY, currentToken)
|
||||
if ( loadedMeta ) {
|
||||
meta.concat(loadedMeta)
|
||||
}
|
||||
currentToken = Object.getPrototypeOf(currentToken)
|
||||
} while (Object.getPrototypeOf(currentToken) !== Function.prototype && Object.getPrototypeOf(currentToken) !== Object.prototype)
|
||||
|
||||
return meta
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the instantiable class of the configured token repository backend.
|
||||
* @protected
|
||||
* @return Instantiable<TokenRepository>
|
||||
*/
|
||||
protected getTokenRepositoryClass(): Instantiable<TokenRepository> {
|
||||
const TokenRepositoryClass = this.config.get('oauth2.repository.token', ORMTokenRepository)
|
||||
|
||||
if ( !isInstantiable(TokenRepositoryClass) || !(TokenRepositoryClass.prototype instanceof TokenRepository) ) {
|
||||
const e = new ErrorWithContext('Provided token repository class does not extend from @extollo/lib.TokenRepository')
|
||||
e.context = {
|
||||
configKey: 'oauth2.repository.client',
|
||||
class: TokenRepositoryClass.toString(),
|
||||
}
|
||||
}
|
||||
|
||||
return TokenRepositoryClass
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import {Awaitable, hasOwnProperty, Maybe} from '../../util'
|
||||
import {Awaitable, hasOwnProperty, Maybe, TypeTag} from '../../util'
|
||||
import {Authenticatable, AuthenticatableIdentifier} from '../types'
|
||||
|
||||
export enum OAuth2FlowType {
|
||||
code = 'code',
|
||||
@@ -81,3 +82,93 @@ export abstract class ScopeRepository {
|
||||
|
||||
abstract findByName(name: string): Awaitable<Maybe<OAuth2Scope>>
|
||||
}
|
||||
|
||||
export interface OAuth2Token {
|
||||
id: string
|
||||
userId: AuthenticatableIdentifier
|
||||
clientId: string
|
||||
issued: Date
|
||||
expires: Date
|
||||
scope?: string
|
||||
}
|
||||
|
||||
export type OAuth2TokenString = TypeTag<'@extollo/lib.OAuth2TokenString'> & string
|
||||
|
||||
export function oauth2TokenString(s: string): OAuth2TokenString {
|
||||
return s as OAuth2TokenString
|
||||
}
|
||||
|
||||
export function isOAuth2Token(what: unknown): what is OAuth2Token {
|
||||
if ( typeof what !== 'object' || what === null ) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (
|
||||
!hasOwnProperty(what, 'id')
|
||||
|| !hasOwnProperty(what, 'userId')
|
||||
|| !hasOwnProperty(what, 'clientId')
|
||||
|| !hasOwnProperty(what, 'issued')
|
||||
|| !hasOwnProperty(what, 'expires')
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (
|
||||
typeof what.id !== 'string'
|
||||
|| !(typeof what.userId === 'string' || typeof what.userId === 'number')
|
||||
|| typeof what.clientId !== 'string'
|
||||
|| !(what.issued instanceof Date)
|
||||
|| !(what.expires instanceof Date)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
return !hasOwnProperty(what, 'scope') || typeof what.scope === 'string'
|
||||
}
|
||||
|
||||
export abstract class TokenRepository {
|
||||
abstract find(id: string): Awaitable<Maybe<OAuth2Token>>
|
||||
|
||||
abstract issue(user: Authenticatable, client: OAuth2Client, scope?: string): Awaitable<OAuth2Token>
|
||||
|
||||
abstract decode(token: OAuth2TokenString): Awaitable<Maybe<OAuth2Token>>
|
||||
|
||||
abstract encode(token: OAuth2Token): Awaitable<OAuth2TokenString>
|
||||
}
|
||||
|
||||
export interface OAuth2RedemptionCode {
|
||||
clientId: string
|
||||
userId: AuthenticatableIdentifier
|
||||
code: string
|
||||
scope?: string
|
||||
}
|
||||
|
||||
export function isOAuth2RedemptionCode(what: unknown): what is OAuth2RedemptionCode {
|
||||
if ( typeof what !== 'object' || what === null ) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (
|
||||
!hasOwnProperty(what, 'clientId')
|
||||
|| !hasOwnProperty(what, 'userId')
|
||||
|| !hasOwnProperty(what, 'code')
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (
|
||||
typeof what.clientId !== 'string'
|
||||
|| !(typeof what.userId === 'number' || typeof what.userId === 'string')
|
||||
|| typeof what.code !== 'string'
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
return !hasOwnProperty(what, 'scope') || typeof what.scope === 'string'
|
||||
}
|
||||
|
||||
export abstract class RedemptionCodeRepository {
|
||||
abstract find(code: string): Awaitable<Maybe<OAuth2RedemptionCode>>
|
||||
|
||||
abstract issue(user: Authenticatable, client: OAuth2Client, scope?: string): Awaitable<OAuth2RedemptionCode>
|
||||
}
|
||||
|
||||
@@ -451,14 +451,19 @@ export class Container {
|
||||
|
||||
this.checkForMakeCycles()
|
||||
|
||||
if ( this.hasKey(target) ) {
|
||||
const realized = this.resolveAndCreate(target, ...parameters)
|
||||
try {
|
||||
if (this.hasKey(target)) {
|
||||
const realized = this.resolveAndCreate(target, ...parameters)
|
||||
Container.makeStack.pop()
|
||||
return realized
|
||||
} else if (typeof target !== 'string' && isInstantiable(target)) {
|
||||
const realized = this.produceFactory(new Factory(target), parameters)
|
||||
Container.makeStack.pop()
|
||||
return realized
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
Container.makeStack.pop()
|
||||
return realized
|
||||
} else if ( typeof target !== 'string' && isInstantiable(target) ) {
|
||||
const realized = this.produceFactory(new Factory(target), parameters)
|
||||
Container.makeStack.pop()
|
||||
return realized
|
||||
throw e
|
||||
}
|
||||
|
||||
Container.makeStack.pop()
|
||||
|
||||
@@ -2,7 +2,7 @@ import {HTTPKernel} from '../HTTPKernel'
|
||||
import {Request} from '../../lifecycle/Request'
|
||||
import {ActivatedRoute} from '../../routing/ActivatedRoute'
|
||||
import {http} from '../../response/HTTPErrorResponseFactory'
|
||||
import {HTTPStatus} from '../../../util'
|
||||
import {HTTPStatus, withErrorContext} from '../../../util'
|
||||
import {AbstractResolvedRouteHandlerHTTPModule} from './AbstractResolvedRouteHandlerHTTPModule'
|
||||
|
||||
/**
|
||||
@@ -23,11 +23,15 @@ export class ExecuteResolvedRouteHandlerHTTPModule extends AbstractResolvedRoute
|
||||
throw new Error('Attempted to call route handler without resolved parameters.')
|
||||
}
|
||||
|
||||
const result = await route.handler
|
||||
.tap(handler => handler(...params))
|
||||
.apply(request)
|
||||
await withErrorContext(async () => {
|
||||
const result = await route.handler
|
||||
.tap(handler => handler(...params))
|
||||
.apply(request)
|
||||
|
||||
await this.applyResponseObject(result, request)
|
||||
await this.applyResponseObject(result, request)
|
||||
}, {
|
||||
route,
|
||||
})
|
||||
} else {
|
||||
await http(HTTPStatus.NOT_FOUND).write(request)
|
||||
request.response.blockingWriteback(true)
|
||||
|
||||
@@ -4,7 +4,7 @@ import {Request} from '../../lifecycle/Request'
|
||||
import {ActivatedRoute} from '../../routing/ActivatedRoute'
|
||||
import {ResponseObject} from '../../routing/Route'
|
||||
import {AbstractResolvedRouteHandlerHTTPModule} from './AbstractResolvedRouteHandlerHTTPModule'
|
||||
import {collect, isLeft, unleft, unright} from '../../../util'
|
||||
import {collect, isLeft, unleft, unright, withErrorContext} from '../../../util'
|
||||
|
||||
/**
|
||||
* HTTP Kernel module that executes the preflight handlers for the route.
|
||||
@@ -22,11 +22,13 @@ export class ExecuteResolvedRoutePreflightHTTPModule extends AbstractResolvedRou
|
||||
const preflight = route.preflight
|
||||
|
||||
for ( const handler of preflight ) {
|
||||
const result: ResponseObject = await handler(request)
|
||||
if ( typeof result !== 'undefined' ) {
|
||||
await this.applyResponseObject(result, request)
|
||||
request.response.blockingWriteback(true)
|
||||
}
|
||||
await withErrorContext(async () => {
|
||||
const result: ResponseObject = await handler(request)
|
||||
if ( typeof result !== 'undefined' ) {
|
||||
await this.applyResponseObject(result, request)
|
||||
request.response.blockingWriteback(true)
|
||||
}
|
||||
}, { handler })
|
||||
}
|
||||
|
||||
const parameters = route.parameters
|
||||
|
||||
@@ -195,6 +195,10 @@ export class Response {
|
||||
*/
|
||||
public async write(data: string | Buffer | Uint8Array | Readable): Promise<void> {
|
||||
return new Promise<void>((res, rej) => {
|
||||
if ( this.responseEnded ) {
|
||||
throw new ErrorWithContext('Tried to write to Response after lifecycle ended.')
|
||||
}
|
||||
|
||||
if ( !this.sentHeaders ) {
|
||||
this.sendHeaders()
|
||||
}
|
||||
|
||||
@@ -72,9 +72,12 @@ export class ErrorResponseFactory extends ResponseFactory {
|
||||
}
|
||||
}
|
||||
|
||||
const suggestion = this.getSuggestion()
|
||||
|
||||
let str = `
|
||||
<b>Sorry, an unexpected error occurred while processing your request.</b>
|
||||
<br>
|
||||
${suggestion ? '<br><b>Suggestion:</b> ' + suggestion + '<br>' : ''}
|
||||
<pre><code>
|
||||
Name: ${thrownError.name}
|
||||
Message: ${thrownError.message}
|
||||
@@ -88,7 +91,7 @@ Stack trace:
|
||||
str += `
|
||||
<pre><code>
|
||||
Context:
|
||||
${Object.keys(context).map(key => ` - ${key} : ${context[key]}`)
|
||||
${Object.keys(context).map(key => ` - ${key} : ${JSON.stringify(context[key]).replace(/\n/g, '<br>')}`)
|
||||
.join('\n')}
|
||||
</code></pre>
|
||||
`
|
||||
@@ -100,4 +103,12 @@ ${Object.keys(context).map(key => ` - ${key} : ${context[key]}`)
|
||||
protected buildJSON(thrownError: Error): string {
|
||||
return JSON.stringify(api.error(thrownError))
|
||||
}
|
||||
|
||||
protected getSuggestion(): string {
|
||||
if ( this.thrownError.message.startsWith('No such dependency is registered with this container: class SecurityContext') ) {
|
||||
return 'It looks like this route relies on the security framework. Is the route you are accessing inside a middleware (e.g. SessionAuthMiddleware)?'
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@ import {Request} from '../lifecycle/Request'
|
||||
* Helper function to create a new RedirectResponseFactory to the given destination.
|
||||
* @param destination
|
||||
*/
|
||||
export function redirect(destination: string): RedirectResponseFactory {
|
||||
return new RedirectResponseFactory(destination)
|
||||
export function redirect(destination: string|URL): RedirectResponseFactory {
|
||||
return new RedirectResponseFactory(destination instanceof URL ? destination.toString() : destination)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -72,12 +72,16 @@ export class Route<TReturn extends ResponseObject, THandlerParams extends unknow
|
||||
for ( const group of stack ) {
|
||||
route.prepend(group.prefix)
|
||||
group.getPreflight()
|
||||
.each(def => route.preflight.prepend(def))
|
||||
.each(def => route.preflight.prepend(
|
||||
request => request.make<Middleware>(def, request).apply(),
|
||||
))
|
||||
}
|
||||
|
||||
for ( const group of this.compiledGroupStack ) {
|
||||
group.getPostflight()
|
||||
.each(def => route.postflight.push(def))
|
||||
.each(def => route.postflight.push(
|
||||
request => request.make<Middleware>(def, request).apply(),
|
||||
))
|
||||
}
|
||||
|
||||
// Add the global pre- and post- middleware
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import {Collection, ErrorWithContext} from '../../util'
|
||||
import {AppClass} from '../../lifecycle/AppClass'
|
||||
import {ResolvedRouteHandler} from './Route'
|
||||
import {Container} from '../../di'
|
||||
import {Container, Instantiable} from '../../di'
|
||||
import {Logging} from '../../service/Logging'
|
||||
import {Middleware} from './Middleware'
|
||||
|
||||
/**
|
||||
* Class that defines a group of Routes in the application, with a prefix.
|
||||
*/
|
||||
export class RouteGroup extends AppClass {
|
||||
protected preflight: Collection<ResolvedRouteHandler> = new Collection<ResolvedRouteHandler>()
|
||||
protected preflight: Collection<Instantiable<Middleware>> = new Collection()
|
||||
|
||||
protected postflight: Collection<ResolvedRouteHandler> = new Collection<ResolvedRouteHandler>()
|
||||
protected postflight: Collection<Instantiable<Middleware>> = new Collection()
|
||||
|
||||
/**
|
||||
* The current set of nested groups. This is used when compiling route groups.
|
||||
@@ -87,22 +87,22 @@ export class RouteGroup extends AppClass {
|
||||
}
|
||||
|
||||
/** Register the given middleware to be applied before all routes in this group. */
|
||||
pre(middleware: ResolvedRouteHandler): this {
|
||||
pre(middleware: Instantiable<Middleware>): this {
|
||||
this.preflight.push(middleware)
|
||||
return this
|
||||
}
|
||||
|
||||
/** Register the given middleware to be applied after all routes in this group. */
|
||||
post(middleware: ResolvedRouteHandler): this {
|
||||
post(middleware: Instantiable<Middleware>): this {
|
||||
this.postflight.push(middleware)
|
||||
return this
|
||||
}
|
||||
|
||||
getPreflight(): Collection<ResolvedRouteHandler> {
|
||||
getPreflight(): Collection<Instantiable<Middleware>> {
|
||||
return this.preflight
|
||||
}
|
||||
|
||||
getPostflight(): Collection<ResolvedRouteHandler> {
|
||||
getPostflight(): Collection<Instantiable<Middleware>> {
|
||||
return this.postflight
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {Injectable, Inject} from '../../di'
|
||||
import {ErrorWithContext} from '../../util'
|
||||
import {ErrorWithContext, Safe} from '../../util'
|
||||
import {Request} from '../lifecycle/Request'
|
||||
|
||||
/**
|
||||
@@ -60,4 +60,9 @@ export abstract class Session {
|
||||
|
||||
/** Remove a key from the session data. */
|
||||
public abstract forget(key: string): void
|
||||
|
||||
/** Load a key from the session as a Safe value. */
|
||||
public safe(key: string): Safe {
|
||||
return new Safe(this.get(key))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
ErrorWithContext,
|
||||
globalRegistry,
|
||||
infer,
|
||||
isLoggingLevel,
|
||||
isLoggingLevel, logIfDebugging,
|
||||
PathLike,
|
||||
StandardLogger,
|
||||
universalPath,
|
||||
@@ -237,9 +237,11 @@ export class Application extends Container {
|
||||
* @protected
|
||||
*/
|
||||
protected bootstrapEnvironment(): void {
|
||||
logIfDebugging('extollo.env', `.env path: ${this.basePath.concat('.env').toLocal}`)
|
||||
dotenv.config({
|
||||
path: this.basePath.concat('.env').toLocal,
|
||||
})
|
||||
logIfDebugging('extollo.env', process.env)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1022,7 +1022,7 @@ export abstract class Model<T extends Model<T>> extends LocalBus<ModelEvent<T>>
|
||||
* @param scope
|
||||
* @protected
|
||||
*/
|
||||
protected scope(scope: Instantiable<Scope> | ScopeClosure): this {
|
||||
protected withScope(scope: Instantiable<Scope> | ScopeClosure): this {
|
||||
if ( isInstantiable(scope) ) {
|
||||
if ( !this.hasScope(scope) ) {
|
||||
this.scopes.push({
|
||||
|
||||
@@ -9,7 +9,12 @@ block content
|
||||
else
|
||||
p This will allow #{clientName} full access to your account.
|
||||
|
||||
//p After allowing this, you may not be prompted again.
|
||||
div(style='display: flex; flex-direction: row; padding-top: 20px')
|
||||
form(method='get' action=(hasRoute('home') ? named('home') : route('/')))
|
||||
button.button(type='submit') Deny
|
||||
|
||||
if buttonText && buttonUrl
|
||||
a.button(href=buttonUrl) #{buttonText}
|
||||
form(method='post' style='padding-left: 20px')
|
||||
button.button(type='submit') Allow
|
||||
|
||||
p
|
||||
small(style='color: var(--color-accent-text)') After allowing, will redirect to: #{redirectDomain}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Base type for a canonical definition.
|
||||
*/
|
||||
import {Canon} from './Canon'
|
||||
import {universalPath, UniversalPath, ErrorWithContext} from '../util'
|
||||
import {universalPath, UniversalPath, ErrorWithContext, Safe} from '../util'
|
||||
import {Logging} from './Logging'
|
||||
import {Inject} from '../di'
|
||||
import * as nodePath from 'path'
|
||||
@@ -192,6 +192,18 @@ export abstract class Canonical<T> extends Unit {
|
||||
return this.loadedItems[key]
|
||||
}
|
||||
|
||||
/** Get a canonical item by key as a Safe value. */
|
||||
public safe(key: string): Safe {
|
||||
return (new Safe(this.get(key))).onError((message, value) => {
|
||||
throw new ErrorWithContext(`Invalid canonical value: ${message}`, {
|
||||
canonicalKey: key,
|
||||
canonicalItems: this.canonicalItems,
|
||||
value,
|
||||
message,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a namespace resolver with the canonical unit.
|
||||
*
|
||||
|
||||
9
src/util/cache/Cache.ts
vendored
9
src/util/cache/Cache.ts
vendored
@@ -1,4 +1,5 @@
|
||||
import {Awaitable} from '../support/types'
|
||||
import {Safe} from '../support/Safe'
|
||||
|
||||
/**
|
||||
* Abstract interface class for a cached object.
|
||||
@@ -11,6 +12,14 @@ export abstract class Cache {
|
||||
*/
|
||||
public abstract fetch(key: string): Awaitable<string|undefined>;
|
||||
|
||||
/**
|
||||
* Fetch a value from the cache by its key as a Safe value.
|
||||
* @param key
|
||||
*/
|
||||
public async safe(key: string): Promise<Safe> {
|
||||
return new Safe(await this.fetch(key))
|
||||
}
|
||||
|
||||
/**
|
||||
* Store the given value in the cache by key.
|
||||
* @param {string} key
|
||||
|
||||
@@ -27,3 +27,25 @@ export class ErrorWithContext extends Error {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function withErrorContext<T>(closure: () => T, context: {[key: string]: any}): T {
|
||||
try {
|
||||
return closure()
|
||||
} catch (e: unknown) {
|
||||
if ( e instanceof ErrorWithContext ) {
|
||||
e.context = {
|
||||
...e.context,
|
||||
...context,
|
||||
}
|
||||
throw e
|
||||
} else if ( e instanceof Error ) {
|
||||
const ewc = new ErrorWithContext(e.message, context)
|
||||
ewc.stack = e.stack
|
||||
ewc.name = e.name
|
||||
ewc.originalError = e
|
||||
throw ewc
|
||||
} else {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import {Integer, isInteger} from './types'
|
||||
import {ErrorWithContext} from '../error/ErrorWithContext'
|
||||
import {JSONState} from './Rehydratable'
|
||||
import {isJSON} from './data'
|
||||
|
||||
export class Safe {
|
||||
protected thrower: (message: string, value: unknown) => never
|
||||
@@ -22,10 +24,10 @@ export class Safe {
|
||||
|
||||
present(): this {
|
||||
if ( !this.value && this.value !== 0 && this.value !== false ) {
|
||||
return this
|
||||
this.thrower('Missing value', this.value)
|
||||
}
|
||||
|
||||
this.thrower('Missing value', this.value)
|
||||
return this
|
||||
}
|
||||
|
||||
integer(): Integer {
|
||||
@@ -51,6 +53,23 @@ export class Safe {
|
||||
return String(this.value)
|
||||
}
|
||||
|
||||
json(): JSONState {
|
||||
const str = this.string()
|
||||
if ( !isJSON(str) ) {
|
||||
this.thrower('Invalid JSON', str)
|
||||
}
|
||||
|
||||
return JSON.parse(str)
|
||||
}
|
||||
|
||||
or(other: unknown): Safe {
|
||||
if ( !this.value && this.value !== 0 && this.value !== false ) {
|
||||
return new Safe(other)
|
||||
}
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
in<T>(allowed: T[]): T {
|
||||
if ( allowed.includes(this.value as any) ) {
|
||||
return this.value as T
|
||||
|
||||
Reference in New Issue
Block a user