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

7
src/assets/README.md Normal file
View File

@ -0,0 +1,7 @@
# Assets
Contains images that can be imported directly into the application
# Folder Architecture
- /assets/[path to element from src]/[folder named as the element]/[assets of the element].[ext]

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 128 128">
<path d="M50.4 78.5a75.1 75.1 0 0 0-28.5 6.9l24.2-65.7c.7-2 1.9-3.2 3.4-3.2h29c1.5 0 2.7 1.2 3.4 3.2l24.2 65.7s-11.6-7-28.5-7L67 45.5c-.4-1.7-1.6-2.8-2.9-2.8-1.3 0-2.5 1.1-2.9 2.7L50.4 78.5Zm-1.1 28.2Zm-4.2-20.2c-2 6.6-.6 15.8 4.2 20.2a17.5 17.5 0 0 1 .2-.7 5.5 5.5 0 0 1 5.7-4.5c2.8.1 4.3 1.5 4.7 4.7.2 1.1.2 2.3.2 3.5v.4c0 2.7.7 5.2 2.2 7.4a13 13 0 0 0 5.7 4.9v-.3l-.2-.3c-1.8-5.6-.5-9.5 4.4-12.8l1.5-1a73 73 0 0 0 3.2-2.2 16 16 0 0 0 6.8-11.4c.3-2 .1-4-.6-6l-.8.6-1.6 1a37 37 0 0 1-22.4 2.7c-5-.7-9.7-2-13.2-6.2Z" />
<style>
path { fill: #000; }
@media (prefers-color-scheme: dark) {
path { fill: #FFF; }
}
</style>
</svg>

After

Width:  |  Height:  |  Size: 758 B

View File

@ -0,0 +1,24 @@
---
import { getImage } from 'astro:assets'
export interface Props {
svg: ImageMetadata
png: ImageMetadata
icoPath?: string
}
if (Astro.props.icoPath !== '/favicon.ico') {
console.warn('It is recommanded that the ICO file should be located at /favicon.ico')
}
const appleTouch = await getImage({src: Astro.props.png, width: 180, height: 180})
---
<>
<link rel="icon" href={Astro.props.icoPath ?? "/favicon.ico"} sizes="any">
<link rel="icon" href={Astro.props.svg.src} type="image/svg+xml">
<link rel="apple-touch-icon" href={appleTouch.src} />
<!-- Currently not integrated until I find a way to. -->
<!-- <link rel="manifest" href="/site.webmanifest" /> -->
</>

View File

@ -0,0 +1,33 @@
import { getImage } from 'astro:assets'
export default class Manifest {
static async create(baseImage, options) {
const [
i192,
i512
] = await Promise.all([
getImage({src: baseImage, format: 'png', width: 192, height: 192}),
getImage({src: baseImage, format: 'png', width: 512, height: 512})
])
return JSON.stringify({
name: options.name,
short_name: options.name,
icons: [
{
src: i192.src,
sizes: "192x192",
type: "image/png"
},
{
src: i512.src,
sizes: "512x512",
type: "image/png"
}
],
theme_color: options.color ?? "#fff",
background_color: options.color ?? "#fff",
display: "standalone"
}
)
}
}

View File

@ -0,0 +1,4 @@
---
const json = JSON.stringify(Astro.props)
---
<script id="ASTRO_DATA" is:inline type="application/json" set:html={json}></script>

View File

@ -1,4 +1,3 @@
---
/**
* note: you MUST only pass simple items that can go in JSON format natively
*/
@ -9,7 +8,3 @@ export function load<T extends {} = {}>(): T {
}
return JSON.parse(tag.innerText)
}
const json = JSON.stringify(Astro.props)
---
<script id="ASTRO_DATA" is:inline type="application/json" set:html={json}></script>

View File

@ -0,0 +1,42 @@
---
import { LocalImageProps, RemoteImageProps, getImage } from 'astro:assets'
import AstroUtils from '../libs/AstroUtils'
type ImageProps = LocalImageProps | RemoteImageProps
export type Props = ImageProps
const res = await AstroUtils.wrap(async () => {
const image = Astro.props.src
const ext = typeof image === 'string' ? image.substring(image.lastIndexOf('.')) : image.format
if (ext === 'svg') {
return {
format: 'raw',
props: {
...Astro.props,
src: typeof image === 'string' ? image : image.src
}
}
}
const avif = await getImage({src: Astro.props.src, format: 'avif'})
const webp = await getImage({src: Astro.props.src, format: 'webp'})
const orig = await getImage({src: Astro.props.src, format: ext})
return {
format: 'new',
avif,
webp,
orig
}
})
---
{res.format === 'new' && (
<picture class:list={[res.orig!.attributes.class, Astro.props.class]}>
<source srcset={res.avif!.src} type="image/avif" />
<source srcset={res.webp!.src} type="image/webp" />
<img src={res.orig!.src} class="" {...res.orig!.attributes} />
</picture>
) || (
<img {...res.props} />
)}

3
src/components/README.md Normal file
View File

@ -0,0 +1,3 @@
# Components
Contains big elements that can be reused by themselve

5
src/content/README.md Normal file
View File

@ -0,0 +1,5 @@
# Content
Contains raw content for pages.
Mostly some static pages or blog posts.

View File

@ -1,15 +1,15 @@
// 1. Import utilities from `astro:content`
import { defineCollection, z } from 'astro:content'
// import { defineCollection, z } from 'astro:content'
// 2. Define your collection(s)
const docsCollection = defineCollection({
type: 'content',
schema: z.object({
title: z.string()
})
})
// const docsCollection = defineCollection({
// type: 'content',
// schema: z.object({
// title: z.string()
// })
// })
// 3. Export a single `collections` object to register your collection(s)
// This key should match your collection directory name in "src/content"
export const collections = {
'docs': docsCollection,
};
// export const collections = {
// 'docs': docsCollection,
// };

View File

@ -1,23 +0,0 @@
---
title: 'Unauthorized Access Error'
---
# Unauthorized Access Error
## Possible Errors
### Permission Error
You need to have an API key with the correct permission to use the specified resource
### Missing API Key
To have access to most of the API Urls you need to have n API key in your headers like the following
```http
Authorization: Bearer 935b6640-25fe-402e-8b18-e60de88bc0da
```
### Cookies not found
An alternative to the API Key is to have your cookies set, this is mostly for in browser and will only work while being connected on the website

17
src/env.d.ts vendored
View File

@ -1,13 +1,11 @@
/// <reference path="../.astro/types.d.ts" />
/// <reference types="astro/client" />
/// <reference types="astro/client-image" />
/// <reference path="./libs/ResponseBuilder" />
/**
* Environment variables declaration
*/
interface ImportMetaEnv {
PRUSASLICER_PATH?: string
BAMBUSTUDIO_PATH?: string
MONGODB?: string
PRIVATE_KEY?: string
PUBLIC_KEY?: string
}
interface ImportMeta {
@ -16,11 +14,10 @@ interface ImportMeta {
declare namespace App {
/**
* Middlewares variables
*/
interface Locals {
/**
* authentification key is the api key or the session token
*/
authKey?: string
responseBuilder: ResponseBuilder
}
}

25
src/layouts/Base.astro Normal file
View File

@ -0,0 +1,25 @@
---
export interface Props {
title: string
}
import Favicon from '../components/Favicon/Favicon.astro'
import IconSVG from '../assets/layouts/Base/favicon.svg'
import IconPNG from '../assets/layouts/Base/favicon.png'
const { title } = Astro.props;
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="description" content="Astro description">
<meta name="viewport" content="width=device-width" />
<Favicon svg={IconSVG} png={IconPNG} icoPath="/favicon.ico" />
<title>{title}</title>
</head>
<body class="bg-gray-50">
<slot />
</body>
</html>

View File

@ -1,37 +1,11 @@
---
import { WifiOff } from 'lucide-astro'
export interface Props {
title: string;
}
import Base, { type Props as BaseProps } from './Base.astro'
const { title } = Astro.props;
export interface Props extends BaseProps {}
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="description" content="Astro description">
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="generator" content={Astro.generator} />
<title>{title}</title>
</head>
<body class="bg-gray-50">
<aside class="fixed top-0 left-0 z-40 w-64 p-4 h-screen bg-white border-r-2 border-gray-100">
<div class="mb-2 flex">
<img src="/logo.svg" class="w-1/2" alt="FI3D Logo">
<WifiOff class='pokemon' />
</div>
<ul class="space-y-2 font-medium">
<li class="p-4 w-full bg-red-100 hover:bg-red-200 cursor-pointer text-center">Item</li>
</ul>
</aside>
<div class="p-4 sm:ml-64">
<slot />
</div>
</body>
</html>
<Base {...Astro.props}>
<main class="container">
<slot />
</main>
</Base>

7
src/layouts/README.md Normal file
View File

@ -0,0 +1,7 @@
# Layouts
Application different layouts they should extends `Base.astro` if added and also pass the parameters of Base.astro to the page
## Base.astro
This is the base file for each path of the application, executed for each paths

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`
})
}

9
src/middleware/README.md Normal file
View File

@ -0,0 +1,9 @@
# Middlewares
This folder contains middlewares for the SSR pages/endpoints
They are run for every paths independent of the middleware and in the specified order of the `index.ts`
## locals
You can pass variables to other middlewares and endpoints by adding a variable in `locals` and in `App.Locals` in `env.d.ts`

View File

@ -1,52 +0,0 @@
import { objectLoop } from '@dzeio/object-util'
import URLManager from '@dzeio/url-manager'
import { defineMiddleware } from "astro/middleware"
import { buildRFC7807 } from '../libs/RFCs/RFC7807'
import { Permission, validateAuth } from '../libs/validateAuth'
const endpointsPermissions: Record<string, Permission> = {
'/api/v1/users/[userId]/configs/[configId]/files/[fileName]': {
api: true,
cookie: true,
name: 'configs.get'
},
'/api/v1/slice/[configId]': {
api: true,
cookie: true,
name: 'slice.slice'
}
}
function objectFind(obj: object, fn: (value: any, key: any) => boolean): {key: string, value: any} | null {
let res: {key: string, value: any} | null = null
objectLoop(obj, (value, key) => {
const tmp = fn(value, key)
if (tmp) {
res = {
key, value
}
}
return !tmp
})
return res
}
// `context` and `next` are automatically typed
export default defineMiddleware(async (context, next) => {
if (!context.request.url.includes('api')) {
return next()
}
const permission = objectFind(endpointsPermissions, (_, key) => new URLManager(key).toString(context.params as any) === context.url.pathname)
if (!permission) {
return buildRFC7807({
type: 'idk'
})
}
const auth = await validateAuth(context.request, permission.value)
if (typeof auth === 'object') {
return auth
}
context.locals.authKey = auth
return next()
})

View File

@ -1,18 +0,0 @@
import { defineMiddleware } from "astro/middleware"
import RateLimiter from '../libs/RateLimiter'
// `context` and `next` are automatically typed
export default defineMiddleware(async ({ request, locals }, next) => {
if (!request.url.includes('api')) {
return next()
}
const limit = RateLimiter.getInstance().consume(locals.authKey as string)
if ('status' in limit) {
return limit
}
locals.responseBuilder.addHeaders(limit)
return next()
})

View File

@ -1,7 +1,5 @@
import { sequence } from "astro/middleware"
import apiAuth from './apiAuth'
import apiRateLimit from './apiRateLimit'
import responseBuilder from './responseBuilder'
export const onRequest = sequence(responseBuilder, apiAuth, apiRateLimit)
export const onRequest = sequence(responseBuilder)

View File

@ -1,79 +0,0 @@
import { objectOmit } from '@dzeio/object-util'
import mongoose from 'mongoose'
import type APIKey from '.'
import Client from '../Client'
import Dao from '../Dao'
export default class APIKeyDao extends Dao<APIKey> {
// @ts-expect-error typing fix
private model = mongoose.models['APIKey'] as null ?? mongoose.model('APIKey', new mongoose.Schema({
user: { type: String, required: true },
key: { type: String, required: true, unique: true, index: true},
permissions: [{ type: String }]
}, {
timestamps: true
}))
public async create(obj: Omit<APIKey, 'id' | 'created' | 'updated'>): Promise<APIKey | null> {
await Client.get()
return this.fromSource(await this.model.create(obj))
}
public async findAll(query?: Partial<APIKey> | undefined): Promise<APIKey[]> {
await Client.get()
try {
if (query?.id) {
const item = await this.model.findById(new mongoose.Types.ObjectId(query.id))
if (!item) {
return []
}
return [this.fromSource(item)]
}
const resp = await this.model.find(query ? this.toSource(query as APIKey) : {})
return resp.map(this.fromSource)
} catch (e) {
console.error(e)
return []
}
}
public async update(obj: APIKey): Promise<APIKey | null> {
await Client.get()
const query = await this.model.updateOne({
_id: new mongoose.Types.ObjectId(obj.id)
}, this.toSource(obj))
if (query.matchedCount >= 1) {
obj.updated = new Date()
return obj
}
return null
// return this.fromSource()
}
public async delete(obj: APIKey): Promise<boolean> {
await Client.get()
const res = await this.model.deleteOne({
_id: new mongoose.Types.ObjectId(obj.id)
})
return res.deletedCount > 0
}
private toSource(obj: APIKey): Omit<APIKey, 'id'> {
return objectOmit(obj, 'id', 'updated', 'created')
}
private fromSource(doc: mongoose.Document<any, any, APIKey>): APIKey {
return {
id: doc._id.toString(),
user: doc.get('user'),
key: doc.get('key'),
permissions: doc.get('permissions') ?? [],
updated: doc.get('updatedAt'),
created: doc.get('createdAt')
}
}
}

View File

@ -1,8 +0,0 @@
export default interface APIKey {
id: string
user: string
key: string
permissions: Array<string>
created: Date
updated: Date
}

View File

@ -1,18 +0,0 @@
import mongoose from 'mongoose'
export default class Client {
private static connectionString = import.meta.env.MONGODB
private static client = false
public static async get() {
if (!this.connectionString) {
throw new Error('Can\'t connect to the database, missing the connection string')
}
if (!this.client) {
console.log(this.connectionString)
mongoose.connect(this.connectionString)
this.client = true
}
return this.client
}
}

View File

@ -1,83 +0,0 @@
import { objectOmit } from '@dzeio/object-util'
import mongoose from 'mongoose'
import type Config from '.'
import Client from '../Client'
import Dao from '../Dao'
export default class ConfigDao extends Dao<Config> {
// @ts-expect-error typing fix
private model = mongoose.models['Config'] as null ?? mongoose.model('Config', new mongoose.Schema({
user: { type: String, required: true },
type: { type: String, required: true},
files: [{
name: { type: String, unique: true, required: true},
data: { type: Buffer, required: true }
}]
}, {
timestamps: true
}))
public async create(obj: Omit<Config, 'id' | 'created' | 'updated'>): Promise<Config | null> {
await Client.get()
return this.fromSource(await this.model.create(obj))
}
public async findAll(query?: Partial<Config> | undefined): Promise<Config[]> {
await Client.get()
try {
if (query?.id) {
const item = await this.model.findById(new mongoose.Types.ObjectId(query.id))
if (!item) {
return []
}
return [this.fromSource(item)]
}
const resp = await this.model.find(query ? this.toSource(query as Config) : {})
return resp.map(this.fromSource)
} catch (e) {
console.error(e)
return []
}
}
public async update(obj: Config): Promise<Config | null> {
await Client.get()
const query = await this.model.updateOne({
_id: new mongoose.Types.ObjectId(obj.id)
}, this.toSource(obj))
if (query.matchedCount >= 1) {
obj.updated = new Date()
return obj
}
return null
// return this.fromSource()
}
public async delete(obj: Config): Promise<boolean> {
await Client.get()
const res = await this.model.deleteOne({
_id: new mongoose.Types.ObjectId(obj.id)
})
return res.deletedCount > 0
}
private toSource(obj: Config): Omit<Config, 'id'> {
return objectOmit(obj, 'id', 'updated', 'created')
}
private fromSource(doc: mongoose.Document<any, any, Config>): Config {
return {
id: doc._id.toString(),
user: doc.get('user'),
type: doc.get('type'),
files: doc.get('files') ?? [],
updated: doc.get('updatedAt'),
created: doc.get('createdAt')
}
}
}

View File

@ -1,11 +0,0 @@
export default interface Config {
id: string
user: string
type: 'prusa'
files: Array<{
name: string
data: Buffer
}>
created: Date
updated: Date
}

View File

@ -1,8 +1,3 @@
import APIKeyDao from './APIKey/APIKeyDao'
import ConfigDao from './Config/ConfigDao'
import SessionDao from './Session/SessionDao'
import UserDao from './User/UserDao'
/**
* TODO:
* Add to `DaoItem` your model name
@ -15,10 +10,6 @@ import UserDao from './User/UserDao'
* Touch this interface to define which key is linked to which Dao
*/
interface DaoItem {
config: ConfigDao
user: UserDao
apiKey: APIKeyDao
session: SessionDao
}
/**
@ -57,10 +48,6 @@ export default class DaoFactory {
*/
private static initDao(item: keyof DaoItem): any | undefined {
switch (item) {
case 'config': return new ConfigDao()
case 'user': return new UserDao()
case 'apiKey': return new APIKeyDao()
case 'session': return new SessionDao()
default: return undefined
}
}

View File

@ -1,52 +0,0 @@
import jwt, { SignOptions } from 'jsonwebtoken'
import type Session from '.'
import CookieManager from '../../libs/CookieManager'
export interface SessionOptions {
cookieName: string
security: SignOptions
key?: string
privateKey?: string
publicKey?: string
}
export default class SessionDao {
private options: SessionOptions = {
cookieName: 'session',
security: {
algorithm: 'ES512'
},
privateKey: import.meta.env.PRIVATE_KEY ?? '',
publicKey: import.meta.env.PUBLIC_KEY ?? ''
}
public getSession(req: Request): Session | null {
const cookie = new CookieManager(req.headers.get('Cookie') ?? '').get(this.options.cookieName)
if (!cookie) {
return null
}
try {
return jwt.verify(cookie, (this.options.publicKey || this.options.key) as string) as Session
} catch {
return null
}
}
public setSession(session: Session, res: ResponseInit & { readonly headers: Headers; }) {
const token = jwt.sign(session, (this.options.privateKey || this.options.key) as string, this.options.security)
CookieManager.addCookie(res, {
key: this.options.cookieName,
value: token,
httpOnly: true,
path: '/',
secure: true,
sameSite: 'Strict',
maxAge: 365000
})
}
public removeSession(_res: ResponseInit & { readonly headers: Headers; }) {
}
}

View File

@ -1,3 +0,0 @@
export default interface Session {
userId: string
}

View File

@ -1,71 +0,0 @@
import { objectOmit } from '@dzeio/object-util'
import mongoose from 'mongoose'
import type User from '.'
import Client from '../Client'
import Dao from '../Dao'
export default class UserDao extends Dao<User> {
// @ts-expect-error typing fix
private model = mongoose.models['User'] as null ?? mongoose.model('User', new mongoose.Schema({
email: { type: String, required: true },
password: { type: String, required: true }
}, {
timestamps: true
}))
public async create(obj: Omit<User, 'id' | 'created' | 'updated'>): Promise<User | null> {
await Client.get()
return this.fromSource(await this.model.create(obj))
}
public async findAll(query?: Partial<User> | undefined): Promise<User[]> {
await Client.get()
if (query?.id) {
const item = await this.model.findById(new mongoose.Types.ObjectId(query.id))
if (!item) {
return []
}
return [this.fromSource(item)]
}
const resp = await this.model.find(query ? this.toSource(query as User) : {})
return resp.map(this.fromSource)
}
public async update(obj: User): Promise<User | null> {
await Client.get()
const query = await this.model.updateOne({
_id: new mongoose.Types.ObjectId(obj.id)
}, this.toSource(obj))
if (query.matchedCount >= 1) {
obj.updated = new Date()
return obj
}
return null
// return this.fromSource()
}
public async delete(obj: User): Promise<boolean> {
await Client.get()
const res = await this.model.deleteOne({
_id: new mongoose.Types.ObjectId(obj.id)
})
return res.deletedCount > 0
}
private toSource(obj: User): Omit<User, 'id'> {
return objectOmit(obj, 'id', 'updated', 'created')
}
private fromSource(doc: mongoose.Document<any, any, User>): User {
return {
id: doc._id.toString(),
email: doc.get('email'),
password: doc.get('password'),
updated: doc.get('updatedAt'),
created: doc.get('createdAt')
}
}
}

View File

@ -1,7 +0,0 @@
export default interface User {
id: string
email: string
password: string
created: Date
updated: Date
}

5
src/pages/README.md Normal file
View File

@ -0,0 +1,5 @@
# Content
Contains raw content for pages.
Mostly some static pages or blog posts.

View File

@ -1,66 +0,0 @@
---
import URLManager from '@dzeio/url-manager'
import Layout from '../../layouts/Layout.astro'
import DaoFactory from '../../models/DaoFactory'
import { comparePassword } from '../../libs/AuthUtils'
import Passthrough from '../../components/Passthrough.astro'
const logout = typeof new URLManager(Astro.url).query('logout') === 'string'
if (logout) {
DaoFactory.get('session').removeSession(Astro.response)
}
// DaoFactory.get('session').removeSession(Astro.response)
let connected = false
const sessionDao = DaoFactory.get('session')
if (sessionDao.getSession(Astro.request) && !logout) {
connected = true
}
if (!connected && Astro.request.method === 'POST') {
const form = await Astro.request.formData()
const email = form.get('email') as string
const password = form.get('password') as string
const account = await DaoFactory.get('user').findOne({
email
})
if (account) {
const valid = await comparePassword(password, account.password)
if (valid) {
DaoFactory.get('session').setSession({
userId: account.id
}, Astro.response)
connected = true
}
}
}
---
<Layout title="Welcome to Astro.">
<main>
<form method="post">
<input type="email" name="email" />
<input type="password" name="password" />
<button>Connect</button>
<button></button>
</form>
</main>
<Passthrough connected={connected} />
</Layout>
<script>import { load } from '../../components/Passthrough.astro'
const {
connected
} = load<{connected: boolean}>()
if (connected) {
window.location.pathname = '/'
}
</script>

View File

@ -1,45 +0,0 @@
---
import Layout from '../../layouts/Layout.astro'
import { hashPassword } from '../../libs/AuthUtils'
import DaoFactory from '../../models/DaoFactory'
let errorMessage: string | undefined
if (Astro.request.method === 'POST') {
const form = await Astro.request.formData()
const email = form.get('email') as string
const password = form.get('password') as string
const user = await DaoFactory.get('user').create({
email: email,
password: await hashPassword(password)
})
if (!user) {
errorMessage = 'User already exists'
return
}
DaoFactory.get('session').setSession({
userId: user.id
}, Astro.response)
}
---
<Layout title="Welcome to Astro.">
<main>
{errorMessage && (
<div>
{errorMessage}
</div>
)}
<form method="post">
<input type="email" name="email" id="email"/>
<input type="password" name="password" id="password" />
<input type="password" name="repeat-password" id="repeat-password">
<button>Register</button>
</form>
</main>
</Layout>

View File

@ -1,59 +0,0 @@
---
import Passthrough from '../components/Passthrough.astro'
import Layout from '../layouts/Layout.astro'
import DaoFactory from '../models/DaoFactory'
const session = DaoFactory.get('session').getSession(Astro.request)
if (!session) {
return Astro.redirect('/')
}
const user = await DaoFactory.get('user').get(session.userId)
const list = await DaoFactory.get('apiKey').findAll({
user: user!.id
})
const configs = await DaoFactory.get('config').findAll({
user: user!.id
})
const userId = user?.id ?? 'unknown'
---
<Layout title="Welcome to Astro.">
<main>
<h1>{user?.id}</h1>
<ul>
<li>API Keys</li>
{list.map((it) => (
<li>
<p>access key: {it.key}</p>
<p>permissions: {it.permissions}</p>
</li>
))}
<li>Configurations</li>
{configs.map((it) => (
<li>
<p>{it.id}: {it.type}</p>
<p>{it.files.map((it) => it.name)}</p>
</li>
))}
<button>Create a new API Key</button>
</ul>
</main>
<Passthrough userId={userId} />
</Layout>
<script>
import { load } from '../components/Passthrough.astro'
const vars = load<{userId: string}>()
console.log(vars)
document.querySelector('button')?.addEventListener('click', async () => {
await fetch(`/api/users/${vars.userId}/keys`, {
method: 'POST'
})
window.location.reload()
})
</script>

View File

@ -1,262 +0,0 @@
import Logger from '@dzeio/logger'
import { objectMap, objectOmit } from '@dzeio/object-util'
import URLManager from '@dzeio/url-manager'
import type { APIRoute } from 'astro'
import { evaluate } from 'mathjs'
import { spawn } from 'node:child_process'
import fs from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import StatusCode from '../../../../libs/HTTP/StatusCode'
import { buildRFC7807 } from '../../../../libs/RFCs/RFC7807'
import { getParams } from '../../../../libs/gcodeUtils'
import DaoFactory from '../../../../models/DaoFactory'
interface SliceError {
code: number
output: Array<string>
}
let tmpDir: string
/**
* body is the stl
* query
* price: algorithm from settings
* adionnal settings from https://manual.slic3r.org/advanced/command-line
*/
export const post: APIRoute = async ({ params, request, locals }) => {
if (!tmpDir) {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'saas-'))
}
const configId = params.configId ?? 'undefined'
const config = await DaoFactory.get('config').get(configId)
if (!config) {
return buildRFC7807({
type: '/docs/errors/missing-config',
status: StatusCode.NOT_FOUND,
title: 'The configuration does not exists',
details: `The configuration ${configId} does not exists`
})
}
const input = new Uint8Array(Buffer.from(await request.arrayBuffer()))
if (input.length <= 0) {
return buildRFC7807({
type: '/docs/errors/missing-input-file',
status: StatusCode.BAD_REQUEST,
title: 'You are missing the STL file',
details: `To process a file you need to input the file binary datas as the only body in your request`
})
}
const query = new URLManager(request.url).query()
const processId = (Math.random() * 1000000).toFixed(0)
const logger = new Logger(`process-${processId}`)
const processFolder = `${tmpDir}/${processId}`
const pouet = await fs.mkdir(processFolder, { recursive: true })
logger.log('poeut', pouet)
logger.log('started processing request')
logger.log('writing configs to dir')
for (const file of config.files) {
await fs.writeFile(`${processFolder}/${file.name}`, file.data)
}
const overrides = objectOmit(query, 'algo')
const stlPath = `${processFolder}/input.stl`
const gcodePath = `${processFolder}/output.gcode`
logger.log('writing STL to filesystem')
// write input
await fs.writeFile(stlPath, input, {
encoding: null
})
// additionnal parameters
let additionnalParams = objectMap(overrides, (value, key) => `--${(key as string).replace(/_/g, '-')} ${value}`).join(' ')
let slicerPath: string
let slicerCommand: string
if (config.type === 'prusa' || true) {
slicerPath = import.meta.env.PRUSASLICER_PATH ?? 'prusa-slicer'
additionnalParams += ' --export-gcode --loglevel 4'
slicerCommand = `${path.normalize(stlPath)} --load ${path.normalize(`${processFolder}/config.ini`)} --output ${path.normalize(gcodePath)} ${additionnalParams}`
}
// TODO: check if it does work on a linux environment
// TODO: Externalise IO for the different slicers
try {
logger.log('Running', slicerPath, slicerCommand)
await new Promise<void>((res, rej) => {
const logs: Array<string> = []
const slicer = spawn(`"${slicerPath}"`, slicerCommand.split(' '), {
shell: true
})
const log = (data: Buffer) => {
const line = `${data.toString('utf-8')}`
logger.log(line)
logs.push(line)
}
slicer.stdout.on('data', log)
slicer.stderr.on('data', log)
slicer.on('spawn', () => {
logs.push('Process spawned')
logger.log('Process spawned')
})
slicer.on('error', (err) => {
logs.push('Process error')
logger.log('Process error')
logger.log('error', err)
logs.push(err.toString())
rej(err)
})
slicer.on('close', (code, signal) => {
logs.push('Process closed')
logger.log('Process closed')
logs.push(`with code ${code}`)
logger.log(`with code ${code}`)
logs.push(`and signal ${signal}`)
logger.log(`and signal ${signal}`)
if (typeof code === 'number' && code !== 0) {
rej({
code: code,
output: logs
} as SliceError)
return
}
res()
})
})
} catch (e: any) {
const err = e as SliceError
logger.log('request finished in error :(', processId)
const line = err.toString()
logger.error('error', err, typeof err)
if (err.code === 3221226505 || line.includes('Objects could not fit on the bed')) {
await fs.rm(stlPath)
return buildRFC7807({
type: '/docs/errors/object-too-large',
status: StatusCode.PAYLOAD_TOO_LARGE,
title: 'Object is too large',
details: 'The STL you are trying to compile is too large for the configuration you chose'
}, locals.responseBuilder)
} else if (line.includes('No such file')) {
await fs.rm(stlPath)
return buildRFC7807({
type: '/docs/errors/missing-config-file',
status: StatusCode.NOT_FOUND,
title: 'Configuration file is missing',
details: `the configuration file "${configId}" is not available on the remote server`
}, locals.responseBuilder)
} else if (line.includes('Unknown option')) {
await fs.rm(stlPath)
return buildRFC7807({
type: '/docs/errors/slicer-option-unknown',
status: 400,
title: ' config override doew not exists',
details: 'an override does not exists, please contact an administrator or refer to the documentation'
}, locals.responseBuilder)
} else if (
line.includes('is not recognized as an internal or external command') ||
line.includes('.dll was not loaded')
) {
await fs.rm(stlPath)
return buildRFC7807({
type: '/docs/errors/slicer-not-found',
status: StatusCode.SERVICE_UNAVAILABLE,
title: 'the slicer used to process this file has not been found',
details: 'the server has a misconfiguration meaning that we can\'t process the request, please contact an administrator',
additionnalInfo: line.includes('dll') ? 'Missing DLL' : 'Slicer not found '
}, locals.responseBuilder)
} else if (line.includes('ETIMEDOUT')) {
await fs.rm(stlPath)
return buildRFC7807({
type: '/docs/errors/timed-out-slicing',
status: StatusCode.PAYLOAD_TOO_LARGE,
title: 'Timed out slicing file',
detail: `The file you are trying to process takes too long to be processed`,
processingTimeoutMillis: 60000
}, locals.responseBuilder)
}
return buildRFC7807({
type: '/docs/errors/general-input-output-error',
status: StatusCode.INTERNAL_SERVER_ERROR,
title: 'General I/O error',
details: 'A server error make it impossible to slice the file, please contact an administrator with the json error',
fileId: processId,
config: configId,
// fileSize: req.body.length,
overrides: overrides,
serverMessage:
err.output.map((line) => line.replace(new RegExp(stlPath), `***FILE***`).replace(new RegExp(processFolder), ''))
}, locals.responseBuilder)
}
const gcode = await fs.readFile(gcodePath, 'utf-8')
await fs.rm(processFolder, { recursive: true, force: true })
logger.log('Getting parameters')
const gcodeParams = getParams(gcode)
let price: string | undefined
if (query?.algo) {
let algo = decodeURI(query.algo as string)
// objectLoop(params, (value, key) => {
// if (typeof value !== 'number') {
// return
// }
// while (algo.includes(key)) {
// algo = algo.replace(key, value.toString())
// }
// })
try {
logger.log('Evaluating Alogrithm')
const tmp = evaluate(algo, gcodeParams)
if (typeof tmp === 'number') {
price = tmp.toFixed(2)
} else {
return buildRFC7807({
type: '/docs/errors/algorithm-error',
status: 500,
title: 'Algorithm compilation error',
details: 'It seems the algorithm resolution failed',
algorithm: algo,
algorithmError: 'Algorithm return a Unit',
parameters: gcodeParams
}, locals.responseBuilder)
}
} catch (e) {
logger.dir(e)
return buildRFC7807({
type: '/docs/errors/algorithm-error',
status: 500,
title: 'Algorithm compilation error',
details: 'It seems the algorithm resolution failed',
algorithm: algo,
algorithmError: e,
parameters: gcodeParams
}, locals.responseBuilder)
}
}
logger.log('request successfull :)')
return locals.responseBuilder
.body({
price: price ? parseFloat(price) : undefined,
...getParams(gcode),
gcode
})
.status(200)
.build()
}

View File

@ -1,24 +0,0 @@
import type { APIRoute } from 'astro'
import { buildRFC7807 } from '../../../../../../../../libs/RFCs/RFC7807'
import DaoFactory from '../../../../../../../../models/DaoFactory'
export const get: APIRoute = async ({ params, locals }) => {
const configId = params.configId as string
const fileName = params.fileName as string
const dao = await DaoFactory.get('config').get(configId)
if (!dao) {
return buildRFC7807({
title: 'Config does not exists :('
})
}
const file = dao.files.find((it) => it.name === fileName)
return locals.responseBuilder
.status(200)
.body(file?.data)
.build()
}

View File

@ -1,45 +0,0 @@
import { objectOmit } from '@dzeio/object-util'
import type { APIRoute } from 'astro'
import StatusCode from '../../../../../../libs/HTTP/StatusCode'
import { buildRFC7807 } from '../../../../../../libs/RFCs/RFC7807'
import DaoFactory from '../../../../../../models/DaoFactory'
export const post: APIRoute = async ({ params, request, locals }) => {
const userId = params.userId as string
const body = request.body
if (!body) {
return buildRFC7807({
title: 'Missing config file'
})
}
const reader = body.getReader()
const chunks: Array<Uint8Array> = []
let finished= false
do {
const { done, value } = await reader.read()
finished = done
if (value) {
chunks.push(value)
}
} while (!finished)
const buffer = Buffer.concat(chunks)
const dao = await DaoFactory.get('config').create({
user: userId,
type: 'prusa',
files: [{
name: 'config.ini',
data: buffer
}]
})
return locals.responseBuilder
.status(StatusCode.CREATED)
.body(objectOmit(dao ?? {}, 'files'))
.build()
}

View File

@ -1,20 +0,0 @@
import type { APIRoute } from 'astro'
import crypto from 'node:crypto'
import StatusCode from '../../../../../../libs/HTTP/StatusCode'
import DaoFactory from '../../../../../../models/DaoFactory'
export const post: APIRoute = async ({ params, locals }) => {
const userId = params.userId as string
const dao = await DaoFactory.get('apiKey').create({
user: userId,
key: crypto.randomUUID(),
permissions: [
'admin.user.list'
]
})
return locals.responseBuilder
.status(StatusCode.CREATED)
.body(dao)
.build()
}

View File

@ -1,17 +0,0 @@
import type { APIRoute } from 'astro'
import StatusCode from '../../../../libs/HTTP/StatusCode'
import { buildRFC7807 } from '../../../../libs/RFCs/RFC7807'
export const get: APIRoute = async ({ locals }) => {
return locals.responseBuilder
.status(200)
.body({iam: true})
.build()
}
export const options: APIRoute = async () => {
return buildRFC7807({
status: StatusCode.METHOD_NOT_ALLOWED,
details: 'Allowed methods: "GET"'
})
}

View File

@ -1,24 +0,0 @@
---
import Layout from '../../layouts/Layout.astro'
import { getEntry } from 'astro:content'
import StatusCode from '../../libs/HTTP/StatusCode'
const page = Astro.params.page
let Result: any
const entry = await getEntry('docs', page as any)
if (!entry) {
Astro.response.status = StatusCode.NOT_FOUND
} else {
const { Content } = await entry.render()
Result = Content
}
---
<Layout title={entry?.data.title ?? ''}>
<main class="prose">
{Result && <Result />}
</main>
</Layout>

View File

@ -1,5 +1,5 @@
---
import Layout from '../layouts/Layout.astro';
import Layout from '../layouts/Layout.astro'
---
<Layout title="Welcome to Astro.">
@ -9,9 +9,5 @@ import Layout from '../layouts/Layout.astro';
To get started, open the directory <code>src/pages</code> in your project.<br />
<strong>Code Challenge:</strong> Tweak the "Welcome to Astro" message above.
</p>
<ul role="list" class="link-card-grid">
<li><a href="/account/login">Login</a></li>
<li><a href="/account/register">Register</a></li>
</ul>
</main>
</Layout>