feat: first version
Some checks failed
Build, check & Test / run (push) Failing after 39s

Signed-off-by: Florian BOUILLON <f.bouillon@aptatio.com>
This commit is contained in:
2023-07-20 17:41:16 +02:00
parent 2bd59f902f
commit 09ed4c487d
80 changed files with 1171 additions and 2755 deletions

5
src/libs/AstroUtils.ts Normal file
View File

@ -0,0 +1,5 @@
export default class AstroUtils {
public static async wrap<T = void>(fn: () => T | Promise<T>) {
return await fn()
}
}

View File

@ -1,9 +0,0 @@
import bcryptjs from 'bcryptjs'
export function hashPassword(password: string): Promise<string> {
return bcryptjs.hash(password, 10)
}
export function comparePassword(password: string, hash: string): Promise<boolean> {
return bcryptjs.compare(password, hash)
}

View File

@ -1,57 +0,0 @@
export default class CookieManager {
private cookies: Record<string, string> = {}
public constructor(data?: string | Record<string, string>) {
if (typeof data === 'string') {
data.split(';').forEach((keyValuePair) => {
const [key, value] = keyValuePair.split('=')
if (!key || !value) {
return
}
this.cookies[key.trim()] = value.trim().replace(/%3B/g, ';')
})
} else if (typeof data === 'object') {
this.cookies = data
}
}
public static addCookie(res: ResponseInit & { readonly headers: Headers; }, cookie: {
key: string
value: string
expire?: string
maxAge?: number
domain?: string
path?: string
secure?: boolean
httpOnly?: boolean
sameSite?: 'Lax' | 'None' | 'Strict'}
) {
const items: Array<string> = [`${cookie.key}=${cookie.value.replace(/;/g, '%3B')}`]
if (cookie.expire) {
items.push(`Expires=${cookie.expire}`)
}
if (cookie.maxAge) {
items.push(`Max-Age=${cookie.maxAge}`)
}
if (cookie.domain) {
items.push(`Domain=${cookie.domain}`)
}
if (cookie.path) {
items.push(`Path=${cookie.path}`)
}
if (cookie.secure) {
items.push('Secure')
}
if (cookie.httpOnly) {
items.push('HttpOnly')
}
if (cookie.sameSite) {
items.push(`SameSite=${cookie.sameSite}`)
}
res.headers.append('Set-Cookie', items.join('; '))
}
public get(key: string): string | undefined {
return this.cookies[key]
}
}

View File

@ -1,20 +0,0 @@
import { promises as fs } from 'node:fs'
/**
* File manipulation utility class
*/
export default class FilesUtils {
/**
* heck if a file/folder exists at the specified location
* @param path the path to check
* @returns if the file exists or not
*/
public static async exists(path: string): Promise<boolean> {
try {
await fs.stat(path)
return true
} catch {
return false
}
}
}

View File

@ -1,70 +1,288 @@
/**
* HTTP Status code
*
* Following https://developer.mozilla.org/en-US/docs/Web/HTTP/Status an extension of the RFC9110
*/
enum StatusCode {
/****************
* 1xx Requests *
****************/
/**
* This interim response indicates that the client should continue the request or ignore the response if the request is already finished.
*/
CONTINUE = 100,
/**
* This code is sent in response to an Upgrade request header from the client and indicates the protocol the server is switching to.
*/
SWITCHING_PROTOCOLS,
/**
* This code indicates that the server has received and is processing the request, but no response is available yet.
*/
PROCESSING,
/**
* This status code is primarily intended to be used with the Link header, letting the user agent start preloading resources while the server prepares a response.
*/
EARLY_HINTS,
/****************
* 2xx Requests *
****************/
/**
* The request succeeded. The result meaning of "success" depends on the HTTP method:
* - `GET`: The resource has been fetched and transmitted in the message body.
* - `HEAD`: The representation headers are included in the response without any message body.
* - `PUT` or `POST`: The resource describing the result of the action is transmitted in the message body.
* - `TRACE`: The message body contains the request message as received by the server.
*/
OK = 200,
/**
* The request succeeded, and a new resource was created as a result. This is typically the response sent after `POST` requests, or some `PUT` requests.
*/
CREATED,
/**
* The request has been received but not yet acted upon. It is noncommittal, since there is no way in HTTP to later send an asynchronous response indicating the outcome of the request. It is intended for cases where another process or server handles the request, or for batch processing.
*/
ACCEPTED,
/**
* This response code means the returned metadata is not exactly the same as is available from the origin server, but is collected from a local or a third-party copy. This is mostly used for mirrors or backups of another resource. Except for that specific case, the `200 OK` response is preferred to this status.
*/
NON_AUTHORITATIVE_INFORMATION,
/**
* There is no content to send for this request, but the headers may be useful. The user agent may update its cached headers for this resource with the new ones.
*/
NO_CONTENT,
/**
* Tells the user agent to reset the document which sent this request.
*/
RESET_CONTENT,
/**
* This response code is used when the Range header is sent from the client to request only part of a resource.
*/
PARTIAL_CONTENT,
/**
* Conveys information about multiple resources, for situations where multiple status codes might be appropriate.
*/
MULTI_STATUS,
/**
* Used inside a `<dav:propstat>` response element to avoid repeatedly enumerating the internal members of multiple bindings to the same collection.
*/
ALREADY_REPORTED,
/**
* The server has fulfilled a `GET` request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
*/
IM_USED = 226,
/****************
* 3xx Requests *
****************/
/**
* The request has more than one possible response. The user agent or user should choose one of them. (There is no standardized way of choosing one of the responses, but HTML links to the possibilities are recommended so the user can pick.)
*/
MULTIPLE_CHOICES = 300,
/**
* The URL of the requested resource has been changed permanently. The new URL is given in the response.
*/
MOVED_PERMANENTLY,
/**
* This response code means that the URI of requested resource has been changed temporarily. Further changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.
*/
FOUND,
/**
* The server sent this response to direct the client to get the requested resource at another URI with a GET request.
*/
SEE_OTHER,
/**
* This is used for caching purposes. It tells the client that the response has not been modified, so the client can continue to use the same cached version of the response.
*/
NOT_MODIFIED,
/**
* Defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy.
*/
USE_PROXY,
/**
* This response code is no longer used; it is just reserved. It was used in a previous version of the HTTP/1.1 specification.
*/
// UNUSED
/**
* The server sends this response to direct the client to get the requested resource at another URI with the same method that was used in the prior request. This has the same semantics as the `302 Found` HTTP response code, with the exception that the user agent must not change the HTTP method used: if a `POST` was used in the first request, a `POST` must be used in the second request.
*/
TEMPORARY_REDIRECT = 307,
/**
* This means that the resource is now permanently located at another URI, specified by the `Location:` HTTP Response header. This has the same semantics as the `301 Moved Permanently` HTTP response code, with the exception that the user agent must not change the HTTP method used: if a `POST` was used in the first request, a `POST` must be used in the second request.
*/
PERMANENT_REDIRECT,
/****************
* 4xx Requests *
****************/
/**
* The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
*/
BAD_REQUEST = 400,
/**
* Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response.
*/
UNAUTHORIZED,
/**
* This response code is reserved for future use. The initial aim for creating this code was using it for digital payment systems, however this status code is used very rarely and no standard convention exists.
*/
PAYMENT_REQUIRED,
/**
* The client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource. Unlike `401 Unauthorized`, the client's identity is known to the server.
*/
FORBIDDEN,
/**
* The server cannot find the requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of `403 Forbidden` to hide the existence of a resource from an unauthorized client. This response code is probably the most well known due to its frequent occurrence on the web.
*/
NOT_FOUND,
/**
* The request method is known by the server but is not supported by the target resource. For example, an API may not allow calling `DELETE` to remove a resource.
*/
METHOD_NOT_ALLOWED,
/**
* This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content that conforms to the criteria given by the user agent.
*/
NOT_ACCEPTABLE,
/**
* This is similar to `401 Unauthorized` but authentication is needed to be done by a proxy.
*/
PROXY_AUTHENTIFICATION_REQUIRED,
/**
* This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message.
*/
REQUEST_TIMEOUT,
/**
* This response is sent when a request conflicts with the current state of the server.
*/
CONFLICT,
/**
* This response is sent when the requested content has been permanently deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional services". APIs should not feel compelled to indicate resources that have been deleted with this status code.
*/
GONE,
/**
* Server rejected the request because the `Content-Length` header field is not defined and the server requires it.
*/
LENGTH_REQUIRED,
/**
* The client has indicated preconditions in its headers which the server does not meet.
*/
PRECONDITION_FAILED,
/**
* Request entity is larger than limits defined by server. The server might close the connection or return an `Retry-After` header field.
*/
PAYLOAD_TOO_LARGE,
/**
* The URI requested by the client is longer than the server is willing to interpret.
*/
URI_TOO_LONG,
/**
* The media format of the requested data is not supported by the server, so the server is rejecting the request.
*/
UNSUPPORTED_MEDIA_TYPE,
/**
* The range specified by the `Range` header field in the request cannot be fulfilled. It's possible that the range is outside the size of the target URI's data.
*/
RANGE_NOT_SATISFIABLE,
/**
* This response code means the expectation indicated by the `Expect` request header field cannot be met by the server.
*/
EXPECTATION_FAILED,
/**
* The server refuses the attempt to brew coffee with a teapot.
*/
IM_A_TEAPOT,
/**
* The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.
*/
MIDIRECTED_REQUEST = 421,
/**
* The request was well-formed but was unable to be followed due to semantic errors.
*/
UNPROCESSABLE_CONTENT,
/**
* The resource that is being accessed is locked.
*/
LOCKED,
/**
* The request failed due to failure of a previous request.
*/
FAILED_DEPENDENCY,
/**
* Indicates that the server is unwilling to risk processing a request that might be replayed.
*/
TOO_EARLY,
/**
* The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server sends an `Upgrade` header in a 426 response to indicate the required protocol(s).
*/
UPGRADE_REQUIRED,
/**
* The origin server requires the request to be conditional. This response is intended to prevent the 'lost update' problem, where a client `GET`s a resource's state, modifies it and `PUT`s it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.
*/
PRECONDITION_REQUIRED = 428,
/**
* The user has sent too many requests in a given amount of time ("rate limiting").
*/
TOO_MANY_REQUESTS,
/**
* The server is unwilling to process the request because its header fields are too large. The request may be resubmitted after reducing the size of the request header fields.
*/
REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
/**
* The user agent requested a resource that cannot legally be provided, such as a web page censored by a government.
*/
UNAVAILABLE_OR_LEGAL_REASONS = 451,
/****************
* 5xx Requests *
****************/
/**
* The server has encountered a situation it does not know how to handle.
*/
INTERNAL_SERVER_ERROR = 500,
/**
* The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are `GET` and `HEAD`.
*/
NOT_IMPLEMENTED,
/**
* This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.
*/
BAD_GATEWAY,
/**
* The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This response should be used for temporary conditions and the `Retry-After` HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.
*/
SERVICE_UNAVAILABLE,
/**
* This error response is given when the server is acting as a gateway and cannot get a response in time.
*/
GATEWAY_TIMEOUT,
/**
* The HTTP version used in the request is not supported by the server.
*/
HTTP_VERSION_NOT_SUPPORTED,
/**
* The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
*/
VARIANT_ALSO_NEGOTIATES,
/**
* The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.
*/
INSUFFICIENT_STORAGE,
/**
* The server detected an infinite loop while processing the request.
*/
LOOP_DETECTED,
/**
* Further extensions to the request are required for the server to fulfill it.
*/
NOT_EXTENDED = 510,
/**
* Indicates that the client needs to authenticate to gain network access.
*/
NETWORK_AUTHENTIFICATION_REQUIRED,
}

View File

@ -1,3 +1,3 @@
# Libs
Globally independent objects/classes/functions that MUST be unit testable by themselve
Globally independent objects/classes/functions that SHOULD be unit testable by themselve

View File

@ -1,74 +0,0 @@
import StatusCode from './HTTP/StatusCode'
import { buildRFC7807 } from './RFCs/RFC7807'
import ResponseBuilder from './ResponseBuilder'
interface StorageItem {
pointsRemaining: number
timeReset: number
}
export interface RateLimitHeaders {
"Retry-After"?: string,
"X-RateLimit-Limit": string,
"X-RateLimit-Remaining": string,
"X-RateLimit-Reset": string
}
export default class RateLimiter {
/**
* number of points that can be used per {timeSpan}
*/
public static points = 10
/**
* timeSpan in seconds
*/
public static timeSpan = 60
private static instance: RateLimiter = new RateLimiter()
public static getInstance(): RateLimiter {
return this.instance
}
private storage: Record<string, StorageItem> = {}
public constructor(
private points = RateLimiter.points,
private timeSpan = RateLimiter.timeSpan
) {}
public consume(key: string, value: number = 1): Response | RateLimitHeaders {
let item = this.storage[key]
const now = (new Date().getTime() / 1000)
if (!item) {
item = {
pointsRemaining: this.points,
timeReset: now + this.timeSpan
}
}
if (item.timeReset <= now) {
item.timeReset = now + this.timeSpan
item.pointsRemaining = this.points
}
item.pointsRemaining -= value
this.storage[key] = item
const headers: RateLimitHeaders = {
"X-RateLimit-Limit": this.points.toFixed(0),
"X-RateLimit-Remaining": Math.max(item.pointsRemaining, 0).toFixed(0),
"X-RateLimit-Reset": item.timeReset.toFixed(0)
}
if (item.pointsRemaining < 0) {
const res = new ResponseBuilder()
const resp = buildRFC7807({
type: '/docs/error/rate-limited',
status: StatusCode.TOO_MANY_REQUESTS,
title: 'You are being rate limited as you have done too many requests to the server'
}, res)
res.addHeader('Retry-After', (item.timeReset - now).toFixed(0))
res.addHeaders(headers as any)
return resp
}
return headers
}
}

View File

@ -1,93 +0,0 @@
/**
* try to parse a GCode config string into a number
* @param str the string to try parsing
* @returns a number if parsing happened correctly or undefined
*/
function parseNumber(str: string): number | undefined {
if (!/^-?(\d|\.)+$/g.test(str)) {
return undefined
}
const float = parseFloat(str)
const int = parseInt(str, 10)
if (isNaN(int)) {
return undefined
}
if (int !== float) {
return float
}
return int
}
/**
* decode a print time to a number of seconds
* @param text the text to decode
* @returns the number of seconds in the text
*/
function decodeTime(text: string): number {
let timeInSec = 0
for (const it of text.split(' ')) {
const lastChar = it.charAt(it.length - 1)
const time = parseInt(it.slice(0, it.length - 1), 10)
switch (lastChar) {
case 'm':
timeInSec += time * 60
break;
case 's':
timeInSec += time
break;
case 'h':
timeInSec += time * 60 * 60
break;
case 'd':
timeInSec += time * 60 * 60 * 24
break;
default:
throw new Error(`error parsing time ${it} (${time})`)
}
}
return timeInSec
}
export function getParams(data: string) {
// get the configuration lines
const lines = data.split('\n').filter((it) => it.startsWith(';') && it.includes('='))
// create the config object
const obj: Record<string, string | number> = {}
// loop through each config
for (const line of lines) {
// get its key and value
const [key, value] = line.slice(1).split(/ *= */, 2).map((it) => it.trim())
// sip if it has no key or value
if (!key || !value) {
continue
}
// process the key
let realKey = key
// replace spaces by _
.replace(/ /g, '_')
// remove unparseable characters
.replace(/\[|\]|\(|\)/g, '')
// process the value
const realValue = parseNumber(value) ?? value
// add an offset if the key is already cited
let offset = 0
while (obj[`${realKey}${offset > 0 ? `_${offset}` : ''}`] && obj[`${realKey}${offset > 0 ? `_${offset}` : ''}`] !== realValue) {
offset++
}
// chnge the key to add the offset
if (offset > 0) {
realKey = `${realKey}_${offset}`
}
// detect key collisions (it will never happens with the while above)
// if (obj[realKey] && obj[realKey] !== realValue) {
// throw new Error(`Key collision ${key}=${realValue} ${realKey}=${obj[realKey]}`)
// }
// set the value to the key
obj[realKey] = realValue
// transform the time to a number of seconds
if (realKey === 'estimated_printing_time_normal_mode') {
obj['estimated_printing_time_seconds'] = decodeTime(value)
}
}
return obj
}

View File

@ -1,123 +0,0 @@
import DaoFactory from '../models/DaoFactory'
import CookieManager from './CookieManager'
import { buildRFC7807 } from './RFCs/RFC7807'
export interface Permission {
name: string
/**
* if set it will be usable by users
*
* else only users with the `admin.` prefix in the key can run it
*/
api: boolean
/**
* if set to true it will pass if a cookie authenticate a valid user
*/
cookie: boolean
}
/**
* validate the authentification
* @param request the request
* @param permission the permission to validate
* @returns a Response if the request is invalid, null otherwise
*
* TODO: implement rate limiting
* http/2.0 429 TOO MANY REQUESTS
* Content-Type: application/json+problem
* X-RateLimit-Limit: 1000 // number of request you cn make until hitting the rate limit
* X-RateLimit-Remaining: 0 // number of request remaining until the rate limit is atteined
* X-RateLimit-Reset: 123456789 // EPOCH time when the rate limit reset
* X-RateLimit-Reset-After: 9 // Number of seconds before the remaining Rate reset
*/
export async function validateAuth(request: Request, permission: Permission): Promise<Response | string> {
const apiKeyHeader = request.headers.get('Authorization')
const cookieHeader = request.headers.get('Cookie')
if (apiKeyHeader) {
const apiKey = apiKeyHeader.slice(apiKeyHeader.lastIndexOf(' ') + 1)
const dao = await DaoFactory.get('apiKey').findOne({
key: apiKey
})
const perm = permission.name.split('.')
const match = dao?.permissions.find((it) => {
const itSplit = it.split('.')
if (itSplit[0] === 'admin') {
itSplit.shift()
}
for (let idx = 0; idx < itSplit.length; idx++) {
const permissionLayer = itSplit[idx]
const requestPermissionLayer = perm[idx]
if (permissionLayer === '*') {
return true
} else if (permissionLayer !== requestPermissionLayer) {
return false
}
}
return itSplit.length === perm.length
// return it.endsWith(permission.name)
})
if (match && (permission.api || match.startsWith('admin.'))) {
return apiKey
} else if (permission.api) {
return buildRFC7807({
type: '/docs/errors/unauthorized-access',
status: 401,
title: 'Unauthorized access',
details: `you are missing the permission "${permission.name}" or is not an admin`
})
}
} else if (permission.api && !permission.cookie) {
return buildRFC7807({
type: '/docs/errors/unauthorized-access',
status: 401,
title: 'Unauthorized access',
details: `You MUST define an API key fo use this endpoint`
})
}
if (cookieHeader && permission.cookie) {
// TODO: make a better cookie implementation
const cookies = new CookieManager(cookieHeader)
const userCookie = cookies.get('userId')
if (!userCookie) {
return buildRFC7807({
type: '/docs/errors/unauthorized-access',
status: 401,
title: 'Unauthorized access',
details: `you must be connected to use this endpoint (missing the userId cookie)`
})
}
const dao = await DaoFactory.get('user').get(userCookie)
if (!dao) {
return buildRFC7807({
type: '/docs/errors/unauthorized-access',
status: 401,
title: 'Unauthorized access',
details: `the user does not exists`
})
}
return userCookie
} else if (!permission.api && permission.cookie) {
return buildRFC7807({
type: '/docs/errors/unauthorized-access',
status: 401,
title: 'Unauthorized access',
details: `You MUST be connected to your account to use this endpoint`
})
} else if (permission.api && permission.cookie) {
return buildRFC7807({
type: '/docs/errors/unauthorized-access',
status: 401,
title: 'Unauthorized access',
details: `You must be connected or use an API key to access this endpoint`
})
}
return buildRFC7807({
type: '/docs/errors/page-not-found',
status: 404,
title: 'Page not found',
details: `the following endpoint does not exists`
})
}