Signed-off-by: Florian BOUILLON <f.bouillon@aptatio.com>
This commit is contained in:
parent
2bd59f902f
commit
09ed4c487d
1
.github/workflows/build_and_check.yml
vendored
1
.github/workflows/build_and_check.yml
vendored
@ -28,7 +28,6 @@ jobs:
|
||||
- name: Check
|
||||
run: npm run check
|
||||
|
||||
|
||||
- name: Test
|
||||
run : |
|
||||
npm run start &
|
||||
|
@ -1,8 +0,0 @@
|
||||
_id: spc_94f36546799342789aa1fe32dea23879
|
||||
type: ApiSpec
|
||||
parentId: wrk_3cc2135f64d540d5937412dae4d8aa07
|
||||
modified: 1687897230775
|
||||
created: 1686699516083
|
||||
fileName: New Document
|
||||
contents: ""
|
||||
contentType: yaml
|
@ -1,14 +0,0 @@
|
||||
_id: env_776870492ea845feb9ba8db60dfad2cd
|
||||
type: Environment
|
||||
parentId: env_d9baf994467f850b2f5eb10e34a1d922a1554245
|
||||
modified: 1687972720998
|
||||
created: 1687972311428
|
||||
name: Production
|
||||
data:
|
||||
BASE_URL: https://slicer.fi3d.fr
|
||||
dataPropertyOrder:
|
||||
"&":
|
||||
- BASE_URL
|
||||
color: null
|
||||
isPrivate: false
|
||||
metaSortKey: 1687972311428
|
@ -1,16 +0,0 @@
|
||||
_id: env_d9baf994467f850b2f5eb10e34a1d922a1554245
|
||||
type: Environment
|
||||
parentId: wrk_3cc2135f64d540d5937412dae4d8aa07
|
||||
modified: 1687898302664
|
||||
created: 1686699516087
|
||||
name: Base Environment
|
||||
data:
|
||||
BASE_URL: http://localhost:3000
|
||||
API_KEY: cb021190-a2fd-4234-99c1-684391e785f7
|
||||
dataPropertyOrder:
|
||||
"&":
|
||||
- BASE_URL
|
||||
- API_KEY
|
||||
color: null
|
||||
isPrivate: false
|
||||
metaSortKey: 1686699516087
|
@ -1,11 +0,0 @@
|
||||
_id: env_e53abedcd2be412c9c501073a658bedd
|
||||
type: Environment
|
||||
parentId: env_d9baf994467f850b2f5eb10e34a1d922a1554245
|
||||
modified: 1687972824301
|
||||
created: 1687972816648
|
||||
name: Development
|
||||
data: {}
|
||||
dataPropertyOrder: null
|
||||
color: null
|
||||
isPrivate: false
|
||||
metaSortKey: 1687972816648
|
@ -1,25 +0,0 @@
|
||||
_id: req_1515365089cb432182dbaea37363c652
|
||||
type: Request
|
||||
parentId: wrk_3cc2135f64d540d5937412dae4d8aa07
|
||||
modified: 1687979177027
|
||||
created: 1687383219272
|
||||
url: "{{ _.BASE_URL
|
||||
}}/api/v1/users/648f81f857503c7d29465318/configs/64936bd944de499b5483bf15/fil\
|
||||
es/config.ini"
|
||||
name: Get a file
|
||||
description: ""
|
||||
method: GET
|
||||
body: {}
|
||||
parameters: []
|
||||
headers: []
|
||||
authentication:
|
||||
type: bearer
|
||||
token: "{{ _.API_KEY }}"
|
||||
metaSortKey: -1686699516056.5
|
||||
isPrivate: false
|
||||
settingStoreCookies: true
|
||||
settingSendCookies: true
|
||||
settingDisableRenderRequestBody: false
|
||||
settingEncodeUrl: true
|
||||
settingRebuildPath: true
|
||||
settingFollowRedirects: global
|
@ -1,35 +0,0 @@
|
||||
_id: req_1f22118c14924c109a0e570fd06332c4
|
||||
type: Request
|
||||
parentId: wrk_3cc2135f64d540d5937412dae4d8aa07
|
||||
modified: 1687979408498
|
||||
created: 1687382885330
|
||||
url: "{{ _.BASE_URL }}/api/v1/users/648f81f857503c7d29465318/configs"
|
||||
name: Create new config
|
||||
description: ""
|
||||
method: POST
|
||||
body:
|
||||
mimeType: application/json
|
||||
text: ""
|
||||
parameters:
|
||||
- id: pair_c7979be1d7bd4c219d0f613f4c778810
|
||||
name: algo
|
||||
value: filament_used_g * 5
|
||||
description: ""
|
||||
- id: pair_2c62d697fa13486dbe27897c6f44fbd2
|
||||
name: scale
|
||||
value: "2"
|
||||
description: ""
|
||||
headers:
|
||||
- name: Content-Type
|
||||
value: application/json
|
||||
authentication:
|
||||
type: bearer
|
||||
token: "{{ _.API_KEY }}"
|
||||
metaSortKey: -1686699516069
|
||||
isPrivate: false
|
||||
settingStoreCookies: true
|
||||
settingSendCookies: true
|
||||
settingDisableRenderRequestBody: false
|
||||
settingEncodeUrl: true
|
||||
settingRebuildPath: true
|
||||
settingFollowRedirects: global
|
@ -1,23 +0,0 @@
|
||||
_id: req_3756d11c98a94741a5b2a06077b6d39f
|
||||
type: Request
|
||||
parentId: fld_eb864538a51541fb95eca9ea362b686c
|
||||
modified: 1687979889111
|
||||
created: 1687979867093
|
||||
url: "{{ _.BASE_URL }}/api/v1/users"
|
||||
name: update
|
||||
description: ""
|
||||
method: PATCH
|
||||
body: {}
|
||||
parameters: []
|
||||
headers: []
|
||||
authentication:
|
||||
type: bearer
|
||||
token: "{{ _.API_KEY }}"
|
||||
metaSortKey: -1686859546747.625
|
||||
isPrivate: false
|
||||
settingStoreCookies: true
|
||||
settingSendCookies: true
|
||||
settingDisableRenderRequestBody: false
|
||||
settingEncodeUrl: true
|
||||
settingRebuildPath: true
|
||||
settingFollowRedirects: global
|
@ -1,23 +0,0 @@
|
||||
_id: req_701b1740deeb45dbb7dc94b8a2b322b7
|
||||
type: Request
|
||||
parentId: fld_eb864538a51541fb95eca9ea362b686c
|
||||
modified: 1687979892209
|
||||
created: 1687979842182
|
||||
url: "{{ _.BASE_URL }}/api/v1/users"
|
||||
name: create
|
||||
description: ""
|
||||
method: POST
|
||||
body: {}
|
||||
parameters: []
|
||||
headers: []
|
||||
authentication:
|
||||
type: bearer
|
||||
token: "{{ _.API_KEY }}"
|
||||
metaSortKey: -1687339638708.5
|
||||
isPrivate: false
|
||||
settingStoreCookies: true
|
||||
settingSendCookies: true
|
||||
settingDisableRenderRequestBody: false
|
||||
settingEncodeUrl: true
|
||||
settingRebuildPath: true
|
||||
settingFollowRedirects: global
|
@ -1,23 +0,0 @@
|
||||
_id: req_86619e03d7094a9eb7f7ca35c7e520c2
|
||||
type: Request
|
||||
parentId: fld_eb864538a51541fb95eca9ea362b686c
|
||||
modified: 1687979887280
|
||||
created: 1687979869709
|
||||
url: "{{ _.BASE_URL }}/api/v1/users"
|
||||
name: delete
|
||||
description: ""
|
||||
method: DELETE
|
||||
body: {}
|
||||
parameters: []
|
||||
headers: []
|
||||
authentication:
|
||||
type: bearer
|
||||
token: "{{ _.API_KEY }}"
|
||||
metaSortKey: -1686779531420.8125
|
||||
isPrivate: false
|
||||
settingStoreCookies: true
|
||||
settingSendCookies: true
|
||||
settingDisableRenderRequestBody: false
|
||||
settingEncodeUrl: true
|
||||
settingRebuildPath: true
|
||||
settingFollowRedirects: global
|
@ -1,23 +0,0 @@
|
||||
_id: req_d687fdb8d20f4a93b7d721acbdbe8f53
|
||||
type: Request
|
||||
parentId: fld_eb864538a51541fb95eca9ea362b686c
|
||||
modified: 1687979809503
|
||||
created: 1687979761323
|
||||
url: "{{ _.BASE_URL }}/api/v1/users"
|
||||
name: list
|
||||
description: ""
|
||||
method: GET
|
||||
body: {}
|
||||
parameters: []
|
||||
headers: []
|
||||
authentication:
|
||||
type: bearer
|
||||
token: "{{ _.API_KEY }}"
|
||||
metaSortKey: -1687979761323
|
||||
isPrivate: false
|
||||
settingStoreCookies: true
|
||||
settingSendCookies: true
|
||||
settingDisableRenderRequestBody: false
|
||||
settingEncodeUrl: true
|
||||
settingRebuildPath: true
|
||||
settingFollowRedirects: global
|
@ -1,41 +0,0 @@
|
||||
_id: req_f64c7df01b9c4364860fe06f7ebd74bf
|
||||
type: Request
|
||||
parentId: wrk_3cc2135f64d540d5937412dae4d8aa07
|
||||
modified: 1687972521892
|
||||
created: 1686699516094
|
||||
url: "{{ _.BASE_URL }}/api/v1/slice/64936ba744de499b5483bf0a"
|
||||
name: Slice an object
|
||||
description: ""
|
||||
method: POST
|
||||
body:
|
||||
mimeType: application/octet-stream
|
||||
fileName: C:\Users\micro\Downloads\toad_6cm.STL
|
||||
parameters:
|
||||
- id: pair_c7979be1d7bd4c219d0f613f4c778810
|
||||
name: algo
|
||||
value: filament_used_g * 0.5
|
||||
description: ""
|
||||
- id: pair_2c62d697fa13486dbe27897c6f44fbd2
|
||||
name: scale
|
||||
value: "0.1"
|
||||
description: ""
|
||||
disabled: true
|
||||
- id: pair_ea7d519d6ad443edb3926a6831a9abbc
|
||||
name: scale-to-fit
|
||||
value: 179,179,179
|
||||
description: ""
|
||||
disabled: true
|
||||
headers:
|
||||
- name: Content-Type
|
||||
value: model/stl
|
||||
authentication:
|
||||
type: bearer
|
||||
token: cb021190-a2fd-4234-99c1-684391e785f7
|
||||
metaSortKey: -1686699516094
|
||||
isPrivate: false
|
||||
settingStoreCookies: true
|
||||
settingSendCookies: true
|
||||
settingDisableRenderRequestBody: false
|
||||
settingEncodeUrl: true
|
||||
settingRebuildPath: true
|
||||
settingFollowRedirects: global
|
@ -1,23 +0,0 @@
|
||||
_id: req_fa536693954e46088f9d0da033bf2f9c
|
||||
type: Request
|
||||
parentId: fld_eb864538a51541fb95eca9ea362b686c
|
||||
modified: 1687979848643
|
||||
created: 1687979848643
|
||||
url: "{{ _.BASE_URL }}/api/v1/users"
|
||||
name: read
|
||||
description: ""
|
||||
method: GET
|
||||
body: {}
|
||||
parameters: []
|
||||
headers: []
|
||||
authentication:
|
||||
type: bearer
|
||||
token: "{{ _.API_KEY }}"
|
||||
metaSortKey: -1687019577401.25
|
||||
isPrivate: false
|
||||
settingStoreCookies: true
|
||||
settingSendCookies: true
|
||||
settingDisableRenderRequestBody: false
|
||||
settingEncodeUrl: true
|
||||
settingRebuildPath: true
|
||||
settingFollowRedirects: global
|
@ -1,10 +0,0 @@
|
||||
_id: fld_eb864538a51541fb95eca9ea362b686c
|
||||
type: RequestGroup
|
||||
parentId: wrk_3cc2135f64d540d5937412dae4d8aa07
|
||||
modified: 1687979686748
|
||||
created: 1687979675228
|
||||
name: Users
|
||||
description: ""
|
||||
environment: {}
|
||||
environmentPropertyOrder: null
|
||||
metaSortKey: -1687299590688.0625
|
@ -1,6 +0,0 @@
|
||||
_id: uts_b1a00bf2496c4cff93b7a7b2871927a9
|
||||
type: UnitTestSuite
|
||||
parentId: wrk_3cc2135f64d540d5937412dae4d8aa07
|
||||
modified: 1686699516095
|
||||
created: 1686699516095
|
||||
name: Example Test Suite
|
@ -1,8 +0,0 @@
|
||||
_id: wrk_3cc2135f64d540d5937412dae4d8aa07
|
||||
type: Workspace
|
||||
parentId: null
|
||||
modified: 1686699516082
|
||||
created: 1686699516082
|
||||
name: New Document
|
||||
description: ""
|
||||
scope: design
|
36
Dockerfile
36
Dockerfile
@ -1,13 +1,9 @@
|
||||
# This Dockerfile allows you to run Astro using @astro/node integration
|
||||
# This Dockerfile allows you to run AstroJS in server mode
|
||||
|
||||
#########
|
||||
# Build #
|
||||
#########
|
||||
FROM node:20-alpine as BUILD_IMAGE
|
||||
|
||||
# External deps (for node-gyp add: "python3 make g++")
|
||||
# git is used to install the npm packages with git deps
|
||||
RUN apk add --no-cache git
|
||||
FROM docker.io/node:20-alpine as BUILD_IMAGE
|
||||
|
||||
# run as non root user
|
||||
USER node
|
||||
@ -27,36 +23,17 @@ ADD --chown=node:node . .
|
||||
# build
|
||||
RUN npm run build
|
||||
|
||||
# remove dev deps
|
||||
RUN npm prune --omit=dev
|
||||
|
||||
##############
|
||||
# Production #
|
||||
##############
|
||||
FROM node:20-slim as PROD_IMAGE
|
||||
FROM docker.io/node:20-alpine as PROD_IMAGE
|
||||
|
||||
# inform software to be in production
|
||||
ENV NODE_ENV=production
|
||||
ENV HOST=0.0.0.0
|
||||
ENV ASTRO_TELEMETRY_DISABLED=true
|
||||
|
||||
# Download & Install Slic3r
|
||||
# RUN apt-get update \
|
||||
# && apt-get install -y --no-install-recommends \
|
||||
# slic3r \
|
||||
# && rm -rf /var/lib/apt/lists/*
|
||||
# ENV SLICER_PATH slic3r
|
||||
|
||||
# Download & install PrusaSlicer
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
prusa-slicer bzip2 libglu1-mesa-dev libegl-dev \
|
||||
&& apt-get remove prusa-slicer -y \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
ADD https://github.com/prusa3d/PrusaSlicer/releases/download/version_2.6.0/PrusaSlicer-2.6.0+linux-x64-GTK3-202306191220.tar.bz2 ./
|
||||
RUN tar -xvf PrusaSlicer-2.6.0+linux-x64-GTK3-202306191220.tar.bz2 -C /opt
|
||||
|
||||
ENV PATH /opt/PrusaSlicer-2.6.0+linux-x64-GTK3-202306191220/bin:$PATH
|
||||
ENV SLICER_PATH prusa-slicer
|
||||
|
||||
# run as non root user
|
||||
USER node
|
||||
@ -64,11 +41,6 @@ USER node
|
||||
# go to work folder
|
||||
WORKDIR /home/node
|
||||
|
||||
# download & Install Bambu Studio
|
||||
# ADD --chown=node:node https://github.com/bambulab/BambuStudio/releases/download/v01.05.00.61/Bambu_Studio_linux_fedora_v01.05.00.61_20230314200047.AppImage ./
|
||||
# ENV SLICER_PATH /home/node/Bambu_Studio_linux_fedora_v01.05.00.61_20230314200047.AppImage
|
||||
# RUN chmod +x /home/node/Bambu_Studio_linux_fedora_v01.05.00.61_20230314200047.AppImage
|
||||
|
||||
# copy from build image
|
||||
COPY --chown=node:node --from=BUILD_IMAGE /home/node/node_modules ./node_modules
|
||||
COPY --chown=node:node --from=BUILD_IMAGE /home/node/dist ./dist
|
||||
|
38
Dockerfile.static
Normal file
38
Dockerfile.static
Normal file
@ -0,0 +1,38 @@
|
||||
# This Dockerfile allows you to run Astro in a static container (no server side)
|
||||
|
||||
#########
|
||||
# Build #
|
||||
#########
|
||||
FROM docker.io/node:20-alpine as BUILD_IMAGE
|
||||
|
||||
# run as non root user
|
||||
USER node
|
||||
|
||||
# go to user repository
|
||||
WORKDIR /home/node
|
||||
|
||||
# Add package json
|
||||
ADD --chown=node:node package.json package-lock.json ./
|
||||
|
||||
# install dependencies from package lock
|
||||
RUN npm ci
|
||||
|
||||
# Add project files
|
||||
ADD --chown=node:node . .
|
||||
|
||||
# build
|
||||
RUN npm run build
|
||||
|
||||
##############
|
||||
# Production #
|
||||
##############
|
||||
FROM docker.io/nginx:1-alpine
|
||||
|
||||
# go to NGINX folder
|
||||
WORKDIR /usr/share/nginx/html
|
||||
|
||||
# Copy the nginx config
|
||||
ADD ./.docker/nginx.conf /etc/nginx/nginx.conf
|
||||
|
||||
# Copy dist fro mthe build image
|
||||
COPY --from=BUILD_IMAGE /home/node/dist ./
|
@ -2,22 +2,30 @@ import { defineConfig } from 'astro/config'
|
||||
import tailwind from "@astrojs/tailwind"
|
||||
import node from "@astrojs/node"
|
||||
|
||||
// const faviconHook = {
|
||||
// name: 'Favicon',
|
||||
// hooks: {
|
||||
// "astro:build:setup": async () => {
|
||||
// await Manifest.create('./src/assets/favicon.png', {
|
||||
// name: 'Template'
|
||||
// })
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// https://astro.build/config
|
||||
export default defineConfig({
|
||||
site: 'https://print.dzeio.com',
|
||||
integrations: [tailwind()],
|
||||
compressHTML: true,
|
||||
build: {
|
||||
assets: 'assets'
|
||||
assets: 'assets',
|
||||
inlineStylesheets: 'auto',
|
||||
split: true
|
||||
},
|
||||
server: {
|
||||
port: 3000,
|
||||
host: true
|
||||
},
|
||||
trailingSlash: 'never',
|
||||
output: 'server',
|
||||
adapter: node({
|
||||
mode: "standalone"
|
||||
}),
|
||||
vite: {
|
||||
server: {
|
||||
watch: {
|
||||
@ -25,5 +33,15 @@ export default defineConfig({
|
||||
usePolling: !!process.env.WSL_DISTRO_NAME
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
experimental: {
|
||||
assets: true
|
||||
},
|
||||
|
||||
// Customizable depending on goal
|
||||
output: 'server',
|
||||
adapter: node({
|
||||
mode: "standalone"
|
||||
}),
|
||||
site: 'https://print.dzeio.com',
|
||||
})
|
||||
|
5
cypress/README.md
Normal file
5
cypress/README.md
Normal file
@ -0,0 +1,5 @@
|
||||
# Cypress
|
||||
|
||||
Hold End2End tests
|
||||
|
||||
currently WIP
|
52
nginx.conf
Normal file
52
nginx.conf
Normal file
@ -0,0 +1,52 @@
|
||||
worker_processes 1;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
server {
|
||||
listen 3000;
|
||||
listen [::]:3000;
|
||||
|
||||
server_name _;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html index.htm;
|
||||
include /etc/nginx/mime.types;
|
||||
|
||||
gzip on;
|
||||
gzip_min_length 1000;
|
||||
gzip_proxied expired no-cache no-store private auth;
|
||||
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;
|
||||
|
||||
error_page 404 /404.html;
|
||||
error_page 500 502 503 504 /500.html;
|
||||
|
||||
location / {
|
||||
try_files $uri $uri.html /$uri /index.html;
|
||||
}
|
||||
|
||||
# Plausible script
|
||||
location /js/index.js {
|
||||
# Change this if you use a different variant of the script
|
||||
proxy_pass https://plausible.io/js/script.js;
|
||||
proxy_set_header Host plausible.io;
|
||||
|
||||
# Tiny, negligible performance improvement. Very optional.
|
||||
proxy_buffering on;
|
||||
}
|
||||
|
||||
# Plausible script
|
||||
location /api/event {
|
||||
proxy_pass https://plausible.io/api/event;
|
||||
proxy_set_header Host plausible.io;
|
||||
proxy_buffering on;
|
||||
proxy_http_version 1.1;
|
||||
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
}
|
||||
}
|
||||
}
|
1349
package-lock.json
generated
1349
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
17
package.json
17
package.json
@ -1,13 +1,11 @@
|
||||
{
|
||||
"name": "@fi3d/slicer-as-a-service",
|
||||
"version": "0.0.1",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "astro dev",
|
||||
"start": "node ./dist/server/entry.mjs",
|
||||
"build": "astro build",
|
||||
"astro": "astro",
|
||||
"check": "npm run check:astro && npm run check:typescript",
|
||||
"check:astro": "astro check",
|
||||
"check:typescript": "tsc --noEmit",
|
||||
@ -22,20 +20,13 @@
|
||||
"@dzeio/object-util": "^1",
|
||||
"@dzeio/url-manager": "^1",
|
||||
"astro": "^2",
|
||||
"bcryptjs": "^2",
|
||||
"jsonwebtoken": "^9",
|
||||
"lucide-astro": "^0.256.1",
|
||||
"mathjs": "^11",
|
||||
"mongoose": "^7",
|
||||
"tailwindcss": "^3"
|
||||
"lucide-astro": "^0.262.0",
|
||||
"tailwindcss": "^4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/typography": "^0.5.9",
|
||||
"@types/bcryptjs": "^2",
|
||||
"@types/jsonwebtoken": "^9",
|
||||
"@types/node": "^20",
|
||||
"@vitest/coverage-v8": "^0.32.2",
|
||||
"@vitest/coverage-v8": "^0.33.0",
|
||||
"cypress": "^12",
|
||||
"vitest": "^0.32.2"
|
||||
"vitest": "^0.33.0"
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +0,0 @@
|
||||
<svg width="206" height="110" viewBox="0 0 206 110" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M63.7908 75.4986V37.0836H89.5535V44.3452H72.4524V52.383H87.6657V59.6447H72.4524V75.4986H63.7908ZM95.6732 37.0836H104.335V75.4986H95.6732V37.0836ZM121.459 76.3301C120.459 76.3301 119.404 76.2564 118.294 76.1083C117.183 75.9975 116.11 75.8312 115.073 75.6094C114.037 75.3877 113.093 75.1478 112.242 74.8888C111.39 74.6303 110.724 74.3899 110.243 74.1682L111.853 67.2945C112.815 67.7011 114.037 68.1446 115.518 68.6249C117.035 69.0683 118.904 69.2901 121.125 69.2901C123.679 69.2901 125.549 68.8098 126.733 67.8488C127.917 66.8883 128.51 65.5947 128.51 63.9685C128.51 62.9707 128.288 62.1392 127.844 61.474C127.436 60.772 126.863 60.2177 126.122 59.811C125.382 59.3675 124.494 59.0722 123.457 58.9241C122.458 58.7396 121.384 58.6469 120.237 58.6469H117.017V51.9949H120.681C121.495 51.9949 122.273 51.9213 123.013 51.7732C123.791 51.6255 124.475 51.3852 125.068 51.0526C125.66 50.6832 126.122 50.2029 126.456 49.6113C126.826 48.9834 127.011 48.2073 127.011 47.2831C127.011 46.5811 126.863 45.9714 126.567 45.4538C126.27 44.9368 125.882 44.5115 125.401 44.1789C124.956 43.8463 124.419 43.6064 123.791 43.4583C123.198 43.2736 122.587 43.1812 121.958 43.1812C120.366 43.1812 118.886 43.4214 117.516 43.9017C116.184 44.3824 114.962 44.9736 113.852 45.6756L110.909 39.6335C111.501 39.264 112.186 38.8759 112.963 38.4694C113.778 38.0629 114.666 37.6933 115.629 37.3608C116.591 37.0282 117.609 36.751 118.682 36.5293C119.793 36.3075 120.959 36.1967 122.18 36.1967C124.438 36.1967 126.381 36.4738 128.01 37.0282C129.676 37.5455 131.045 38.3031 132.119 39.3009C133.192 40.2618 133.988 41.4074 134.506 42.7378C135.024 44.0312 135.284 45.4538 135.284 47.006C135.284 48.5213 134.858 49.9994 134.007 51.4406C133.155 52.8451 132.008 53.9169 130.564 54.6557C132.563 55.469 134.099 56.6886 135.173 58.3143C136.283 59.9037 136.838 61.8252 136.838 64.0794C136.838 65.8532 136.542 67.498 135.95 69.0129C135.358 70.4914 134.432 71.7846 133.174 72.8932C131.915 73.9651 130.305 74.8152 128.343 75.4431C126.418 76.0347 124.124 76.3301 121.459 76.3301ZM153.46 68.4586C153.867 68.4958 154.33 68.5326 154.848 68.5694C155.403 68.5694 156.051 68.5694 156.791 68.5694C161.122 68.5694 164.324 67.4794 166.397 65.2989C168.507 63.1188 169.562 60.1068 169.562 56.2633C169.562 52.2353 168.562 49.1865 166.563 47.1168C164.564 45.0476 161.4 44.0126 157.069 44.0126C156.476 44.0126 155.866 44.0312 155.237 44.068C154.607 44.068 154.015 44.1053 153.46 44.1789V68.4586ZM178.501 56.2633C178.501 59.5893 177.982 62.4904 176.946 64.9663C175.909 67.4426 174.429 69.4936 172.504 71.1194C170.616 72.7455 168.303 73.9651 165.564 74.7779C162.825 75.5912 159.752 75.9975 156.347 75.9975C154.792 75.9975 152.978 75.9239 150.906 75.7757C148.833 75.6649 146.797 75.4063 144.798 74.9997V37.5825C146.797 37.2129 148.87 36.9727 151.017 36.8619C153.2 36.714 155.07 36.6401 156.625 36.6401C159.919 36.6401 162.899 37.0097 165.564 37.7488C168.266 38.4879 170.579 39.652 172.504 41.2411C174.429 42.8302 175.909 44.8627 176.946 47.3386C177.982 49.8149 178.501 52.7896 178.501 56.2633Z" fill="black"/>
|
||||
<path d="M49.5 15C48.806 14.3071 48.0241 14 47 14H18C16.9758 14 16.1917 14.3071 15.5 15C14.806 15.6905 14.5 16.4775 14.5 17.5V75.5C14.5 76.5225 14.806 77.3071 15.5 78C16.1917 78.6908 16.9758 79 18 79H25.5V82.5C25.5 83.5225 25.8083 84.3071 26.5 85C27.194 85.6903 27.9758 86 29 86H36C37.0242 86 37.8084 85.6903 38.5 85C39.194 84.3071 39.5 83.5225 39.5 82.5V79H47C48.0241 79 48.806 78.6908 49.5 78C50.1914 77.3071 50.5 76.5225 50.5 75.5V17.5C50.5 16.4775 50.1914 15.6905 49.5 15Z" fill="black"/>
|
||||
<path d="M189.53 96H33C30.5 96 29.5 95 29.5 92.5V86H35.5V88C35.5 90 36.5 91 38.5 91H189.53C190.5 91 191.5 91.5 191.5 93.5C191.5 95.5 190.5 96 189.53 96Z" fill="black"/>
|
||||
</svg>
|
Before Width: | Height: | Size: 3.7 KiB |
7
src/assets/README.md
Normal file
7
src/assets/README.md
Normal 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]
|
BIN
src/assets/layouts/Base/favicon.png
Normal file
BIN
src/assets/layouts/Base/favicon.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 1.9 KiB |
9
src/assets/layouts/Base/favicon.svg
Normal file
9
src/assets/layouts/Base/favicon.svg
Normal 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 |
24
src/components/Favicon/Favicon.astro
Normal file
24
src/components/Favicon/Favicon.astro
Normal 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" /> -->
|
||||
</>
|
33
src/components/Favicon/Manifest.ts
Normal file
33
src/components/Favicon/Manifest.ts
Normal 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"
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
4
src/components/Passthrough/Passthrough.astro
Normal file
4
src/components/Passthrough/Passthrough.astro
Normal file
@ -0,0 +1,4 @@
|
||||
---
|
||||
const json = JSON.stringify(Astro.props)
|
||||
---
|
||||
<script id="ASTRO_DATA" is:inline type="application/json" set:html={json}></script>
|
@ -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>
|
42
src/components/Picture.astro.tmp
Normal file
42
src/components/Picture.astro.tmp
Normal 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
3
src/components/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
# Components
|
||||
|
||||
Contains big elements that can be reused by themselve
|
5
src/content/README.md
Normal file
5
src/content/README.md
Normal file
@ -0,0 +1,5 @@
|
||||
# Content
|
||||
|
||||
Contains raw content for pages.
|
||||
|
||||
Mostly some static pages or blog posts.
|
@ -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,
|
||||
// };
|
||||
|
@ -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
17
src/env.d.ts
vendored
@ -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
25
src/layouts/Base.astro
Normal 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>
|
@ -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
7
src/layouts/README.md
Normal 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
5
src/libs/AstroUtils.ts
Normal file
@ -0,0 +1,5 @@
|
||||
export default class AstroUtils {
|
||||
public static async wrap<T = void>(fn: () => T | Promise<T>) {
|
||||
return await fn()
|
||||
}
|
||||
}
|
@ -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)
|
||||
}
|
@ -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]
|
||||
}
|
||||
|
||||
}
|
@ -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
|
||||
}
|
||||
}
|
||||
}
|
@ -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,
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
|
@ -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
|
||||
}
|
||||
}
|
@ -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
|
||||
}
|
@ -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
9
src/middleware/README.md
Normal 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`
|
@ -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()
|
||||
})
|
@ -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()
|
||||
})
|
@ -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)
|
||||
|
@ -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')
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,8 +0,0 @@
|
||||
export default interface APIKey {
|
||||
id: string
|
||||
user: string
|
||||
key: string
|
||||
permissions: Array<string>
|
||||
created: Date
|
||||
updated: Date
|
||||
}
|
@ -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
|
||||
}
|
||||
}
|
@ -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')
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
export default interface Config {
|
||||
id: string
|
||||
user: string
|
||||
type: 'prusa'
|
||||
files: Array<{
|
||||
name: string
|
||||
data: Buffer
|
||||
}>
|
||||
created: Date
|
||||
updated: Date
|
||||
}
|
@ -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
|
||||
}
|
||||
}
|
||||
|
@ -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; }) {
|
||||
}
|
||||
}
|
@ -1,3 +0,0 @@
|
||||
export default interface Session {
|
||||
userId: string
|
||||
}
|
@ -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')
|
||||
}
|
||||
}
|
||||
}
|
@ -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
5
src/pages/README.md
Normal file
@ -0,0 +1,5 @@
|
||||
# Content
|
||||
|
||||
Contains raw content for pages.
|
||||
|
||||
Mostly some static pages or blog posts.
|
@ -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>
|
@ -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>
|
@ -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>
|
@ -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()
|
||||
}
|
@ -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()
|
||||
}
|
@ -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()
|
||||
}
|
@ -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()
|
||||
}
|
@ -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"'
|
||||
})
|
||||
}
|
@ -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>
|
@ -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>
|
||||
|
@ -1,10 +1,9 @@
|
||||
// const defaultTheme = require('tailwindcss/defaultTheme')
|
||||
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [
|
||||
require('@tailwindcss/typography'),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
5
tests/README.md
Normal file
5
tests/README.md
Normal file
@ -0,0 +1,5 @@
|
||||
# Tests
|
||||
|
||||
Old Unit tests for each elements
|
||||
|
||||
the paths should correspond to the base folder from `src`
|
@ -1,5 +1,4 @@
|
||||
import { assert, expect, test } from 'vitest'
|
||||
import { comparePassword, hashPassword } from '../src/libs/AuthUtils'
|
||||
import { expect, test } from 'vitest'
|
||||
|
||||
// Edit an assertion and save to see HMR in action
|
||||
|
||||
@ -8,26 +7,3 @@ test('Math.sqrt()', () => {
|
||||
expect(Math.sqrt(144)).toBe(12);
|
||||
expect(Math.sqrt(2)).toBe(Math.SQRT2);
|
||||
});
|
||||
|
||||
test('JSON', () => {
|
||||
const input = {
|
||||
foo: 'hello',
|
||||
bar: 'world',
|
||||
};
|
||||
|
||||
const output = JSON.stringify(input);
|
||||
|
||||
expect(output).eq('{"foo":"hello","bar":"world"}');
|
||||
assert.deepEqual(JSON.parse(output), input, 'matches original');
|
||||
});
|
||||
|
||||
test('auth util', async () => {
|
||||
const password = 'pouet'
|
||||
|
||||
const out1 = await hashPassword(password)
|
||||
expect(out1).not.toBe(password)
|
||||
const out2 = await hashPassword(password)
|
||||
expect(out2).not.toBe(out1)
|
||||
expect(await comparePassword(password, out1)).toBe(true)
|
||||
expect(await comparePassword(password, out2)).toBe(true)
|
||||
})
|
||||
|
@ -1,22 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { comparePassword, hashPassword } from '../../src/libs/AuthUtils'
|
||||
|
||||
|
||||
describe('AuthUtils', () => {
|
||||
it('should hash the password', async () => {
|
||||
expect(await hashPassword('test')).toBeDefined()
|
||||
})
|
||||
|
||||
it('should compared succeffully password', async () => {
|
||||
const pass = 'test'
|
||||
const hash = await hashPassword(pass)
|
||||
expect(await comparePassword(pass, hash)).toBe(true)
|
||||
})
|
||||
|
||||
it('should not generate twice the same hash', async () => {
|
||||
const pass = 'test'
|
||||
const hash1 = await hashPassword(pass)
|
||||
const hash2 = await hashPassword(pass)
|
||||
expect(hash1).not.toBe(hash2)
|
||||
})
|
||||
})
|
@ -1,50 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getParams } from '../../src/libs/gcodeUtils'
|
||||
|
||||
|
||||
describe('gcodeUtils', () => {
|
||||
it('should get parameters', () => {
|
||||
const gcode = `
|
||||
balfs
|
||||
dgfdf
|
||||
sd
|
||||
httphq
|
||||
estimated_printing_time_normal_modewef
|
||||
|
||||
; test=a
|
||||
fgd
|
||||
;test =b
|
||||
;test= c
|
||||
;test = d
|
||||
;number=1.12
|
||||
;number2=-1
|
||||
;invalid=
|
||||
;invalid
|
||||
;estimated_printing_time_normal_mode=1d 1h 1m 1s
|
||||
|
||||
sdffgaf
|
||||
fgsdf
|
||||
g
|
||||
sfd
|
||||
hh
|
||||
ehf
|
||||
`
|
||||
expect(getParams(gcode)).toEqual({
|
||||
test: 'a',
|
||||
test_1: 'b',
|
||||
test_2: 'c',
|
||||
test_3: 'd',
|
||||
number: 1.12,
|
||||
number2: -1,
|
||||
estimated_printing_time_normal_mode: '1d 1h 1m 1s',
|
||||
estimated_printing_time_seconds: 90061
|
||||
})
|
||||
})
|
||||
|
||||
it('should get parameters', () => {
|
||||
const gcode = `
|
||||
;estimated_printing_time_normal_mode=1w 1d 1h 1m 1s
|
||||
`
|
||||
expect(() => getParams(gcode)).toThrow(/1w/g)
|
||||
})
|
||||
})
|
@ -1,122 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import RateLimiter from '../../src/libs/RateLimiter'
|
||||
|
||||
|
||||
// Mock Response
|
||||
vi.stubGlobal('Response', class {
|
||||
public constructor(
|
||||
public body?: any,
|
||||
public init?: any
|
||||
) {}
|
||||
})
|
||||
|
||||
describe('Rate Limit', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
|
||||
it('should work with global variant', () => {
|
||||
const now1 = new Date(1000)
|
||||
vi.setSystemTime(now1)
|
||||
const limit = RateLimiter.getInstance()
|
||||
|
||||
const result1 = limit.consume('key')
|
||||
expect(result1).toEqual({
|
||||
"X-RateLimit-Limit": '10',
|
||||
"X-RateLimit-Remaining": '9',
|
||||
"X-RateLimit-Reset": '61'
|
||||
})
|
||||
const limit2 = RateLimiter.getInstance()
|
||||
const result2 = limit2.consume('key')
|
||||
expect(result2).toEqual({
|
||||
"X-RateLimit-Limit": '10',
|
||||
"X-RateLimit-Remaining": '8',
|
||||
"X-RateLimit-Reset": '61'
|
||||
})
|
||||
})
|
||||
|
||||
it('should consume points', () => {
|
||||
const now1 = new Date(1000)
|
||||
vi.setSystemTime(now1)
|
||||
const limit = new RateLimiter(2, 10)
|
||||
|
||||
const result1 = limit.consume('key')
|
||||
expect(result1).toEqual({
|
||||
"X-RateLimit-Limit": '2',
|
||||
"X-RateLimit-Remaining": '1',
|
||||
"X-RateLimit-Reset": '11'
|
||||
})
|
||||
const result2 = limit.consume('key')
|
||||
expect(result2).toEqual({
|
||||
"X-RateLimit-Limit": '2',
|
||||
"X-RateLimit-Remaining": '0',
|
||||
"X-RateLimit-Reset": '11'
|
||||
})
|
||||
})
|
||||
|
||||
it('should rate limit', () => {
|
||||
const now1 = new Date(1000)
|
||||
vi.setSystemTime(now1)
|
||||
const limit = new RateLimiter(1, 10)
|
||||
|
||||
const result1 = limit.consume('key')
|
||||
expect(result1).toEqual({
|
||||
"X-RateLimit-Limit": '1',
|
||||
"X-RateLimit-Remaining": '0',
|
||||
"X-RateLimit-Reset": '11'
|
||||
})
|
||||
const result2 = limit.consume('key')
|
||||
expect(result2).instanceOf(Response)
|
||||
const result3 = limit.consume('key')
|
||||
expect(result3).instanceOf(Response)
|
||||
})
|
||||
|
||||
it('should reset after some time', () => {
|
||||
const now1 = new Date(1000)
|
||||
vi.setSystemTime(now1)
|
||||
const limit = new RateLimiter(2, 10)
|
||||
|
||||
const result1 = limit.consume('key')
|
||||
expect(result1).toEqual({
|
||||
"X-RateLimit-Limit": '2',
|
||||
"X-RateLimit-Remaining": '1',
|
||||
"X-RateLimit-Reset": '11'
|
||||
})
|
||||
const result2 = limit.consume('key')
|
||||
expect(result2).toEqual({
|
||||
"X-RateLimit-Limit": '2',
|
||||
"X-RateLimit-Remaining": '0',
|
||||
"X-RateLimit-Reset": '11'
|
||||
})
|
||||
|
||||
|
||||
const result3 = limit.consume('key')
|
||||
expect(result3).instanceOf(Response)
|
||||
|
||||
const now2 = new Date(11000)
|
||||
vi.setSystemTime(now2)
|
||||
const result4 = limit.consume('key')
|
||||
expect(result4).toEqual({
|
||||
"X-RateLimit-Limit": '2',
|
||||
"X-RateLimit-Remaining": '1',
|
||||
"X-RateLimit-Reset": '21'
|
||||
})
|
||||
|
||||
|
||||
const result5 = limit.consume('key')
|
||||
expect(result5).toEqual({
|
||||
"X-RateLimit-Limit": '2',
|
||||
"X-RateLimit-Remaining": '0',
|
||||
"X-RateLimit-Reset": '21'
|
||||
})
|
||||
|
||||
|
||||
const result6 = limit.consume('key')
|
||||
expect(result6).instanceOf(Response)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
Loading…
x
Reference in New Issue
Block a user