From 4eccba49d87c4e7d9dc16e7585f802b2d728a877 Mon Sep 17 00:00:00 2001 From: ewsgit Date: Thu, 18 Jun 2026 16:46:16 +0100 Subject: [PATCH] nothing --- .../src/assets/fs_template_files/markdown.md | 20 +- instance/src/index.ts | 306 ++-- instance/src/log.ts | 550 +++--- instance/src/system.ts | 118 +- instance/src/systems/api.ts | 548 +++--- instance/src/systems/applications.ts | 3 +- .../src/systems/applications/application.ts | 58 +- .../src/systems/applications/serviceStatus.ts | 8 +- instance/src/systems/authorization.ts | 886 +++++----- instance/src/systems/configuration.ts | 406 ++--- instance/src/systems/consoleCommands.ts | 4 +- .../src/systems/consoleCommands/command.ts | 2 +- .../consoleCommands/commands/application.ts | 66 +- .../systems/consoleCommands/commands/exit.ts | 30 +- .../consoleCommands/commands/feature.ts | 114 +- .../systems/consoleCommands/commands/help.ts | 60 +- .../commands/install_application.ts | 48 +- .../consoleCommands/commands/notify.ts | 84 +- .../systems/consoleCommands/commands/op.ts | 80 +- .../consoleCommands/commands/password.ts | 52 +- .../consoleCommands/commands/restart.ts | 52 +- .../systems/consoleCommands/commands/stop.ts | 30 +- .../consoleCommands/commands/useradd.ts | 178 +- .../consoleCommands/commands/userdel.ts | 78 +- .../systems/consoleCommands/commands/users.ts | 50 +- instance/src/systems/database.ts | 130 +- instance/src/systems/email.ts | 46 +- instance/src/systems/events.ts | 202 +-- instance/src/systems/filesystem.ts | 482 +++--- instance/src/systems/image.ts | 370 ++-- instance/src/systems/notifications.ts | 176 +- instance/src/systems/reverseProxy.ts | 132 +- instance/src/systems/settings.ts | 196 +-- .../applicationSetting/applicationSetting.ts | 62 +- .../applicationSetting/booleanSetting.ts | 196 +-- .../applicationSetting/numberSetting.ts | 194 +-- .../applicationSetting/stringListSetting.ts | 306 ++-- .../applicationSetting/stringSetting.ts | 196 +-- instance/src/systems/terminalUI.ts | 100 +- instance/src/systems/terminalUI/effect.ts | 388 ++--- .../terminalUI/events/keyPressEvent.ts | 24 +- .../terminalUI/events/mouseClickEvent.ts | 24 +- .../terminalUI/events/resizeScreenEvent.ts | 24 +- .../terminalUI/events/scrollDownEvent.ts | 24 +- .../terminalUI/events/scrollUpEvent.ts | 24 +- instance/src/systems/terminalUI/notes.md | 33 + .../src/systems/terminalUI/renderError.ts | 50 +- .../src/systems/terminalUI/scalarValue.ts | 24 +- instance/src/systems/terminalUI/screen.ts | 16 +- instance/src/systems/terminalUI/terminal.ts | 64 +- .../src/systems/terminalUI/terminalEvent.ts | 54 +- instance/src/systems/terminalUI/view.ts | 166 +- .../systems/terminalUI/views/borderView.ts | 34 +- .../src/systems/terminalUI/views/container.ts | 18 +- .../src/systems/terminalUI/views/crossView.ts | 87 +- .../src/systems/terminalUI/views/textInput.ts | 25 +- instance/src/systems/trpc.ts | 178 +- instance/src/systems/trpcRouter.ts | 1490 ++++++++--------- instance/src/systems/users.ts | 1254 +++++++------- instance/src/systems/webFrontend.ts | 56 +- instance/src/web/.gitignore | 48 +- instance/src/web/index.html | 42 +- instance/src/web/package.json | 68 +- instance/src/web/public/app.webmanifest | 26 +- .../onlineworkspace/online_workspace_logo.svg | 38 +- .../online_workspace_wordmark.svg | 46 +- .../assets/placeholder/placeholder_image.svg | 990 +++++------ instance/src/web/public/fonts/roboto.css | 160 +- instance/src/web/public/fonts/roboto_flex.css | 40 +- instance/src/web/src/App.module.scss | 28 +- instance/src/web/src/App.tsx | 70 +- instance/src/web/src/MissingApp.module.scss | 18 +- instance/src/web/src/MissingApp.tsx | 60 +- instance/src/web/src/index.scss | 28 +- instance/src/web/src/index.tsx | 18 +- instance/src/web/src/lib/backend.ts | 14 +- instance/src/web/src/lib/trpc.ts | 56 +- .../web/src/pages/app/AuthCheck.module.scss | 44 +- instance/src/web/src/pages/app/AuthCheck.tsx | 90 +- instance/src/web/src/pages/app/Index.tsx | 26 +- .../src/web/src/pages/app/Layout.module.scss | 20 +- instance/src/web/src/pages/app/Layout.tsx | 132 +- .../web/src/pages/app/Navigation.module.scss | 48 +- instance/src/web/src/pages/app/Navigation.tsx | 216 +-- .../NavigationRailApplications.module.scss | 202 +-- .../NavigationRailApplications.tsx | 150 +- .../NavigationRailAvatar.module.scss | 238 +-- .../NavigationRailAvatar.tsx | 112 +- .../NavigationRailClock.module.scss | 80 +- .../NavigationRailClock.tsx | 100 +- .../NavigationRailNotifications.module.scss | 234 +-- .../NavigationRailNotifications.tsx | 286 ++-- .../notification/Notification.module.scss | 76 +- .../notification/Notification.tsx | 106 +- instance/src/web/src/pages/notFound/Index.tsx | 30 +- .../src/pages/userSelect/Layout.module.scss | 68 +- .../src/web/src/pages/userSelect/Layout.tsx | 54 +- .../forgotPassword/ForgotPassword.module.scss | 28 +- .../forgotPassword/ForgotPassword.tsx | 76 +- .../pages/userSelect/login/Login.module.scss | 68 +- .../web/src/pages/userSelect/login/Login.tsx | 336 ++-- .../userSelect/signup/Signup.module.scss | 82 +- .../src/pages/userSelect/signup/Signup.tsx | 430 ++--- .../userSelect/signup/stages/Email/Email.tsx | 118 +- .../userSelect/signup/stages/Guide/Guide.tsx | 14 +- .../signup/stages/GuidePrompt/GuidePrompt.tsx | 14 +- .../stages/Password/Password.module.scss | 22 +- .../signup/stages/Password/Password.tsx | 246 +-- .../components/Requirement/Requirement.tsx | 44 +- .../signup/stages/Profile/Profile.module.scss | 70 +- .../signup/stages/Profile/Profile.tsx | 182 +- .../stages/TermsOfUse/TermsOfUse.module.scss | 22 +- .../signup/stages/TermsOfUse/TermsOfUse.tsx | 92 +- .../TwoFactorAuthentication.module.scss | 40 +- .../TwoFactorAuthentication.tsx | 214 +-- .../stages/Username/Username.module.scss | 30 +- .../signup/stages/Username/Username.tsx | 164 +- .../signup/stages/VerifyEmail/VerifyEmail.tsx | 142 +- instance/src/web/src/vite-env.d.ts | 2 +- instance/src/web/tsconfig.app.json | 56 +- instance/src/web/tsconfig.json | 14 +- instance/src/web/tsconfig.node.json | 50 +- instance/src/web/vite.config.ts | 64 +- uikit-solid | 2 +- 124 files changed, 8684 insertions(+), 8676 deletions(-) create mode 100644 instance/src/systems/terminalUI/notes.md diff --git a/instance/src/assets/fs_template_files/markdown.md b/instance/src/assets/fs_template_files/markdown.md index dd68906..07d08ca 100644 --- a/instance/src/assets/fs_template_files/markdown.md +++ b/instance/src/assets/fs_template_files/markdown.md @@ -1,11 +1,11 @@ -# Template Markdown File - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam mattis, orci ut porttitor efficitur, nisl quam tincidunt libero, ut pharetra justo metus id augue. In convallis lobortis facilisis. Pellentesque gravida egestas mi nec sagittis. Fusce suscipit vel justo sit amet sodales. Aenean quis ornare lorem. Nam blandit vitae elit et elementum. Suspendisse quis feugiat libero. Vestibulum quis pellentesque libero, ut tincidunt tellus. Integer posuere vel sapien volutpat maximus. Praesent commodo lacus velit, sollicitudin faucibus ipsum cursus et. Praesent sodales congue tempor. Vivamus vel nulla ac tortor commodo tincidunt. Pellentesque nec vestibulum odio, eget accumsan ligula. Sed vel urna quis leo sollicitudin fringilla sed at erat. In fermentum vitae turpis non semper. - -Ut risus orci, condimentum nec ante vel, sollicitudin fermentum lorem. Vivamus velit ex, dapibus eu fringilla vitae, blandit nec nibh. Fusce nec erat nec dui sodales maximus. Mauris et elit lorem. Pellentesque neque metus, malesuada in rhoncus tincidunt, tristique sit amet augue. Proin pharetra nisl sit amet pharetra iaculis. Nam non arcu neque. Nulla non porta ipsum. Etiam luctus lacinia pellentesque. Proin non volutpat elit, lobortis aliquet ante. Nunc dolor diam, gravida nec velit vel, fringilla condimentum libero. Aenean semper sit amet nulla at mollis. - -Quisque velit erat, rhoncus eleifend ex non, malesuada gravida enim. Morbi fermentum sem non augue imperdiet facilisis. Nulla tempus scelerisque mi, a luctus ex. Sed id risus sit amet purus dapibus blandit. Duis libero ipsum, dapibus et dictum eget, pharetra a ante. Suspendisse porta elit non risus vulputate, id blandit nisi congue. Cras arcu purus, placerat non enim vel, vestibulum vehicula lectus. - -Cras eleifend maximus enim imperdiet pharetra. Aliquam erat volutpat. Nulla nec sapien metus. Suspendisse pharetra semper tellus. Donec luctus justo vitae risus dapibus, sit amet egestas mauris consectetur. Ut tempor dui at enim porttitor lacinia. Maecenas vel imperdiet eros. Nullam porttitor elit sed mi mattis, sit amet pulvinar orci bibendum. Praesent sit amet ullamcorper quam. In hac habitasse platea dictumst. Nullam accumsan tortor quam, in porttitor ante efficitur ut. Nulla auctor velit dolor. In gravida tellus ullamcorper mollis dapibus. Proin ut ex purus. - +# Template Markdown File + +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam mattis, orci ut porttitor efficitur, nisl quam tincidunt libero, ut pharetra justo metus id augue. In convallis lobortis facilisis. Pellentesque gravida egestas mi nec sagittis. Fusce suscipit vel justo sit amet sodales. Aenean quis ornare lorem. Nam blandit vitae elit et elementum. Suspendisse quis feugiat libero. Vestibulum quis pellentesque libero, ut tincidunt tellus. Integer posuere vel sapien volutpat maximus. Praesent commodo lacus velit, sollicitudin faucibus ipsum cursus et. Praesent sodales congue tempor. Vivamus vel nulla ac tortor commodo tincidunt. Pellentesque nec vestibulum odio, eget accumsan ligula. Sed vel urna quis leo sollicitudin fringilla sed at erat. In fermentum vitae turpis non semper. + +Ut risus orci, condimentum nec ante vel, sollicitudin fermentum lorem. Vivamus velit ex, dapibus eu fringilla vitae, blandit nec nibh. Fusce nec erat nec dui sodales maximus. Mauris et elit lorem. Pellentesque neque metus, malesuada in rhoncus tincidunt, tristique sit amet augue. Proin pharetra nisl sit amet pharetra iaculis. Nam non arcu neque. Nulla non porta ipsum. Etiam luctus lacinia pellentesque. Proin non volutpat elit, lobortis aliquet ante. Nunc dolor diam, gravida nec velit vel, fringilla condimentum libero. Aenean semper sit amet nulla at mollis. + +Quisque velit erat, rhoncus eleifend ex non, malesuada gravida enim. Morbi fermentum sem non augue imperdiet facilisis. Nulla tempus scelerisque mi, a luctus ex. Sed id risus sit amet purus dapibus blandit. Duis libero ipsum, dapibus et dictum eget, pharetra a ante. Suspendisse porta elit non risus vulputate, id blandit nisi congue. Cras arcu purus, placerat non enim vel, vestibulum vehicula lectus. + +Cras eleifend maximus enim imperdiet pharetra. Aliquam erat volutpat. Nulla nec sapien metus. Suspendisse pharetra semper tellus. Donec luctus justo vitae risus dapibus, sit amet egestas mauris consectetur. Ut tempor dui at enim porttitor lacinia. Maecenas vel imperdiet eros. Nullam porttitor elit sed mi mattis, sit amet pulvinar orci bibendum. Praesent sit amet ullamcorper quam. In hac habitasse platea dictumst. Nullam accumsan tortor quam, in porttitor ante efficitur ut. Nulla auctor velit dolor. In gravida tellus ullamcorper mollis dapibus. Proin ut ex purus. + Nullam consectetur urna tellus, ut condimentum justo porta commodo. Aenean interdum, enim et porttitor gravida, augue velit pulvinar mauris, et vulputate nisi diam eget lectus. Nulla facilisi. Sed ac ligula fringilla, imperdiet sapien non, consequat purus. Nunc interdum tortor sed finibus tincidunt. Donec a velit eget dui commodo ultricies. Duis vel diam aliquam, vulputate augue eget, hendrerit lorem. Donec a congue lacus. Phasellus volutpat fermentum est, congue placerat nisi interdum nec. Fusce ultricies dictum tincidunt. Aliquam id pharetra eros, efficitur posuere nibh. Duis porttitor orci enim, a egestas nibh dignissim non. Curabitur suscipit facilisis mattis. \ No newline at end of file diff --git a/instance/src/index.ts b/instance/src/index.ts index cfdf5e8..96d7a20 100644 --- a/instance/src/index.ts +++ b/instance/src/index.ts @@ -1,153 +1,153 @@ -import chalk from "chalk"; -// https://github.com/cah4a/trpc-bun-adapter/blob/main/src/createBunHttpHandler.ts TODO: patch this and merge into the instance package -import Log from "./log.ts"; -import type { Sys } from "./system.ts"; -import ApplicationsSystem from "./systems/applications.ts"; -import AuthorizationSystem from "./systems/authorization.ts"; -import ConfigurationSystem from "./systems/configuration.ts"; -import ConsoleCommandsSystem from "./systems/consoleCommands.ts"; -import DatabaseSystem from "./systems/database.ts"; -import EmailSystem from "./systems/email.ts"; -import EventSystem, { WorkspacesEvent } from "./systems/events.ts"; -import FilesystemSystem from "./systems/filesystem.ts"; -import ImageSystem from "./systems/image.ts"; -import NotificationsSystem from "./systems/notifications.ts"; -import ReverseProxySystem from "./systems/reverseProxy.ts"; -import { StringListApplicationSetting } from "./systems/settings/applicationSetting/stringListSetting.ts"; -import SettingsSystem from "./systems/settings.ts"; -import TerminalUISystem from "./systems/terminalUI.ts"; -import TRPCSystem from "./systems/trpc.ts"; -import { createTRPCContext as createWorkspacesTRPCContext, workspacesRouter } from "./systems/trpcRouter.ts"; -import UsersSystem from "./systems/users.ts"; -import WebFrontendSystem from "./systems/webFrontend.ts"; - -export enum InstanceStatus { - Online, - Offline, - StartingUp, - Stopping, -} - -class Instance { - sys: Sys; - log: Log; - webServer!: Deno.HttpServer; - status: InstanceStatus; - - constructor() { - this.log = new Log(this); - - // @ts-ignore Don't know, don't care - this.sys = {}; - - this.sys.event = new EventSystem(this); - this.sys.filesystem = new FilesystemSystem(this); - this.sys.configuration = new ConfigurationSystem(this); - this.sys.database = new DatabaseSystem(this); - this.sys.notifications = new NotificationsSystem(this); - this.sys.consoleCommands = new ConsoleCommandsSystem(this); - this.sys.users = new UsersSystem(this); - this.sys.authorization = new AuthorizationSystem(this); - this.sys.applications = new ApplicationsSystem(this); - this.sys.tRPC = new TRPCSystem(this); - this.sys.image = new ImageSystem(this); - this.sys.settings = new SettingsSystem(this); - this.sys.webFrontend = new WebFrontendSystem(this); - this.sys.email = new EmailSystem(this); - this.sys.reverseProxy = new ReverseProxySystem(this); - this.sys.terminalUI = new TerminalUISystem(this); - - this.status = InstanceStatus.Offline; - } - - async startup() { - this.log.system.info(`=======================================================================`); - this.log.system.info(` ${chalk.hex("FF002E")("/XXX/")}${chalk.hex("70FF00")("/XXX/")}${chalk.hex("0066FF")("/XXX/")}`); - this.log.system.info( - ` ${chalk.hex("FF002E")("/XXX/")}${chalk.hex("70FF00")("/XXX/")}${chalk.hex("0066FF")("/XXX/")} Online Workspace © 2026 Ewsgit -> https://ewsgit.uk`, - ); - this.log.system.info(` ${chalk.hex("FF002E")("/XXX/")}${chalk.hex("70FF00")("/XXX/")}${chalk.hex("0066FF")("/XXX/")}`); - this.log.system.info(`=======================================================================`); - this.log.system.info(`Starting up...`); - - if (this.status !== InstanceStatus.Offline) { - this.log.system.info("Cannot stop"); - return this; - } - - for (const sys of Object.values(this.sys)) { - const subSystemState = await sys.startup(); - - if (subSystemState) { - this.log.system.success(`System '${sys.id}' Startup Complete!`); - } else { - this.log.system.error(`System '${sys.id}' Startup Failed!`); - } - } - - this.sys.event.on(WorkspacesEvent.BeforeStartupComplete, () => { - this.sys.settings.registerApplicationSetting( - new StringListApplicationSetting("core", "quick_shortcuts", this.sys.configuration.defaultQuickShortcuts).setDisplayName("Quick Shortcuts"), - ); - }); - - this.sys.event.invoke(WorkspacesEvent.BeforeStartupComplete); - - // this.webServer = Deno.serve(route(, () => {}) - // // this.sys.tRPC.serve({ - // // routes: { - - // // }, - // // fetch() { - // // // will be executed if it's not a TRPC request - // // return new Response("Unknown path"); - // // }, - // // development: this.sys.configuration.isDevMode, - // // }), - // ); - - this.sys.tRPC.registeredRouters.push({ - basePath: "/api/trpc", - router: workspacesRouter, - createContext: createWorkspacesTRPCContext(this), - }); - - // this.log.system.success(`Listening for http requests on port ${this.webServer.port}`); - - this.log.system.info("Startup complete"); - this.status = InstanceStatus.Online; - - return this; - } - - async promptForRestart(reason: string): Promise { - this.log.system.warning(`Hey Server Admin, THE INSTANCE HAS BEEN PROMPTED FOR RESTART DUE TO '${reason}' please restart when possible.`); - return this; - } - - async shutdown() { - this.status = InstanceStatus.Stopping; - this.sys.consoleCommands.currentCommandInterface.active = true; - this.sys.consoleCommands.currentCommandInterface.cb = () => 0; - this.log.system.info("Shutting down..."); - - this.sys.event.invoke(WorkspacesEvent.BeforeShutdown); - this.status = InstanceStatus.Offline; - - if (process.stdout.cursorTo) { - process.stdout.cursorTo(0, 0); - process.stdout.clearScreenDown(); - process.stdout.cursorTo(0, 0); - } - - process.stdout.write("Shutdown complete!\n"); - process.exit(0); - } -} - -export type { Instance }; - -const INSTANCE = new Instance(); -export default INSTANCE; - -await INSTANCE.startup(); +import chalk from "chalk"; +// https://github.com/cah4a/trpc-bun-adapter/blob/main/src/createBunHttpHandler.ts TODO: patch this and merge into the instance package +import Log from "./log.ts"; +import type { Sys } from "./system.ts"; +import ApplicationsSystem from "./systems/applications.ts"; +import AuthorizationSystem from "./systems/authorization.ts"; +import ConfigurationSystem from "./systems/configuration.ts"; +import ConsoleCommandsSystem from "./systems/consoleCommands.ts"; +import DatabaseSystem from "./systems/database.ts"; +import EmailSystem from "./systems/email.ts"; +import EventSystem, { WorkspacesEvent } from "./systems/events.ts"; +import FilesystemSystem from "./systems/filesystem.ts"; +import ImageSystem from "./systems/image.ts"; +import NotificationsSystem from "./systems/notifications.ts"; +import ReverseProxySystem from "./systems/reverseProxy.ts"; +import { StringListApplicationSetting } from "./systems/settings/applicationSetting/stringListSetting.ts"; +import SettingsSystem from "./systems/settings.ts"; +import TerminalUISystem from "./systems/terminalUI.ts"; +import TRPCSystem from "./systems/trpc.ts"; +import { createTRPCContext as createWorkspacesTRPCContext, workspacesRouter } from "./systems/trpcRouter.ts"; +import UsersSystem from "./systems/users.ts"; +import WebFrontendSystem from "./systems/webFrontend.ts"; + +export enum InstanceStatus { + Online, + Offline, + StartingUp, + Stopping, +} + +class Instance { + sys: Sys; + log: Log; + webServer!: Deno.HttpServer; + status: InstanceStatus; + + constructor() { + this.log = new Log(this); + + // @ts-ignore Don't know, don't care + this.sys = {}; + + this.sys.event = new EventSystem(this); + this.sys.filesystem = new FilesystemSystem(this); + this.sys.configuration = new ConfigurationSystem(this); + this.sys.database = new DatabaseSystem(this); + this.sys.notifications = new NotificationsSystem(this); + this.sys.consoleCommands = new ConsoleCommandsSystem(this); + this.sys.users = new UsersSystem(this); + this.sys.authorization = new AuthorizationSystem(this); + this.sys.applications = new ApplicationsSystem(this); + this.sys.tRPC = new TRPCSystem(this); + this.sys.image = new ImageSystem(this); + this.sys.settings = new SettingsSystem(this); + this.sys.webFrontend = new WebFrontendSystem(this); + this.sys.email = new EmailSystem(this); + this.sys.reverseProxy = new ReverseProxySystem(this); + this.sys.terminalUI = new TerminalUISystem(this); + + this.status = InstanceStatus.Offline; + } + + async startup() { + this.log.system.info(`=======================================================================`); + this.log.system.info(` ${chalk.hex("FF002E")("/XXX/")}${chalk.hex("70FF00")("/XXX/")}${chalk.hex("0066FF")("/XXX/")}`); + this.log.system.info( + ` ${chalk.hex("FF002E")("/XXX/")}${chalk.hex("70FF00")("/XXX/")}${chalk.hex("0066FF")("/XXX/")} Online Workspace © 2026 Ewsgit -> https://ewsgit.uk`, + ); + this.log.system.info(` ${chalk.hex("FF002E")("/XXX/")}${chalk.hex("70FF00")("/XXX/")}${chalk.hex("0066FF")("/XXX/")}`); + this.log.system.info(`=======================================================================`); + this.log.system.info(`Starting up...`); + + if (this.status !== InstanceStatus.Offline) { + this.log.system.info("Cannot stop"); + return this; + } + + for (const sys of Object.values(this.sys)) { + const subSystemState = await sys.startup(); + + if (subSystemState) { + this.log.system.success(`System '${sys.id}' Startup Complete!`); + } else { + this.log.system.error(`System '${sys.id}' Startup Failed!`); + } + } + + this.sys.event.on(WorkspacesEvent.BeforeStartupComplete, () => { + this.sys.settings.registerApplicationSetting( + new StringListApplicationSetting("core", "quick_shortcuts", this.sys.configuration.defaultQuickShortcuts).setDisplayName("Quick Shortcuts"), + ); + }); + + this.sys.event.invoke(WorkspacesEvent.BeforeStartupComplete); + + // this.webServer = Deno.serve(route(, () => {}) + // // this.sys.tRPC.serve({ + // // routes: { + + // // }, + // // fetch() { + // // // will be executed if it's not a TRPC request + // // return new Response("Unknown path"); + // // }, + // // development: this.sys.configuration.isDevMode, + // // }), + // ); + + this.sys.tRPC.registeredRouters.push({ + basePath: "/api/trpc", + router: workspacesRouter, + createContext: createWorkspacesTRPCContext(this), + }); + + // this.log.system.success(`Listening for http requests on port ${this.webServer.port}`); + + this.log.system.info("Startup complete"); + this.status = InstanceStatus.Online; + + return this; + } + + async promptForRestart(reason: string): Promise { + this.log.system.warning(`Hey Server Admin, THE INSTANCE HAS BEEN PROMPTED FOR RESTART DUE TO '${reason}' please restart when possible.`); + return this; + } + + async shutdown() { + this.status = InstanceStatus.Stopping; + this.sys.consoleCommands.currentCommandInterface.active = true; + this.sys.consoleCommands.currentCommandInterface.cb = () => 0; + this.log.system.info("Shutting down..."); + + this.sys.event.invoke(WorkspacesEvent.BeforeShutdown); + this.status = InstanceStatus.Offline; + + if (process.stdout.cursorTo) { + process.stdout.cursorTo(0, 0); + process.stdout.clearScreenDown(); + process.stdout.cursorTo(0, 0); + } + + process.stdout.write("Shutdown complete!\n"); + process.exit(0); + } +} + +export type { Instance }; + +const INSTANCE = new Instance(); +export default INSTANCE; + +await INSTANCE.startup(); diff --git a/instance/src/log.ts b/instance/src/log.ts index 85775a5..b6aa29f 100644 --- a/instance/src/log.ts +++ b/instance/src/log.ts @@ -1,275 +1,275 @@ -import util from "node:util"; -import chalk from "chalk"; -import type { Instance } from "./index.ts"; -import { WorkspacesFeatureFlags } from "./systems/configuration.ts"; - -export enum LogType { - INFO, - WARNING, - ERROR, - SUCCESS, - DEBUG, - RAW, - PROMPT, -} - -class Logger { - logHistory: { - type: LogType; - level: string; - message: (string | Uint8Array)[]; - }[] = []; - private log: Log; - private level: string; - private isRootLogger: boolean; - - constructor(level: string, log: Log, isRootLogger: boolean = false) { - this.level = level; - this.log = log; - this.isRootLogger = isRootLogger; - - // biome-ignore lint/suspicious/noExplicitAny: data could be of any type - global.console.log = (...data: any[]): void => { - if (process.stdout.cursorTo) { - process.stdout.cursorTo(0, this._internal_getWindowSize()[1], () => { - process.stdout.clearLine(1, () => { - let writtenData = ""; - for (const d of data) { - if (d?.toString !== undefined) { - writtenData += util.format(d); - } else { - writtenData += util.inspect(d, { - compact: false, - colors: true, - depth: 3, - breakLength: this._internal_getWindowSize()[0] - this.log.META_LENGTH + 6, - }); - } - writtenData += " "; - } - if (writtenData.endsWith("\n")) { - process.stdout.write(writtenData, () => { - this._internal_writePrompt(); - }); - } else { - process.stdout.write(`${writtenData}\n`, () => { - this._internal_writePrompt(); - }); - } - }); - }); - } else { - let writtenData = ""; - for (const d of data) { - if (d.toString !== undefined) { - writtenData += util.format(d); - } else { - writtenData += util.inspect(d, { - compact: false, - colors: true, - depth: 3, - breakLength: this._internal_getWindowSize()[0] - this.log.META_LENGTH + 6, - }); - } - writtenData += " "; - } - if (writtenData.endsWith("\n")) { - process.stdout.write(writtenData); - } else { - process.stdout.write(`${writtenData}\n`); - } - } - }; - } - - emphasis(...message: (string | Uint8Array)[]) { - return chalk.bold.magenta(message); - } - - rawLog(...message: (string | Uint8Array)[]) { - if (message.length === 0) { - throw new Error("log message is empty"); - } - - return this.logMessage(LogType.RAW, ...message); - } - - // biome-ignore lint/suspicious/noExplicitAny: the message can be of any type - _internal_promptMessage(...message: any[]) { - return this.logMessage(LogType.PROMPT, ...message); - } - - removeCommandPrompt(cb: () => void) { - process.stdout.cursorTo(0, process.stdout.getWindowSize()[1] - 1, () => { - process.stdout.clearScreenDown(); - cb(); - }); - - return this; - } - - info(...message: (string | Uint8Array)[]) { - if (this.level.length === 0) { - throw new Error("log level is empty"); - } - - if (message.length === 0) { - throw new Error("log message is empty"); - } - - return this.logMessage(LogType.INFO, ...message); - } - - success(...message: (string | Uint8Array)[]) { - if (this.level.length === 0) { - throw new Error("log level is empty"); - } - - if (message.length === 0) { - throw new Error("log message is empty"); - } - - return this.logMessage(LogType.SUCCESS, ...message); - } - - warning(...message: (string | Uint8Array)[]) { - if (this.level.length === 0) { - throw new Error("log level is empty"); - } - - if (message.length === 0) { - throw new Error("log message is empty"); - } - - return this.logMessage(LogType.WARNING, ...message); - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - error(...message: any[]) { - if (message.length === 0) { - this.logMessage(LogType.ERROR, "log", new Error("log message is empty").stack); - } - - this.logMessage(LogType.ERROR, ...message); - - return this; - } - - debug(...message: (string | Uint8Array)[]) { - // if (!this.log.instance.configurationManager.config.isDevMode) { - // return this; - // } - - if (this.level.length === 0) { - throw new Error("log level is empty"); - } - - if (message.length === 0) { - throw new Error("log message is empty"); - } - - return this.logMessage(LogType.DEBUG, ...message); - } - - // biome-ignore lint/suspicious/noExplicitAny: the message can be of any type - private logMessage(type: LogType, ...message: any[]): this { - this.logHistory.push({ type: type, level: this.level, message: message }); - - let typeString = ""; - - switch (type) { - case LogType.INFO: - typeString = chalk.bold(`${chalk.blue("INF")} ${chalk.white("|")}`); - break; - case LogType.WARNING: - typeString = chalk.bold(`${chalk.yellow("WAR")} ${chalk.white("|")}`); - break; - case LogType.ERROR: - typeString = chalk.bold(`${chalk.red("ERR")} ${chalk.white("|")}`); - break; - case LogType.SUCCESS: - typeString = chalk.bold(`${chalk.green("SUC")} ${chalk.white("|")}`); - break; - case LogType.DEBUG: - typeString = chalk.bold(`${chalk.magenta("DBG")} ${chalk.white("|")}`); - break; - case LogType.PROMPT: - typeString = chalk.bold(`${chalk.cyan("PRM")} ${chalk.white("|")} `); - break; - case LogType.RAW: - typeString = ` `; - break; - } - - this.writeMessage(type, typeString, ...message); - - return this; - } - - _internal_getWindowSize(): [number, number] { - const size = process?.stdout?.getWindowSize?.(); - - return [size?.[0] || 120, size?.[1] || 60]; - } - - _internal_writePrompt() { - // if (!this.log.instance?.sys.configuration?.hasFeature(WorkspacesFeatureFlags.SlashCommands) || !process.stdout.cursorTo) return this; - // process.stdout.cursorTo(0, this._internal_getWindowSize()[1], () => { - // process.stdout.write(`Workspaces Alpha ${this.log.instance.sys.configuration?.isDevMode ? `[${this.emphasis("Dev Mode")}] ` : ""}`, () => { - // // move the cursor to the metaLen+6th column of the 2nd from the bottom row - // process.stdout.cursorTo(this.log.META_LENGTH + 6, this._internal_getWindowSize()[1], () => { - // // write the prompt indicator to the stdout - // process.stdout.write(`> ${this.log.instance.sys.consoleCommands?.rlInterface?.line || ""}`); - // }); - // }); - // }); - } - - private writeMessage(logType: LogType, typeString: string, ...message: any[]) { - // if (logType === LogType.RAW) { - // process.stdout.write( - // chalk.bold(`${typeString}${chalk.yellow(this.level.toUpperCase().slice(0, this.log.META_LENGTH).padEnd(this.log.META_LENGTH))} `) + message.join(" "), - // ); - // return this; - // } - // if (logType === LogType.PROMPT) { - // process.stdout.cursorTo(0, this._internal_getWindowSize()[1], () => { - // process.stdout.clearLine(1, () => { - // process.stdout.write( - // chalk.bold(`${typeString}${chalk.yellow(this.level.toUpperCase().slice(0, this.log.META_LENGTH).padEnd(this.log.META_LENGTH))} `) + - // message.join(" "), - // ); - // }); - // }); - // return this; - // } - // console.log(typeString, chalk.bold(`${chalk.yellow(this.level.toUpperCase().slice(0, this.log.META_LENGTH).padEnd(this.log.META_LENGTH))} `), ...message); - // return this; - } -} - -export type { Logger }; - -export default class Log { - allLogHistory: { - type: LogType; - level: string; - message: (string | Uint8Array)[]; - }[] = []; - system: Logger; - instance: Instance; - readonly META_LENGTH = 28; - - constructor(instance: Instance) { - this.instance = instance; - this.system = this.createLogger("system"); - } - - createLogger(prefix: string): Logger { - return new Logger(prefix, this); - } -} - -/* - * Prompt a message - */ +import util from "node:util"; +import chalk from "chalk"; +import type { Instance } from "./index.ts"; +import { WorkspacesFeatureFlags } from "./systems/configuration.ts"; + +export enum LogType { + INFO, + WARNING, + ERROR, + SUCCESS, + DEBUG, + RAW, + PROMPT, +} + +class Logger { + logHistory: { + type: LogType; + level: string; + message: (string | Uint8Array)[]; + }[] = []; + private log: Log; + private level: string; + private isRootLogger: boolean; + + constructor(level: string, log: Log, isRootLogger: boolean = false) { + this.level = level; + this.log = log; + this.isRootLogger = isRootLogger; + + // biome-ignore lint/suspicious/noExplicitAny: data could be of any type + global.console.log = (...data: any[]): void => { + if (process.stdout.cursorTo) { + process.stdout.cursorTo(0, this._internal_getWindowSize()[1], () => { + process.stdout.clearLine(1, () => { + let writtenData = ""; + for (const d of data) { + if (d?.toString !== undefined) { + writtenData += util.format(d); + } else { + writtenData += util.inspect(d, { + compact: false, + colors: true, + depth: 3, + breakLength: this._internal_getWindowSize()[0] - this.log.META_LENGTH + 6, + }); + } + writtenData += " "; + } + if (writtenData.endsWith("\n")) { + process.stdout.write(writtenData, () => { + this._internal_writePrompt(); + }); + } else { + process.stdout.write(`${writtenData}\n`, () => { + this._internal_writePrompt(); + }); + } + }); + }); + } else { + let writtenData = ""; + for (const d of data) { + if (d.toString !== undefined) { + writtenData += util.format(d); + } else { + writtenData += util.inspect(d, { + compact: false, + colors: true, + depth: 3, + breakLength: this._internal_getWindowSize()[0] - this.log.META_LENGTH + 6, + }); + } + writtenData += " "; + } + if (writtenData.endsWith("\n")) { + process.stdout.write(writtenData); + } else { + process.stdout.write(`${writtenData}\n`); + } + } + }; + } + + emphasis(...message: (string | Uint8Array)[]) { + return chalk.bold.magenta(message); + } + + rawLog(...message: (string | Uint8Array)[]) { + if (message.length === 0) { + throw new Error("log message is empty"); + } + + return this.logMessage(LogType.RAW, ...message); + } + + // biome-ignore lint/suspicious/noExplicitAny: the message can be of any type + _internal_promptMessage(...message: any[]) { + return this.logMessage(LogType.PROMPT, ...message); + } + + removeCommandPrompt(cb: () => void) { + process.stdout.cursorTo(0, process.stdout.getWindowSize()[1] - 1, () => { + process.stdout.clearScreenDown(); + cb(); + }); + + return this; + } + + info(...message: (string | Uint8Array)[]) { + if (this.level.length === 0) { + throw new Error("log level is empty"); + } + + if (message.length === 0) { + throw new Error("log message is empty"); + } + + return this.logMessage(LogType.INFO, ...message); + } + + success(...message: (string | Uint8Array)[]) { + if (this.level.length === 0) { + throw new Error("log level is empty"); + } + + if (message.length === 0) { + throw new Error("log message is empty"); + } + + return this.logMessage(LogType.SUCCESS, ...message); + } + + warning(...message: (string | Uint8Array)[]) { + if (this.level.length === 0) { + throw new Error("log level is empty"); + } + + if (message.length === 0) { + throw new Error("log message is empty"); + } + + return this.logMessage(LogType.WARNING, ...message); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error(...message: any[]) { + if (message.length === 0) { + this.logMessage(LogType.ERROR, "log", new Error("log message is empty").stack); + } + + this.logMessage(LogType.ERROR, ...message); + + return this; + } + + debug(...message: (string | Uint8Array)[]) { + // if (!this.log.instance.configurationManager.config.isDevMode) { + // return this; + // } + + if (this.level.length === 0) { + throw new Error("log level is empty"); + } + + if (message.length === 0) { + throw new Error("log message is empty"); + } + + return this.logMessage(LogType.DEBUG, ...message); + } + + // biome-ignore lint/suspicious/noExplicitAny: the message can be of any type + private logMessage(type: LogType, ...message: any[]): this { + this.logHistory.push({ type: type, level: this.level, message: message }); + + let typeString = ""; + + switch (type) { + case LogType.INFO: + typeString = chalk.bold(`${chalk.blue("INF")} ${chalk.white("|")}`); + break; + case LogType.WARNING: + typeString = chalk.bold(`${chalk.yellow("WAR")} ${chalk.white("|")}`); + break; + case LogType.ERROR: + typeString = chalk.bold(`${chalk.red("ERR")} ${chalk.white("|")}`); + break; + case LogType.SUCCESS: + typeString = chalk.bold(`${chalk.green("SUC")} ${chalk.white("|")}`); + break; + case LogType.DEBUG: + typeString = chalk.bold(`${chalk.magenta("DBG")} ${chalk.white("|")}`); + break; + case LogType.PROMPT: + typeString = chalk.bold(`${chalk.cyan("PRM")} ${chalk.white("|")} `); + break; + case LogType.RAW: + typeString = ` `; + break; + } + + this.writeMessage(type, typeString, ...message); + + return this; + } + + _internal_getWindowSize(): [number, number] { + const size = process?.stdout?.getWindowSize?.(); + + return [size?.[0] || 120, size?.[1] || 60]; + } + + _internal_writePrompt() { + // if (!this.log.instance?.sys.configuration?.hasFeature(WorkspacesFeatureFlags.SlashCommands) || !process.stdout.cursorTo) return this; + // process.stdout.cursorTo(0, this._internal_getWindowSize()[1], () => { + // process.stdout.write(`Workspaces Alpha ${this.log.instance.sys.configuration?.isDevMode ? `[${this.emphasis("Dev Mode")}] ` : ""}`, () => { + // // move the cursor to the metaLen+6th column of the 2nd from the bottom row + // process.stdout.cursorTo(this.log.META_LENGTH + 6, this._internal_getWindowSize()[1], () => { + // // write the prompt indicator to the stdout + // process.stdout.write(`> ${this.log.instance.sys.consoleCommands?.rlInterface?.line || ""}`); + // }); + // }); + // }); + } + + private writeMessage(logType: LogType, typeString: string, ...message: any[]) { + // if (logType === LogType.RAW) { + // process.stdout.write( + // chalk.bold(`${typeString}${chalk.yellow(this.level.toUpperCase().slice(0, this.log.META_LENGTH).padEnd(this.log.META_LENGTH))} `) + message.join(" "), + // ); + // return this; + // } + // if (logType === LogType.PROMPT) { + // process.stdout.cursorTo(0, this._internal_getWindowSize()[1], () => { + // process.stdout.clearLine(1, () => { + // process.stdout.write( + // chalk.bold(`${typeString}${chalk.yellow(this.level.toUpperCase().slice(0, this.log.META_LENGTH).padEnd(this.log.META_LENGTH))} `) + + // message.join(" "), + // ); + // }); + // }); + // return this; + // } + // console.log(typeString, chalk.bold(`${chalk.yellow(this.level.toUpperCase().slice(0, this.log.META_LENGTH).padEnd(this.log.META_LENGTH))} `), ...message); + // return this; + } +} + +export type { Logger }; + +export default class Log { + allLogHistory: { + type: LogType; + level: string; + message: (string | Uint8Array)[]; + }[] = []; + system: Logger; + instance: Instance; + readonly META_LENGTH = 28; + + constructor(instance: Instance) { + this.instance = instance; + this.system = this.createLogger("system"); + } + + createLogger(prefix: string): Logger { + return new Logger(prefix, this); + } +} + +/* + * Prompt a message + */ diff --git a/instance/src/system.ts b/instance/src/system.ts index 58da6cf..4a42dbd 100644 --- a/instance/src/system.ts +++ b/instance/src/system.ts @@ -1,59 +1,59 @@ -import type { Instance } from "./index.ts"; -import type { Logger } from "./log.ts"; -import type ApplicationsSubsystem from "./systems/applications.ts"; -import type AuthorizationSubsystem from "./systems/authorization.ts"; -import type ConfigurationSubsystem from "./systems/configuration.ts"; -import type ConsoleCommandsSubsystem from "./systems/consoleCommands.ts"; -import type DatabaseSubsystem from "./systems/database.ts"; -import type EmailSystem from "./systems/email.ts"; -import type EventSystem from "./systems/events.ts"; -import type FilesystemSubsystem from "./systems/filesystem.ts"; -import type ImageSubsystem from "./systems/image.ts"; -import type NotificationsSubsystem from "./systems/notifications.ts"; -import type ReverseProxySystem from "./systems/reverseProxy.ts"; -import type SettingsSubsystem from "./systems/settings.ts"; -import type TerminalUISystem from "./systems/terminalUI.ts"; -import type TRPCSubsystem from "./systems/trpc.ts"; -import type UsersSubsystem from "./systems/users.ts"; -import type WebFrontendSubsystem from "./systems/webFrontend.ts"; - -export type Sys = { - users: UsersSubsystem; - notifications: NotificationsSubsystem; - filesystem: FilesystemSubsystem; - configuration: ConfigurationSubsystem; - consoleCommands: ConsoleCommandsSubsystem; - authorization: AuthorizationSubsystem; - database: DatabaseSubsystem; - applications: ApplicationsSubsystem; - tRPC: TRPCSubsystem; - image: ImageSubsystem; - settings: SettingsSubsystem; - webFrontend: WebFrontendSubsystem; - email: EmailSystem; - event: EventSystem; - reverseProxy: ReverseProxySystem; - terminalUI: TerminalUISystem; -} & { [key: string]: System }; - -export default abstract class System { - instance: Instance; - readonly log: Logger; - readonly id: string; - - protected constructor(id: string, instance: Instance) { - this.instance = instance; - this.id = id; - this.log = instance.log.createLogger(this.id); - } - - async startup(): Promise { - this.log.info("Starting up..."); - return true; - } - - stop() { - this.log.info(`Stopping System ${this.id}`); - return this; - } -} +import type { Instance } from "./index.ts"; +import type { Logger } from "./log.ts"; +import type ApplicationsSubsystem from "./systems/applications.ts"; +import type AuthorizationSubsystem from "./systems/authorization.ts"; +import type ConfigurationSubsystem from "./systems/configuration.ts"; +import type ConsoleCommandsSubsystem from "./systems/consoleCommands.ts"; +import type DatabaseSubsystem from "./systems/database.ts"; +import type EmailSystem from "./systems/email.ts"; +import type EventSystem from "./systems/events.ts"; +import type FilesystemSubsystem from "./systems/filesystem.ts"; +import type ImageSubsystem from "./systems/image.ts"; +import type NotificationsSubsystem from "./systems/notifications.ts"; +import type ReverseProxySystem from "./systems/reverseProxy.ts"; +import type SettingsSubsystem from "./systems/settings.ts"; +import type TerminalUISystem from "./systems/terminalUI.ts"; +import type TRPCSubsystem from "./systems/trpc.ts"; +import type UsersSubsystem from "./systems/users.ts"; +import type WebFrontendSubsystem from "./systems/webFrontend.ts"; + +export type Sys = { + users: UsersSubsystem; + notifications: NotificationsSubsystem; + filesystem: FilesystemSubsystem; + configuration: ConfigurationSubsystem; + consoleCommands: ConsoleCommandsSubsystem; + authorization: AuthorizationSubsystem; + database: DatabaseSubsystem; + applications: ApplicationsSubsystem; + tRPC: TRPCSubsystem; + image: ImageSubsystem; + settings: SettingsSubsystem; + webFrontend: WebFrontendSubsystem; + email: EmailSystem; + event: EventSystem; + reverseProxy: ReverseProxySystem; + terminalUI: TerminalUISystem; +} & { [key: string]: System }; + +export default abstract class System { + instance: Instance; + readonly log: Logger; + readonly id: string; + + protected constructor(id: string, instance: Instance) { + this.instance = instance; + this.id = id; + this.log = instance.log.createLogger(this.id); + } + + async startup(): Promise { + this.log.info("Starting up..."); + return true; + } + + stop() { + this.log.info(`Stopping System ${this.id}`); + return this; + } +} diff --git a/instance/src/systems/api.ts b/instance/src/systems/api.ts index c862fb3..8c5c5ea 100644 --- a/instance/src/systems/api.ts +++ b/instance/src/systems/api.ts @@ -1,274 +1,274 @@ -import { serveFile } from "@std/http/file-server"; -import type { Route } from "@std/http/unstable-route"; -import * as path from "@std/path/posix"; -import nodeCanvas from "canvas"; -import type { Instance } from "../index.ts"; -import System from "../system.ts"; - -export default class ApiSystem extends System { - private routes: Route[]; - - constructor(instance: Instance) { - super("api", instance); - - // deno-lint-ignore no-this-alias - const self = this; - - this.routes = [ - { - method: ["GET"], - pattern: new URLPattern({ pathname: "/api/instance/login/banner" }), - handler(req) { - return serveFile(req, path.join(self.instance.sys.filesystem.FS_ROOT, "assets/login/banner.png")); - }, - }, - { - method: ["GET"], - pattern: new URLPattern({ pathname: "/api/instance/login/background" }), - handler(req) { - return serveFile(req, path.join(self.instance.sys.filesystem.FS_ROOT, "assets/login/background.png")); - }, - }, - { - method: ["GET"], - pattern: new URLPattern({ pathname: "/api/user/me/avatar/:size" }), - async handler(req, _, rawParams) { - // @ts-ignore this does exist - const params = rawParams?.pathname.groups; - - const size = params.size; - - const cookieString = req.headers?.get("cookie"); - - if (cookieString === null) { - return Response.json({ - code: "UNAUTHORIZED", - message: "missing auth cookie", - }); - } - - const parsedCookie = Bun.Cookie.parse(cookieString); - - const userId = await self.instance.sys.authorization.verifySession(decodeURIComponent(parsedCookie.value)); - - if (userId === undefined) { - return Response.json({ - code: "UNAUTHORIZED", - message: "invalid session", - }); - } - - switch (size) { - case "xs": - case "s": - case "m": - case "l": - case "xl": - case "2xl": - return serveFile(req, path.join(self.instance.sys.filesystem.FS_ROOT, `users/${userId}/assets/avatar/${size}.webp`)); - default: - return serveFile(req, path.join(self.instance.sys.filesystem.FS_ROOT, `users/${userId}/assets/avatar/xs.webp`)); - } - }, - }, - { - method: ["GET"], - pattern: new URLPattern({ pathname: "/api/application/:app/icon/" }), - async handler(req, _, rawParams) { - // @ts-ignore this does exist - const params = rawParams?.pathname.groups; - - const app = (params as { app: string }).app; - - const cookieString = req.headers?.get("cookie"); - - if (cookieString === null) { - self.log.warning("Missing auth cookie in request for application icon"); - - return Response.json({ - code: "UNAUTHORIZED", - message: "missing auth cookie", - }); - } - - const parsedCookie = Bun.Cookie.parse(cookieString); - - const userId = await self.instance.sys.authorization.verifySession(decodeURIComponent(parsedCookie.value)); - - if (userId === undefined) { - self.log.warning("Invalid session in request for application icon"); - - return Response.json({ - code: "UNAUTHORIZED", - message: "invalid session", - }); - } - - const application = self.instance.sys.applications.availableApplications.find((a) => a.manifest?.id === app); - - if (!application) - return Response.json({ - code: "INTERNAL_ERROR", - message: "Invalid application!", - }); - - const applicationIconPath = path.join(application.path, application.manifest?.icon?.value || ""); - - return serveFile(req, applicationIconPath); - }, - }, - { - method: ["GET"], - pattern: new URLPattern({ pathname: "/api/asset/image/:imageId/:resolution" }), - async handler(req, _, rawParams) { - // @ts-ignore this does exist - const params = rawParams?.pathname.groups; - - const image = self.instance.sys.image._internalImages.get(params.imageId as string); - - if (!image) { - return new Response("Invalid image"); - } - - if (!image.public) { - const cookieString = req.headers?.get("cookie"); - - if (cookieString === null) { - return Response.json({ - code: "UNAUTHORIZED", - message: "missing auth cookie", - }); - } - - const parsedCookie = Bun.Cookie.parse(cookieString); - - const userId = await self.instance.sys.authorization.verifySession(decodeURIComponent(parsedCookie.value)); - - if (userId === undefined) { - return Response.json({ - code: "UNAUTHORIZED", - message: "invalid session", - }); - } - } - - const resolutionParam = params.resolution as string; - - const sourceImage = image[resolutionParam]; - - if (!sourceImage) { - return Response.json({ - code: "NOT_FOUND", - message: "missing image", - }); - } - - if (resolutionParam === "raw") { - self.instance.sys.image.log.info(`Served Image -> '${(params as { imageId: string }).imageId} @ ${resolutionParam}'`); - return serveFile(req, sourceImage.path); - } - - return Response.json({ false: true }); - /* TODO: implement hashing again... else { - const cachedFilePath = path.join(self.instance.sys.filesystem.CACHE_PATH, sourceImage.path.replaceAll(":", "")); - const outputPath = path.join(cachedFilePath, resolutionParam); - const hashPath = path.join(`${outputPath}.hash`); - - if (fs.existsSync(outputPath)) { - const fileHash = Bun.hash.rapidhash(await Deno.readFile(sourceImage.path)).toString(); - const cacheFileHash = (await Deno.readFile(hashPath)).toString(); - - if (fileHash === cacheFileHash) { - self.instance.sys.image.log.info(`Served Image -> '${(params as { imageId: string }).imageId} @ ${resolutionParam}'`); - return serveFile(req, outputPath); - } - } - - if (!fs.existsSync(path.join(outputPath, ".."))) { - await fs.ensureDir(path.join(outputPath, "..")); - } - - const fileHash = Bun.hash.rapidhash(await Deno.readFile(sourceImage.path)).toString(); - await self.instance.sys.image.resizeImage(sourceImage.path, outputPath, sourceImage.resize!.dimensions, sourceImage.resize!); - await Deno.writeFile(hashPath, Buffer.from(fileHash)); - - self.instance.sys.image.log.info(`Served Image -> '${(params as { imageId: string }).imageId} @ ${resolutionParam}'`); - return serveFile(req, outputPath); - } */ - }, - }, - { - method: ["GET"], - pattern: new URLPattern({ pathname: "/api/asset/raw/:assetId" }), - async handler(req, _, rawParams) { - // @ts-ignore this does exist - const params = rawParams?.pathname.groups; - - const asset = self.instance.sys.filesystem._internalAssets.get(params.assetId as string); - - if (!asset) { - return new Response("Invalid raw asset"); - } - - if (!asset.public) { - const cookieString = req.headers?.get("cookie"); - - if (cookieString === null) { - return Response.json({ - code: "UNAUTHORIZED", - message: "missing auth cookie", - }); - } - - const parsedCookie = Bun.Cookie.parse(cookieString); - - const userId = await self.instance.sys.authorization.verifySession(decodeURIComponent(parsedCookie.value)); - - if (userId === undefined) { - return Response.json({ - code: "UNAUTHORIZED", - message: "invalid session", - }); - } - } - - return serveFile(req, asset.path); - }, - }, - { - method: ["GET"], - pattern: new URLPattern({ pathname: "/api/asset/fileicon/:filetype" }), - async handler(_req, _, rawParams) { - // @ts-ignore this does exist - const params = rawParams?.pathname.groups; - - const CANVAS_PADDING = 8; - const CANVAS_WIDTH = 128; - const CANVAS_HEIGHT = 128; - const canvas = nodeCanvas.createCanvas(CANVAS_WIDTH, CANVAS_HEIGHT); - const ctx = canvas.getContext("2d"); - ctx.drawImage(await nodeCanvas.loadImage(path.join(self.instance.sys.filesystem.SRC_ROOT, "assets/placeholder/file.png")), 0, 0); - - ctx.font = `20px Arial`; - ctx.textAlign = "end"; - ctx.textBaseline = "bottom"; - const LABEL_PADDING: { x: number; y: number } = { x: 4, y: 0 }; - const labelBr: { x: number; y: number } = { x: CANVAS_WIDTH - CANVAS_PADDING, y: CANVAS_HEIGHT - CANVAS_PADDING }; - const textContent = `${params.filetype.toUpperCase().slice(0, 3)}`; - const textSize = ctx.measureText(textContent); - ctx.fillStyle = "#00aa00"; - ctx.fillRect( - labelBr.x - (textSize.width + LABEL_PADDING.x * 2), - labelBr.y - (textSize.emHeightAscent + LABEL_PADDING.y * 2), - textSize.width + LABEL_PADDING.x * 2, - textSize.emHeightAscent + LABEL_PADDING.y * 2, - ); - ctx.fillStyle = "white"; - ctx.fillText(textContent, labelBr.x - LABEL_PADDING.x, labelBr.y + LABEL_PADDING.y); - - return new Response(canvas.createPNGStream()); - }, - }, - ]; - } -} +import { serveFile } from "@std/http/file-server"; +import type { Route } from "@std/http/unstable-route"; +import * as path from "@std/path/posix"; +import nodeCanvas from "canvas"; +import type { Instance } from "../index.ts"; +import System from "../system.ts"; + +export default class ApiSystem extends System { + private routes: Route[]; + + constructor(instance: Instance) { + super("api", instance); + + // deno-lint-ignore no-this-alias + const self = this; + + this.routes = [ + { + method: ["GET"], + pattern: new URLPattern({ pathname: "/api/instance/login/banner" }), + handler(req) { + return serveFile(req, path.join(self.instance.sys.filesystem.FS_ROOT, "assets/login/banner.png")); + }, + }, + { + method: ["GET"], + pattern: new URLPattern({ pathname: "/api/instance/login/background" }), + handler(req) { + return serveFile(req, path.join(self.instance.sys.filesystem.FS_ROOT, "assets/login/background.png")); + }, + }, + { + method: ["GET"], + pattern: new URLPattern({ pathname: "/api/user/me/avatar/:size" }), + async handler(req, _, rawParams) { + // @ts-ignore this does exist + const params = rawParams?.pathname.groups; + + const size = params.size; + + const cookieString = req.headers?.get("cookie"); + + if (cookieString === null) { + return Response.json({ + code: "UNAUTHORIZED", + message: "missing auth cookie", + }); + } + + const parsedCookie = Bun.Cookie.parse(cookieString); + + const userId = await self.instance.sys.authorization.verifySession(decodeURIComponent(parsedCookie.value)); + + if (userId === undefined) { + return Response.json({ + code: "UNAUTHORIZED", + message: "invalid session", + }); + } + + switch (size) { + case "xs": + case "s": + case "m": + case "l": + case "xl": + case "2xl": + return serveFile(req, path.join(self.instance.sys.filesystem.FS_ROOT, `users/${userId}/assets/avatar/${size}.webp`)); + default: + return serveFile(req, path.join(self.instance.sys.filesystem.FS_ROOT, `users/${userId}/assets/avatar/xs.webp`)); + } + }, + }, + { + method: ["GET"], + pattern: new URLPattern({ pathname: "/api/application/:app/icon/" }), + async handler(req, _, rawParams) { + // @ts-ignore this does exist + const params = rawParams?.pathname.groups; + + const app = (params as { app: string }).app; + + const cookieString = req.headers?.get("cookie"); + + if (cookieString === null) { + self.log.warning("Missing auth cookie in request for application icon"); + + return Response.json({ + code: "UNAUTHORIZED", + message: "missing auth cookie", + }); + } + + const parsedCookie = Bun.Cookie.parse(cookieString); + + const userId = await self.instance.sys.authorization.verifySession(decodeURIComponent(parsedCookie.value)); + + if (userId === undefined) { + self.log.warning("Invalid session in request for application icon"); + + return Response.json({ + code: "UNAUTHORIZED", + message: "invalid session", + }); + } + + const application = self.instance.sys.applications.availableApplications.find((a) => a.manifest?.id === app); + + if (!application) + return Response.json({ + code: "INTERNAL_ERROR", + message: "Invalid application!", + }); + + const applicationIconPath = path.join(application.path, application.manifest?.icon?.value || ""); + + return serveFile(req, applicationIconPath); + }, + }, + { + method: ["GET"], + pattern: new URLPattern({ pathname: "/api/asset/image/:imageId/:resolution" }), + async handler(req, _, rawParams) { + // @ts-ignore this does exist + const params = rawParams?.pathname.groups; + + const image = self.instance.sys.image._internalImages.get(params.imageId as string); + + if (!image) { + return new Response("Invalid image"); + } + + if (!image.public) { + const cookieString = req.headers?.get("cookie"); + + if (cookieString === null) { + return Response.json({ + code: "UNAUTHORIZED", + message: "missing auth cookie", + }); + } + + const parsedCookie = Bun.Cookie.parse(cookieString); + + const userId = await self.instance.sys.authorization.verifySession(decodeURIComponent(parsedCookie.value)); + + if (userId === undefined) { + return Response.json({ + code: "UNAUTHORIZED", + message: "invalid session", + }); + } + } + + const resolutionParam = params.resolution as string; + + const sourceImage = image[resolutionParam]; + + if (!sourceImage) { + return Response.json({ + code: "NOT_FOUND", + message: "missing image", + }); + } + + if (resolutionParam === "raw") { + self.instance.sys.image.log.info(`Served Image -> '${(params as { imageId: string }).imageId} @ ${resolutionParam}'`); + return serveFile(req, sourceImage.path); + } + + return Response.json({ false: true }); + /* TODO: implement hashing again... else { + const cachedFilePath = path.join(self.instance.sys.filesystem.CACHE_PATH, sourceImage.path.replaceAll(":", "")); + const outputPath = path.join(cachedFilePath, resolutionParam); + const hashPath = path.join(`${outputPath}.hash`); + + if (fs.existsSync(outputPath)) { + const fileHash = Bun.hash.rapidhash(await Deno.readFile(sourceImage.path)).toString(); + const cacheFileHash = (await Deno.readFile(hashPath)).toString(); + + if (fileHash === cacheFileHash) { + self.instance.sys.image.log.info(`Served Image -> '${(params as { imageId: string }).imageId} @ ${resolutionParam}'`); + return serveFile(req, outputPath); + } + } + + if (!fs.existsSync(path.join(outputPath, ".."))) { + await fs.ensureDir(path.join(outputPath, "..")); + } + + const fileHash = Bun.hash.rapidhash(await Deno.readFile(sourceImage.path)).toString(); + await self.instance.sys.image.resizeImage(sourceImage.path, outputPath, sourceImage.resize!.dimensions, sourceImage.resize!); + await Deno.writeFile(hashPath, Buffer.from(fileHash)); + + self.instance.sys.image.log.info(`Served Image -> '${(params as { imageId: string }).imageId} @ ${resolutionParam}'`); + return serveFile(req, outputPath); + } */ + }, + }, + { + method: ["GET"], + pattern: new URLPattern({ pathname: "/api/asset/raw/:assetId" }), + async handler(req, _, rawParams) { + // @ts-ignore this does exist + const params = rawParams?.pathname.groups; + + const asset = self.instance.sys.filesystem._internalAssets.get(params.assetId as string); + + if (!asset) { + return new Response("Invalid raw asset"); + } + + if (!asset.public) { + const cookieString = req.headers?.get("cookie"); + + if (cookieString === null) { + return Response.json({ + code: "UNAUTHORIZED", + message: "missing auth cookie", + }); + } + + const parsedCookie = Bun.Cookie.parse(cookieString); + + const userId = await self.instance.sys.authorization.verifySession(decodeURIComponent(parsedCookie.value)); + + if (userId === undefined) { + return Response.json({ + code: "UNAUTHORIZED", + message: "invalid session", + }); + } + } + + return serveFile(req, asset.path); + }, + }, + { + method: ["GET"], + pattern: new URLPattern({ pathname: "/api/asset/fileicon/:filetype" }), + async handler(_req, _, rawParams) { + // @ts-ignore this does exist + const params = rawParams?.pathname.groups; + + const CANVAS_PADDING = 8; + const CANVAS_WIDTH = 128; + const CANVAS_HEIGHT = 128; + const canvas = nodeCanvas.createCanvas(CANVAS_WIDTH, CANVAS_HEIGHT); + const ctx = canvas.getContext("2d"); + ctx.drawImage(await nodeCanvas.loadImage(path.join(self.instance.sys.filesystem.SRC_ROOT, "assets/placeholder/file.png")), 0, 0); + + ctx.font = `20px Arial`; + ctx.textAlign = "end"; + ctx.textBaseline = "bottom"; + const LABEL_PADDING: { x: number; y: number } = { x: 4, y: 0 }; + const labelBr: { x: number; y: number } = { x: CANVAS_WIDTH - CANVAS_PADDING, y: CANVAS_HEIGHT - CANVAS_PADDING }; + const textContent = `${params.filetype.toUpperCase().slice(0, 3)}`; + const textSize = ctx.measureText(textContent); + ctx.fillStyle = "#00aa00"; + ctx.fillRect( + labelBr.x - (textSize.width + LABEL_PADDING.x * 2), + labelBr.y - (textSize.emHeightAscent + LABEL_PADDING.y * 2), + textSize.width + LABEL_PADDING.x * 2, + textSize.emHeightAscent + LABEL_PADDING.y * 2, + ); + ctx.fillStyle = "white"; + ctx.fillText(textContent, labelBr.x - LABEL_PADDING.x, labelBr.y + LABEL_PADDING.y); + + return new Response(canvas.createPNGStream()); + }, + }, + ]; + } +} diff --git a/instance/src/systems/applications.ts b/instance/src/systems/applications.ts index ac65e4c..436f6d3 100644 --- a/instance/src/systems/applications.ts +++ b/instance/src/systems/applications.ts @@ -5,6 +5,7 @@ import System from "../system.ts"; import type { WorkspacesApplication } from "./applications/application.ts"; import type { WorkspacesApplicationServiceStatus } from "./applications/serviceStatus.ts"; import { WorkspacesNotificationPriority } from "./notifications.ts"; +import { Buffer } from "node:buffer"; const APPLICATIONS_CONFIG_FILE_PATH = (subsystem: System) => path.join(subsystem.instance.sys.filesystem.SYSTEM_PATH, "applications.json"); const APPLICATIONS_TSX_FILE_PATH = (subsystem: System) => path.join(subsystem.instance.sys.filesystem.SYSTEM_PATH, "vite", "Applications.tsx"); @@ -302,7 +303,7 @@ export default class ApplicationsSystem extends System { try { // @ts-ignore globalThis.instance = this.instance; - await import(path.join(app.path, app.manifest.modules.internal.path)); + await import(`file://${path.join(app.path, app.manifest.modules.internal.path)}`); } catch (err) { console.error("problem with application's bun module ->", err); } diff --git a/instance/src/systems/applications/application.ts b/instance/src/systems/applications/application.ts index d5bdb90..115ff60 100644 --- a/instance/src/systems/applications/application.ts +++ b/instance/src/systems/applications/application.ts @@ -1,29 +1,29 @@ -export interface WorkspacesApplication { - id: string; - // if undefined, just the id is used - displayName?: string; - icon?: { - type: "icon" | "image"; - value: string; - }; - description?: string; - authors: string[]; - license: string; - source?: string; - dependsOn?: { - applications: { - id: string; - repository?: string; - }[]; - }; - graphicsAcceleration?: string; - modules: { - // located at /app/[id]/ - web?: { path: string }; - // run bun ./[path.ts] - internal?: { path: string }; - // run ./[path] - external?: { path: string }; - }; - version?: string; -} +export interface WorkspacesApplication { + id: string; + // if undefined, just the id is used + displayName?: string; + icon?: { + type: "icon" | "image"; + value: string; + }; + description?: string; + authors: string[]; + license: string; + source?: string; + dependsOn?: { + applications: { + id: string; + repository?: string; + }[]; + }; + graphicsAcceleration?: string; + modules: { + // located at /app/[id]/ + web?: { path: string }; + // run bun ./[path.ts] + internal?: { path: string }; + // run ./[path] + external?: { path: string }; + }; + version?: string; +} diff --git a/instance/src/systems/applications/serviceStatus.ts b/instance/src/systems/applications/serviceStatus.ts index b54fd75..1037abf 100644 --- a/instance/src/systems/applications/serviceStatus.ts +++ b/instance/src/systems/applications/serviceStatus.ts @@ -1,4 +1,4 @@ -export interface WorkspacesApplicationServiceStatus { - service: "docker" | "web" | "bun"; - status: "online" | "warning" | "error" | "unknown" | "offline"; -} +export interface WorkspacesApplicationServiceStatus { + service: "docker" | "web" | "bun"; + status: "online" | "warning" | "error" | "unknown" | "offline"; +} diff --git a/instance/src/systems/authorization.ts b/instance/src/systems/authorization.ts index f3cf815..6bf20dd 100644 --- a/instance/src/systems/authorization.ts +++ b/instance/src/systems/authorization.ts @@ -1,443 +1,443 @@ -import utils from "node:util"; -import { - type AuthenticatorTransportFuture, - generateAuthenticationOptions, - generateRegistrationOptions, - type PublicKeyCredentialCreationOptionsJSON, - type PublicKeyCredentialRequestOptionsJSON, - verifyAuthenticationResponse, - verifyRegistrationResponse, -} from "@simplewebauthn/server"; -import * as OTPAuth from "otpauth"; -import type { Instance } from "../index.ts"; -import System from "../system.ts"; -import { WorkspacesNotificationPriority } from "./notifications.ts"; - -export enum AuthorizedDeviceType { - Desktop, - Mobile, - UnknownBrowser, -} - -// the number of ms that a login session is valid for -export const SESSION_VALID_TERM_MS = 7 * 24 * 60 * 60 * 1000; - -export default class AuthorizationSystem extends System { - private temporaryPasskeyCreationChallenges: Map; - private temporaryPasskeyAuthenticationChallenges: Map; - - constructor(instance: Instance) { - super("authorization", instance); - - this.temporaryPasskeyCreationChallenges = new Map(); - this.temporaryPasskeyAuthenticationChallenges = new Map(); - } - - // Creates a new session for a user - // @returns {string} the new session's sessionToken - async createPasswordSession( - userId: number, - password: string, - deviceId: AuthorizedDeviceType, - otpCode?: string, - ipAddress?: string, - ): Promise { - try { - const db = this.instance.sys.database.postgres(); - - if (!(await Bun.password.verify(password, (await db`SELECT hashed_password FROM public.users WHERE id = ${userId}`)?.[0]?.hashed_password))) { - return undefined; - } - - if (await this.instance.sys.authorization.hasTwoFactorAuthenticationSecret(userId)) { - if (!otpCode) { - console.log("no otp code provided when creating session?"); - return undefined; - } - - const totp = new OTPAuth.TOTP({ - issuer: this.instance.sys.configuration.proxyUrl, - label: `${this.instance.sys.configuration.displayName} (Workspace)`, - algorithm: "SHA1", - digits: 6, - secret: (await db`SELECT two_factor_secret FROM public.users WHERE id = ${userId}`)?.[0]?.two_factor_secret, - }); - - if (totp.validate({ token: otpCode }) === null) { - return undefined; - } - } - - const sessionToken = crypto.getRandomValues(new Uint32Array(16)).join(""); - - await db`INSERT INTO public.sessions (user_id, session_token, device_type, valid_until, ip_address, login_method) VALUES (${userId}, ${sessionToken}, ${deviceId}, ${Date.now() + SESSION_VALID_TERM_MS}, ${ipAddress || "Anonymous"}, 'password authentication')`; - - const user = await this.instance.sys.users.getUserById(userId); - - if (await user?.isAdministrator()) { - if (password === "password") { - this.log.warning(`User (${userId})${await user?.getUsername()} has the default password! Please tell them to change it!`); - - setTimeout(() => { - this.instance.sys.notifications.send( - userId, - "authorization.createSession", - WorkspacesNotificationPriority.Urgent, - { - title: "Change Your Password", - icon: "key", - body: "Please change your password from the default!", - }, - { - buttons: [ - { - id: "change-password", - label: "Change Password", - type: "filled", - }, - ], - }, - { - onButton(_id) { - return { - action: { - type: "navigate", - value: "/app/uk.ewsgit.settings/authentication/reset-password", - }, - }; - }, - }, - ); - }, 5000); - } - } - - return `workspaces_session:${userId}:${sessionToken}`; - } catch (err) { - this.log.warning(`Failed to create session. -> ${userId} @ ${AuthorizedDeviceType[deviceId]}`, utils.inspect(err)); - - return undefined; - } - } - - /** - Verifies that a sessionToken exists and is valid - @returns {number} the userId of the session - @returns {undefined} the session is invalid - */ - async verifySession(sessionToken: string): Promise { - const [_, userId, token] = sessionToken.split(":"); - - const sessionsDb = this.instance.sys.database.postgres(); - - const session = (await sessionsDb`SELECT session_id, valid_until FROM public.sessions WHERE user_id = ${userId} AND session_token = ${token}`)?.[0]; - - if (Number(session?.valid_until) < Date.now()) { - await sessionsDb`DELETE FROM public.sessions WHERE user_id = ${userId} AND session_token = ${token}`; - return undefined; - } - - if (session?.session_id !== undefined) return Number(userId); - - return undefined; - } - - // Removes a user's session and invalidates it's token - // @returns {true} the session is removed, and it's token is invalidated - // @returns {undefined} the sessionToken is invalid - async endSessionByToken(sessionToken: string): Promise { - const [_, userId, token] = sessionToken.split(":"); - - const sessionsDb = this.instance.sys.database.postgres(); - - await sessionsDb`DELETE FROM public.sessions WHERE user_id = ${userId} AND session_token = ${token}`; - - return true; - } - - // Removes a user's session and invalidates it's token - // @returns {true} the session is removed, and it's token is invalidated - // @returns {undefined} the sessionToken is invalid - async endSessionById(userId: number, sessionId: number): Promise { - const sessionsDb = this.instance.sys.database.postgres(); - - await sessionsDb`DELETE FROM public.sessions WHERE user_id = ${userId} AND session_id = ${sessionId}`; - - return true; - } - - // Sets a user's password to password - // @returns {true} successful - // @returns {false} failed - async setPassword(userId: number, password: string): Promise { - const db = this.instance.sys.database.postgres(); - - if (!(await this.instance.sys.users.doesUserExist(userId))) { - return false; - } - - const hashedPassword = await Bun.password.hash(password); - - await db`UPDATE public.users SET hashed_password = ${hashedPassword} WHERE id = ${userId}`; - - return true; - } - - // Returns whether a user has a password set or not - // @returns {true} if they have a password - // @returns {false} if they lack a password - async hasPassword(userId: number) { - const db = this.instance.sys.database.postgres(); - - if (!(await this.instance.sys.users.doesUserExist(userId))) { - return false; - } - - const [{ exists }] = await db` - SELECT (hashed_password IS NOT NULL) as exists - FROM public.users - WHERE id = ${userId} - `; - - return !!exists; - } - - // Sets a user's two-factor authentication secret - // @returns {true} successful - // @returns {false} failed - async setTwoFactorAuthenticationSecret(userId: number, secret: string) { - const db = this.instance.sys.database.postgres(); - - if (!(await this.instance.sys.users.doesUserExist(userId))) { - return false; - } - - try { - await db`UPDATE public.users SET two_factor_secret = ${secret} WHERE id = ${userId}`; - } catch (_) { - return false; - } - - return true; - } - - // Returns whether a user has a two-factor authentication secret or not - // @returns {true} if they have a factor authentication secret - // @returns {false} if they lack a factor authentication secret - async hasTwoFactorAuthenticationSecret(userId: number) { - const db = this.instance.sys.database.postgres(); - - if (!(await this.instance.sys.users.doesUserExist(userId))) { - return false; - } - - const [{ exists }] = await db` - SELECT (two_factor_secret IS NOT NULL) as exists - FROM public.users - WHERE id = ${userId} - `; - - return !!exists; - } - - // Returns whether a user has a passkey or not - // @returns {true} if they have a passkey - // @returns {false} if they lack a passkey - async hasPasskey(userId: number) { - const db = this.instance.sys.database.postgres(); - - if (!(await this.instance.sys.users.doesUserExist(userId))) { - return false; - } - - const userPasskeys = await db`SELECT COUNT(*) FROM public.passkeys WHERE user_id = ${userId}`; - - return Number(userPasskeys[0].count) > 0; - } - - async requestNewPasskey(userId: number) { - const db = this.instance.sys.database.postgres(); - - const userPasskeys = await db`SELECT * FROM public.passkeys WHERE user_id = ${userId}`; - - const passkeyCreationOptions: PublicKeyCredentialCreationOptionsJSON = await generateRegistrationOptions({ - rpName: this.instance.sys.configuration.displayName, - rpID: this.instance.sys.configuration.proxyUrl.replace("https://", ""), - userName: (await (await this.instance.sys.users.getUserById(userId))?.getUsername()) || `${userId}`, - excludeCredentials: userPasskeys.map((passkey: { passkey_id: string; transports: string }) => { - return { - id: passkey.passkey_id, - transports: passkey.transports.split(",") as AuthenticatorTransportFuture[], - }; - }), - authenticatorSelection: { - residentKey: "preferred", - userVerification: "preferred", - authenticatorAttachment: "platform", - }, - }); - - this.temporaryPasskeyCreationChallenges.set(userId, passkeyCreationOptions); - - return passkeyCreationOptions; - } - - // biome-ignore lint/suspicious/noExplicitAny: the input is a webauthn response which is very complex and would require a lot of work to type, so we'll just use any here as it is handled by a library and we don't need to worry about the types - async registerPasskey(userId: number, input: any) { - const db = this.instance.sys.database.postgres(); - const expectedChallenge = this.temporaryPasskeyCreationChallenges.get(userId); - if (!expectedChallenge) { - return false; - } - - const verification = await verifyRegistrationResponse({ - response: input, - expectedChallenge: expectedChallenge.challenge, - expectedOrigin: this.instance.sys.configuration.proxyUrl, - expectedRPID: this.instance.sys.configuration.proxyUrl.replace("https://", ""), - }); - - const registrationInfo = verification.registrationInfo!; - const credential = registrationInfo?.credential; - - await db`INSERT INTO public.passkeys ( - passkey_id, - public_key, - user_id, - webauthn_user_id, - counter, - device_type, - backed_up, - transports - ) VALUES ( - ${credential.id}, - ${credential.publicKey}, - ${userId}, - ${expectedChallenge.user.id}, - ${credential.counter}, - ${registrationInfo.credentialDeviceType}, - ${registrationInfo.credentialBackedUp}, - ${credential.transports} - )`; - - this.temporaryPasskeyCreationChallenges.delete(userId); - - return verification.verified; - } - - async requestPasskeySession(userId: number) { - const db = this.instance.sys.database.postgres(); - const userPasskeys = await db`SELECT * FROM public.passkeys WHERE user_id = ${userId}`; - - const passkeyOptions: PublicKeyCredentialRequestOptionsJSON = await generateAuthenticationOptions({ - rpID: this.instance.sys.configuration.proxyUrl.replace("https://", ""), - allowCredentials: userPasskeys.map((passkey: { passkey_id: string; transports: string }) => { - return { - id: passkey.passkey_id, - transports: passkey.transports.split(",") as AuthenticatorTransportFuture[], - }; - }), - }); - - this.temporaryPasskeyAuthenticationChallenges.set(userId, passkeyOptions); - - return passkeyOptions; - } - - // biome-ignore lint/suspicious/noExplicitAny: the input is a webauthn response which is very complex and would require a lot of work to type, so we'll just use any here as it is handled by a library and we don't need to worry about the types - async createPasskeySession(userId: number, deviceId: AuthorizedDeviceType, input: any, ipAddress?: string) { - const db = this.instance.sys.database.postgres(); - const expectedChallenge = this.temporaryPasskeyAuthenticationChallenges.get(userId); - if (!expectedChallenge) { - return undefined; - } - - const passkey = (await db`SELECT * FROM public.passkeys WHERE user_id = ${userId} AND passkey_id = ${input.id}`)?.[0]; - if (!passkey) { - return undefined; - } - - const verification = await verifyAuthenticationResponse({ - response: input, - expectedChallenge: expectedChallenge.challenge, - expectedOrigin: this.instance.sys.configuration.proxyUrl, - expectedRPID: this.instance.sys.configuration.proxyUrl.replace("https://", ""), - credential: { - id: passkey.id, - publicKey: passkey.public_key, - counter: passkey.counter, - transports: passkey.transports.split(",") as AuthenticatorTransportFuture[], - }, - }); - - if (verification.verified) { - const sessionToken = crypto.getRandomValues(new Uint32Array(16)).join(""); - - await db`INSERT INTO public.sessions (user_id, session_token, device_type, valid_until, ip_address, login_method) VALUES (${userId}, ${sessionToken}, ${deviceId}, ${Date.now() + SESSION_VALID_TERM_MS}, ${ipAddress || "Anonymous"}, 'passkey')`; - await db`UPDATE public.passkeys SET last_used_timestamp = NOW(), counter = ${passkey.counter + 1} WHERE passkey_id = ${passkey.passkey_id}`; - - return `workspaces_session:${userId}:${sessionToken}`; - } - - return undefined; - } - - removePasskey(userId: number, passkeyId: string) { - const db = this.instance.sys.database.postgres(); - - return db`DELETE FROM public.passkeys WHERE user_id = ${userId} AND passkey_id = ${passkeyId}`; - } - - override async startup() { - // loop through all users, check for any session tokens which are expired and remove them from the user's valid sessions pool - - const db = this.instance.sys.database.postgres(); - - // init the sessions database - // - // session_id - the id of the session (number) - // user_id - the id of the user (number) - // session_token - the session's access token in the format 'workspaces_session:[user_id]:[token]' (string) - // device_type - the session's device type (AuthorizedDeviceType) - // valid_until - the epoch time which when reached, the session will be invalid (number) - // ip_address - the ip address of the session (string) - // login_method - the authentication method used to log in (string) - await db`CREATE TABLE IF NOT EXISTS Sessions ( - session_id SERIAL PRIMARY KEY, - user_id INTEGER, - session_token TEXT, - device_type INTEGER, - valid_until BIGINT, - ip_address TEXT DEFAULT 'Anonymous', - login_method TEXT, - FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE - )`; - - // init the passkeys database - // passkey_id - the id of the passkey (Base64URLString) - // public_key - the passkey's public key (Uint8Array) - // user_id - the id of the user who owns the passkey (number) - // webauthn_user_id - the webauthn user id associated with the passkey (string) - // counter - the passkey's counter for preventing replay attacks (number) - // device_type - the type of device the passkey is used on (CredentialDeviceType) - // backed_up - whether the passkey has been backed up or not (boolean) - // transports - the transports supported by the passkey (string array stored as a CSV string -> AuthenticatorTransportFuture[]) - // creation_timestamp - the timestamp of when the passkey was created (Date) - // last_used_timestamp - the timestamp of when the passkey was last used (Date) - await db`CREATE TABLE IF NOT EXISTS Passkeys ( - passkey_id TEXT PRIMARY KEY, - public_key BYTEA, - user_id INTEGER, - webauthn_user_id TEXT, - counter BIGINT, - device_type VARCHAR(32), - backed_up BOOLEAN DEFAULT FALSE, - transports VARCHAR(255), - creation_timetamp TIMESTAMPTZ DEFAULT NOW(), - last_used_timestamp TIMESTAMPTZ DEFAULT NOW(), - FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE - )`; - - return true; - } -} +import utils from "node:util"; +import { + type AuthenticatorTransportFuture, + generateAuthenticationOptions, + generateRegistrationOptions, + type PublicKeyCredentialCreationOptionsJSON, + type PublicKeyCredentialRequestOptionsJSON, + verifyAuthenticationResponse, + verifyRegistrationResponse, +} from "@simplewebauthn/server"; +import * as OTPAuth from "otpauth"; +import type { Instance } from "../index.ts"; +import System from "../system.ts"; +import { WorkspacesNotificationPriority } from "./notifications.ts"; + +export enum AuthorizedDeviceType { + Desktop, + Mobile, + UnknownBrowser, +} + +// the number of ms that a login session is valid for +export const SESSION_VALID_TERM_MS = 7 * 24 * 60 * 60 * 1000; + +export default class AuthorizationSystem extends System { + private temporaryPasskeyCreationChallenges: Map; + private temporaryPasskeyAuthenticationChallenges: Map; + + constructor(instance: Instance) { + super("authorization", instance); + + this.temporaryPasskeyCreationChallenges = new Map(); + this.temporaryPasskeyAuthenticationChallenges = new Map(); + } + + // Creates a new session for a user + // @returns {string} the new session's sessionToken + async createPasswordSession( + userId: number, + password: string, + deviceId: AuthorizedDeviceType, + otpCode?: string, + ipAddress?: string, + ): Promise { + try { + const db = this.instance.sys.database.postgres(); + + if (!(await Bun.password.verify(password, (await db`SELECT hashed_password FROM public.users WHERE id = ${userId}`)?.[0]?.hashed_password))) { + return undefined; + } + + if (await this.instance.sys.authorization.hasTwoFactorAuthenticationSecret(userId)) { + if (!otpCode) { + console.log("no otp code provided when creating session?"); + return undefined; + } + + const totp = new OTPAuth.TOTP({ + issuer: this.instance.sys.configuration.proxyUrl, + label: `${this.instance.sys.configuration.displayName} (Workspace)`, + algorithm: "SHA1", + digits: 6, + secret: (await db`SELECT two_factor_secret FROM public.users WHERE id = ${userId}`)?.[0]?.two_factor_secret, + }); + + if (totp.validate({ token: otpCode }) === null) { + return undefined; + } + } + + const sessionToken = crypto.getRandomValues(new Uint32Array(16)).join(""); + + await db`INSERT INTO public.sessions (user_id, session_token, device_type, valid_until, ip_address, login_method) VALUES (${userId}, ${sessionToken}, ${deviceId}, ${Date.now() + SESSION_VALID_TERM_MS}, ${ipAddress || "Anonymous"}, 'password authentication')`; + + const user = await this.instance.sys.users.getUserById(userId); + + if (await user?.isAdministrator()) { + if (password === "password") { + this.log.warning(`User (${userId})${await user?.getUsername()} has the default password! Please tell them to change it!`); + + setTimeout(() => { + this.instance.sys.notifications.send( + userId, + "authorization.createSession", + WorkspacesNotificationPriority.Urgent, + { + title: "Change Your Password", + icon: "key", + body: "Please change your password from the default!", + }, + { + buttons: [ + { + id: "change-password", + label: "Change Password", + type: "filled", + }, + ], + }, + { + onButton(_id) { + return { + action: { + type: "navigate", + value: "/app/uk.ewsgit.settings/authentication/reset-password", + }, + }; + }, + }, + ); + }, 5000); + } + } + + return `workspaces_session:${userId}:${sessionToken}`; + } catch (err) { + this.log.warning(`Failed to create session. -> ${userId} @ ${AuthorizedDeviceType[deviceId]}`, utils.inspect(err)); + + return undefined; + } + } + + /** + Verifies that a sessionToken exists and is valid + @returns {number} the userId of the session + @returns {undefined} the session is invalid + */ + async verifySession(sessionToken: string): Promise { + const [_, userId, token] = sessionToken.split(":"); + + const sessionsDb = this.instance.sys.database.postgres(); + + const session = (await sessionsDb`SELECT session_id, valid_until FROM public.sessions WHERE user_id = ${userId} AND session_token = ${token}`)?.[0]; + + if (Number(session?.valid_until) < Date.now()) { + await sessionsDb`DELETE FROM public.sessions WHERE user_id = ${userId} AND session_token = ${token}`; + return undefined; + } + + if (session?.session_id !== undefined) return Number(userId); + + return undefined; + } + + // Removes a user's session and invalidates it's token + // @returns {true} the session is removed, and it's token is invalidated + // @returns {undefined} the sessionToken is invalid + async endSessionByToken(sessionToken: string): Promise { + const [_, userId, token] = sessionToken.split(":"); + + const sessionsDb = this.instance.sys.database.postgres(); + + await sessionsDb`DELETE FROM public.sessions WHERE user_id = ${userId} AND session_token = ${token}`; + + return true; + } + + // Removes a user's session and invalidates it's token + // @returns {true} the session is removed, and it's token is invalidated + // @returns {undefined} the sessionToken is invalid + async endSessionById(userId: number, sessionId: number): Promise { + const sessionsDb = this.instance.sys.database.postgres(); + + await sessionsDb`DELETE FROM public.sessions WHERE user_id = ${userId} AND session_id = ${sessionId}`; + + return true; + } + + // Sets a user's password to password + // @returns {true} successful + // @returns {false} failed + async setPassword(userId: number, password: string): Promise { + const db = this.instance.sys.database.postgres(); + + if (!(await this.instance.sys.users.doesUserExist(userId))) { + return false; + } + + const hashedPassword = await Bun.password.hash(password); + + await db`UPDATE public.users SET hashed_password = ${hashedPassword} WHERE id = ${userId}`; + + return true; + } + + // Returns whether a user has a password set or not + // @returns {true} if they have a password + // @returns {false} if they lack a password + async hasPassword(userId: number) { + const db = this.instance.sys.database.postgres(); + + if (!(await this.instance.sys.users.doesUserExist(userId))) { + return false; + } + + const [{ exists }] = await db` + SELECT (hashed_password IS NOT NULL) as exists + FROM public.users + WHERE id = ${userId} + `; + + return !!exists; + } + + // Sets a user's two-factor authentication secret + // @returns {true} successful + // @returns {false} failed + async setTwoFactorAuthenticationSecret(userId: number, secret: string) { + const db = this.instance.sys.database.postgres(); + + if (!(await this.instance.sys.users.doesUserExist(userId))) { + return false; + } + + try { + await db`UPDATE public.users SET two_factor_secret = ${secret} WHERE id = ${userId}`; + } catch (_) { + return false; + } + + return true; + } + + // Returns whether a user has a two-factor authentication secret or not + // @returns {true} if they have a factor authentication secret + // @returns {false} if they lack a factor authentication secret + async hasTwoFactorAuthenticationSecret(userId: number) { + const db = this.instance.sys.database.postgres(); + + if (!(await this.instance.sys.users.doesUserExist(userId))) { + return false; + } + + const [{ exists }] = await db` + SELECT (two_factor_secret IS NOT NULL) as exists + FROM public.users + WHERE id = ${userId} + `; + + return !!exists; + } + + // Returns whether a user has a passkey or not + // @returns {true} if they have a passkey + // @returns {false} if they lack a passkey + async hasPasskey(userId: number) { + const db = this.instance.sys.database.postgres(); + + if (!(await this.instance.sys.users.doesUserExist(userId))) { + return false; + } + + const userPasskeys = await db`SELECT COUNT(*) FROM public.passkeys WHERE user_id = ${userId}`; + + return Number(userPasskeys[0].count) > 0; + } + + async requestNewPasskey(userId: number) { + const db = this.instance.sys.database.postgres(); + + const userPasskeys = await db`SELECT * FROM public.passkeys WHERE user_id = ${userId}`; + + const passkeyCreationOptions: PublicKeyCredentialCreationOptionsJSON = await generateRegistrationOptions({ + rpName: this.instance.sys.configuration.displayName, + rpID: this.instance.sys.configuration.proxyUrl.replace("https://", ""), + userName: (await (await this.instance.sys.users.getUserById(userId))?.getUsername()) || `${userId}`, + excludeCredentials: userPasskeys.map((passkey: { passkey_id: string; transports: string }) => { + return { + id: passkey.passkey_id, + transports: passkey.transports.split(",") as AuthenticatorTransportFuture[], + }; + }), + authenticatorSelection: { + residentKey: "preferred", + userVerification: "preferred", + authenticatorAttachment: "platform", + }, + }); + + this.temporaryPasskeyCreationChallenges.set(userId, passkeyCreationOptions); + + return passkeyCreationOptions; + } + + // biome-ignore lint/suspicious/noExplicitAny: the input is a webauthn response which is very complex and would require a lot of work to type, so we'll just use any here as it is handled by a library and we don't need to worry about the types + async registerPasskey(userId: number, input: any) { + const db = this.instance.sys.database.postgres(); + const expectedChallenge = this.temporaryPasskeyCreationChallenges.get(userId); + if (!expectedChallenge) { + return false; + } + + const verification = await verifyRegistrationResponse({ + response: input, + expectedChallenge: expectedChallenge.challenge, + expectedOrigin: this.instance.sys.configuration.proxyUrl, + expectedRPID: this.instance.sys.configuration.proxyUrl.replace("https://", ""), + }); + + const registrationInfo = verification.registrationInfo!; + const credential = registrationInfo?.credential; + + await db`INSERT INTO public.passkeys ( + passkey_id, + public_key, + user_id, + webauthn_user_id, + counter, + device_type, + backed_up, + transports + ) VALUES ( + ${credential.id}, + ${credential.publicKey}, + ${userId}, + ${expectedChallenge.user.id}, + ${credential.counter}, + ${registrationInfo.credentialDeviceType}, + ${registrationInfo.credentialBackedUp}, + ${credential.transports} + )`; + + this.temporaryPasskeyCreationChallenges.delete(userId); + + return verification.verified; + } + + async requestPasskeySession(userId: number) { + const db = this.instance.sys.database.postgres(); + const userPasskeys = await db`SELECT * FROM public.passkeys WHERE user_id = ${userId}`; + + const passkeyOptions: PublicKeyCredentialRequestOptionsJSON = await generateAuthenticationOptions({ + rpID: this.instance.sys.configuration.proxyUrl.replace("https://", ""), + allowCredentials: userPasskeys.map((passkey: { passkey_id: string; transports: string }) => { + return { + id: passkey.passkey_id, + transports: passkey.transports.split(",") as AuthenticatorTransportFuture[], + }; + }), + }); + + this.temporaryPasskeyAuthenticationChallenges.set(userId, passkeyOptions); + + return passkeyOptions; + } + + // biome-ignore lint/suspicious/noExplicitAny: the input is a webauthn response which is very complex and would require a lot of work to type, so we'll just use any here as it is handled by a library and we don't need to worry about the types + async createPasskeySession(userId: number, deviceId: AuthorizedDeviceType, input: any, ipAddress?: string) { + const db = this.instance.sys.database.postgres(); + const expectedChallenge = this.temporaryPasskeyAuthenticationChallenges.get(userId); + if (!expectedChallenge) { + return undefined; + } + + const passkey = (await db`SELECT * FROM public.passkeys WHERE user_id = ${userId} AND passkey_id = ${input.id}`)?.[0]; + if (!passkey) { + return undefined; + } + + const verification = await verifyAuthenticationResponse({ + response: input, + expectedChallenge: expectedChallenge.challenge, + expectedOrigin: this.instance.sys.configuration.proxyUrl, + expectedRPID: this.instance.sys.configuration.proxyUrl.replace("https://", ""), + credential: { + id: passkey.id, + publicKey: passkey.public_key, + counter: passkey.counter, + transports: passkey.transports.split(",") as AuthenticatorTransportFuture[], + }, + }); + + if (verification.verified) { + const sessionToken = crypto.getRandomValues(new Uint32Array(16)).join(""); + + await db`INSERT INTO public.sessions (user_id, session_token, device_type, valid_until, ip_address, login_method) VALUES (${userId}, ${sessionToken}, ${deviceId}, ${Date.now() + SESSION_VALID_TERM_MS}, ${ipAddress || "Anonymous"}, 'passkey')`; + await db`UPDATE public.passkeys SET last_used_timestamp = NOW(), counter = ${passkey.counter + 1} WHERE passkey_id = ${passkey.passkey_id}`; + + return `workspaces_session:${userId}:${sessionToken}`; + } + + return undefined; + } + + removePasskey(userId: number, passkeyId: string) { + const db = this.instance.sys.database.postgres(); + + return db`DELETE FROM public.passkeys WHERE user_id = ${userId} AND passkey_id = ${passkeyId}`; + } + + override async startup() { + // loop through all users, check for any session tokens which are expired and remove them from the user's valid sessions pool + + const db = this.instance.sys.database.postgres(); + + // init the sessions database + // + // session_id - the id of the session (number) + // user_id - the id of the user (number) + // session_token - the session's access token in the format 'workspaces_session:[user_id]:[token]' (string) + // device_type - the session's device type (AuthorizedDeviceType) + // valid_until - the epoch time which when reached, the session will be invalid (number) + // ip_address - the ip address of the session (string) + // login_method - the authentication method used to log in (string) + await db`CREATE TABLE IF NOT EXISTS Sessions ( + session_id SERIAL PRIMARY KEY, + user_id INTEGER, + session_token TEXT, + device_type INTEGER, + valid_until BIGINT, + ip_address TEXT DEFAULT 'Anonymous', + login_method TEXT, + FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE + )`; + + // init the passkeys database + // passkey_id - the id of the passkey (Base64URLString) + // public_key - the passkey's public key (Uint8Array) + // user_id - the id of the user who owns the passkey (number) + // webauthn_user_id - the webauthn user id associated with the passkey (string) + // counter - the passkey's counter for preventing replay attacks (number) + // device_type - the type of device the passkey is used on (CredentialDeviceType) + // backed_up - whether the passkey has been backed up or not (boolean) + // transports - the transports supported by the passkey (string array stored as a CSV string -> AuthenticatorTransportFuture[]) + // creation_timestamp - the timestamp of when the passkey was created (Date) + // last_used_timestamp - the timestamp of when the passkey was last used (Date) + await db`CREATE TABLE IF NOT EXISTS Passkeys ( + passkey_id TEXT PRIMARY KEY, + public_key BYTEA, + user_id INTEGER, + webauthn_user_id TEXT, + counter BIGINT, + device_type VARCHAR(32), + backed_up BOOLEAN DEFAULT FALSE, + transports VARCHAR(255), + creation_timetamp TIMESTAMPTZ DEFAULT NOW(), + last_used_timestamp TIMESTAMPTZ DEFAULT NOW(), + FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE + )`; + + return true; + } +} diff --git a/instance/src/systems/configuration.ts b/instance/src/systems/configuration.ts index 7cb78d9..3d4a947 100644 --- a/instance/src/systems/configuration.ts +++ b/instance/src/systems/configuration.ts @@ -1,203 +1,203 @@ -import { promises as fs, existsSync as fsExistsSync, readFileSync as fsReadFileSync } from "node:fs"; -import path from "node:path"; -import type { Instance } from "../index.ts"; -import System from "../system.ts"; - -export enum WorkspacesFeatureFlags { - SlashCommands = "slash_commands", - ShootYourselfInTheFoot = "shoot_yourself_in_the_foot", - AllowUserSignups = "allow_user_signups", -} - -export const FEATURE_FLAG_DESCRIPTIONS = { - [WorkspacesFeatureFlags.SlashCommands]: "Enable the ability to use slash commands in the instance's console", - [WorkspacesFeatureFlags.ShootYourselfInTheFoot]: - "Allow administrators to alter settings / configuration options which may cause the instance to malfunction. (Only enable this if you are sure you know what you are doing!)", - [WorkspacesFeatureFlags.AllowUserSignups]: "Allow new users to create accounts from the instance user login page", -}; - -export default class ConfigurationSystem extends System { - isDevMode: boolean = true; - databases: { - postgres: { - user: string; - password: string; - host: string; - port: number; - database: string; - }; - }; - proxyUrl: string; - enabledFeatures: (WorkspacesFeatureFlags | string)[]; - signupRequirements: { - email: boolean; - twoFactorAuthentication: boolean; - passwordMinimumLength?: number; - passwordContains?: { - minimumUppercase?: number; - minimumLowercase?: number; - minimumNumbers?: number; - minimumSymbols?: number; - }; - }; - displayName: string; - mailServer: { - host: string; - port: number; - secure: boolean; - auth: { - user: string; - pass: string; - }; - }; - termsOfUse: { message: string; lastUpdated: number }; - defaultQuickShortcuts: string[]; - defaultApplications: { id: string; uri: string }[]; - caddyfile: string | undefined; - - constructor(instance: Instance) { - super("configuration", instance); - - this.enabledFeatures = [WorkspacesFeatureFlags.SlashCommands]; - this.databases = { - postgres: { - user: "postgres", - password: "postgres", - host: "localhost", - port: 5432, - database: "onlineworkspace_workspace", - }, - }; - if (process.env.POSTGRES_DATABASE_HOST) this.databases.postgres.host = process.env.POSTGRES_DATABASE_HOST; - this.proxyUrl = "https://localhost"; - this.signupRequirements = { - email: false, - twoFactorAuthentication: false, - passwordMinimumLength: 5, - passwordContains: { - minimumLowercase: 1, - minimumNumbers: 1, - minimumSymbols: 1, - minimumUppercase: 1, - }, - }; - this.displayName = "Workspace"; - this.mailServer = { - host: "smtp.example.com", - port: 587, - secure: true, - auth: { - user: "user", - pass: "password", - }, - }; - this.termsOfUse = { - message: `1. Acceptance of Terms - - By logging in, you agree to these rules. If you do not agree, please do not use the service. -2. Account Security - - You are the gatekeeper of your account. Keep your password private, as you are responsible for all activity that happens under your login. -3. Content Ownership - - What is yours remains yours. We claim no ownership over the files, photos, or data you upload to this instance. -4. Acceptable Use - - Do not use this space for anything illegal, malicious, or harmful. This includes uploading malware or attempting to disrupt the service for others. -5. Privacy and Access - - We value your privacy. We will not access your stored data unless it is strictly necessary for technical support or required by legal authorities. -6. Storage and Maintenance - - While we strive for 100% uptime, this service is provided "as is." We may occasionally perform maintenance that results in temporary downtime. -7. Personal Responsibility - - Hardware and software can fail. You agree to maintain your own external backups of any mission-critical data. We are not liable for data loss. -8. Termination - - We reserve the right to suspend or close accounts that violate these terms or compromise the security of the server. -9. Policy Updates - - These terms may change. If we make significant updates, we will post a notification within the app or send an email.`, - lastUpdated: Date.now(), - }; - this.defaultQuickShortcuts = ["uk.ewsgit.dashboard", "uk.ewsgit.store", "uk.ewsgit.settings", "uk.ewsgit.photos", "uk.ewsgit.files"]; - this.defaultApplications = [ - { id: "uk.ewsgit.dashboard", uri: "local:uk.ewsgit.dashboard" }, - { id: "uk.ewsgit.store", uri: "local:uk.ewsgit.store" }, - { id: "uk.ewsgit.settings", uri: "local:uk.ewsgit.settings" }, - { id: "uk.ewsgit.photos", uri: "local:uk.ewsgit.photos" }, - { id: "uk.ewsgit.files", uri: "local:uk.ewsgit.files" }, - ]; - this.caddyfile = "../Caddyfile"; - if (fsExistsSync(path.join(this.instance.sys.filesystem.AUTOINSTALL_PATH, "configuration.json"))) { - this.log.info("Auto-install configuration detected. Loading configuration from auto-install."); - - const autoInstallConfig = JSON.parse(fsReadFileSync(path.join(this.instance.sys.filesystem.AUTOINSTALL_PATH, "configuration.json")).toString()); - - for (const key of Object.keys(autoInstallConfig)) { - if (key in this) { - // @ts-ignore - this[key] = autoInstallConfig[key]; - } - } - } - } - - hasFeature(feature: WorkspacesFeatureFlags | string): boolean { - return !!this.enabledFeatures.find((f) => f === feature); - } - - async enableFeature(feature: WorkspacesFeatureFlags | string) { - if (!this.enabledFeatures.includes(feature)) this.enabledFeatures.push(feature); - - await this.saveConfiguration(); - - return true; - } - - async disableFeature(feature: WorkspacesFeatureFlags | string) { - this.enabledFeatures = this.enabledFeatures.filter((feat) => feat !== feature); - - await this.saveConfiguration(); - - return true; - } - - async saveConfiguration(): Promise { - const CONFIGURATION_FILE_PATH = path.join(this.instance.sys.filesystem.FS_ROOT, "configuration.json"); - - const allowedProperties = (Object.keys(this) as (keyof ConfigurationSystem)[]).filter((property) => { - return typeof this[property] !== "function" && property !== "instance" && property !== "id" && property !== "log"; - }); - - const configurationFileContents: Record = {}; - - for (const propertyKey of allowedProperties) { - console.log(propertyKey); - configurationFileContents[propertyKey] = this[propertyKey]; - } - - await fs.writeFile(CONFIGURATION_FILE_PATH, JSON.stringify(configurationFileContents, null, 2)); - - return true; - } - - override async startup(): Promise { - const CONFIGURATION_FILE_PATH = path.join(this.instance.sys.filesystem.FS_ROOT, "configuration.json"); - - if (!fsExistsSync(CONFIGURATION_FILE_PATH)) { - await this.saveConfiguration(); - } - - const configurationFile = JSON.parse((await fs.readFile(CONFIGURATION_FILE_PATH)).toString()); - - const allowedProperties = (Object.keys(this) as (keyof ConfigurationSystem)[]).filter((property) => { - return typeof this[property] !== "function" && property !== "instance" && property !== "id" && property !== "log"; - }); - - for (const propertyKey of allowedProperties) { - if (propertyKey in configurationFile) { - // @ts-expect-error We can ignore this as the properties which are read-only are already removed from the allowedProperties by this stage. - this[propertyKey] = configurationFile[propertyKey]; - } - } - - for (const feature of Object.keys(WorkspacesFeatureFlags) as (keyof typeof WorkspacesFeatureFlags)[]) { - this.log.info(`Feature ${feature} -> ${this.enabledFeatures.includes(WorkspacesFeatureFlags[feature])}`); - } - - return true; - } -} +import { promises as fs, existsSync as fsExistsSync, readFileSync as fsReadFileSync } from "node:fs"; +import path from "node:path"; +import type { Instance } from "../index.ts"; +import System from "../system.ts"; + +export enum WorkspacesFeatureFlags { + SlashCommands = "slash_commands", + ShootYourselfInTheFoot = "shoot_yourself_in_the_foot", + AllowUserSignups = "allow_user_signups", +} + +export const FEATURE_FLAG_DESCRIPTIONS = { + [WorkspacesFeatureFlags.SlashCommands]: "Enable the ability to use slash commands in the instance's console", + [WorkspacesFeatureFlags.ShootYourselfInTheFoot]: + "Allow administrators to alter settings / configuration options which may cause the instance to malfunction. (Only enable this if you are sure you know what you are doing!)", + [WorkspacesFeatureFlags.AllowUserSignups]: "Allow new users to create accounts from the instance user login page", +}; + +export default class ConfigurationSystem extends System { + isDevMode: boolean = true; + databases: { + postgres: { + user: string; + password: string; + host: string; + port: number; + database: string; + }; + }; + proxyUrl: string; + enabledFeatures: (WorkspacesFeatureFlags | string)[]; + signupRequirements: { + email: boolean; + twoFactorAuthentication: boolean; + passwordMinimumLength?: number; + passwordContains?: { + minimumUppercase?: number; + minimumLowercase?: number; + minimumNumbers?: number; + minimumSymbols?: number; + }; + }; + displayName: string; + mailServer: { + host: string; + port: number; + secure: boolean; + auth: { + user: string; + pass: string; + }; + }; + termsOfUse: { message: string; lastUpdated: number }; + defaultQuickShortcuts: string[]; + defaultApplications: { id: string; uri: string }[]; + caddyfile: string | undefined; + + constructor(instance: Instance) { + super("configuration", instance); + + this.enabledFeatures = [WorkspacesFeatureFlags.SlashCommands]; + this.databases = { + postgres: { + user: "postgres", + password: "postgres", + host: "localhost", + port: 5432, + database: "onlineworkspace_workspace", + }, + }; + if (process.env.POSTGRES_DATABASE_HOST) this.databases.postgres.host = process.env.POSTGRES_DATABASE_HOST; + this.proxyUrl = "https://localhost"; + this.signupRequirements = { + email: false, + twoFactorAuthentication: false, + passwordMinimumLength: 5, + passwordContains: { + minimumLowercase: 1, + minimumNumbers: 1, + minimumSymbols: 1, + minimumUppercase: 1, + }, + }; + this.displayName = "Workspace"; + this.mailServer = { + host: "smtp.example.com", + port: 587, + secure: true, + auth: { + user: "user", + pass: "password", + }, + }; + this.termsOfUse = { + message: `1. Acceptance of Terms + - By logging in, you agree to these rules. If you do not agree, please do not use the service. +2. Account Security + - You are the gatekeeper of your account. Keep your password private, as you are responsible for all activity that happens under your login. +3. Content Ownership + - What is yours remains yours. We claim no ownership over the files, photos, or data you upload to this instance. +4. Acceptable Use + - Do not use this space for anything illegal, malicious, or harmful. This includes uploading malware or attempting to disrupt the service for others. +5. Privacy and Access + - We value your privacy. We will not access your stored data unless it is strictly necessary for technical support or required by legal authorities. +6. Storage and Maintenance + - While we strive for 100% uptime, this service is provided "as is." We may occasionally perform maintenance that results in temporary downtime. +7. Personal Responsibility + - Hardware and software can fail. You agree to maintain your own external backups of any mission-critical data. We are not liable for data loss. +8. Termination + - We reserve the right to suspend or close accounts that violate these terms or compromise the security of the server. +9. Policy Updates + - These terms may change. If we make significant updates, we will post a notification within the app or send an email.`, + lastUpdated: Date.now(), + }; + this.defaultQuickShortcuts = ["uk.ewsgit.dashboard", "uk.ewsgit.store", "uk.ewsgit.settings", "uk.ewsgit.photos", "uk.ewsgit.files"]; + this.defaultApplications = [ + { id: "uk.ewsgit.dashboard", uri: "local:uk.ewsgit.dashboard" }, + { id: "uk.ewsgit.store", uri: "local:uk.ewsgit.store" }, + { id: "uk.ewsgit.settings", uri: "local:uk.ewsgit.settings" }, + { id: "uk.ewsgit.photos", uri: "local:uk.ewsgit.photos" }, + { id: "uk.ewsgit.files", uri: "local:uk.ewsgit.files" }, + ]; + this.caddyfile = "../Caddyfile"; + if (fsExistsSync(path.join(this.instance.sys.filesystem.AUTOINSTALL_PATH, "configuration.json"))) { + this.log.info("Auto-install configuration detected. Loading configuration from auto-install."); + + const autoInstallConfig = JSON.parse(fsReadFileSync(path.join(this.instance.sys.filesystem.AUTOINSTALL_PATH, "configuration.json")).toString()); + + for (const key of Object.keys(autoInstallConfig)) { + if (key in this) { + // @ts-ignore + this[key] = autoInstallConfig[key]; + } + } + } + } + + hasFeature(feature: WorkspacesFeatureFlags | string): boolean { + return !!this.enabledFeatures.find((f) => f === feature); + } + + async enableFeature(feature: WorkspacesFeatureFlags | string) { + if (!this.enabledFeatures.includes(feature)) this.enabledFeatures.push(feature); + + await this.saveConfiguration(); + + return true; + } + + async disableFeature(feature: WorkspacesFeatureFlags | string) { + this.enabledFeatures = this.enabledFeatures.filter((feat) => feat !== feature); + + await this.saveConfiguration(); + + return true; + } + + async saveConfiguration(): Promise { + const CONFIGURATION_FILE_PATH = path.join(this.instance.sys.filesystem.FS_ROOT, "configuration.json"); + + const allowedProperties = (Object.keys(this) as (keyof ConfigurationSystem)[]).filter((property) => { + return typeof this[property] !== "function" && property !== "instance" && property !== "id" && property !== "log"; + }); + + const configurationFileContents: Record = {}; + + for (const propertyKey of allowedProperties) { + console.log(propertyKey); + configurationFileContents[propertyKey] = this[propertyKey]; + } + + await fs.writeFile(CONFIGURATION_FILE_PATH, JSON.stringify(configurationFileContents, null, 2)); + + return true; + } + + override async startup(): Promise { + const CONFIGURATION_FILE_PATH = path.join(this.instance.sys.filesystem.FS_ROOT, "configuration.json"); + + if (!fsExistsSync(CONFIGURATION_FILE_PATH)) { + await this.saveConfiguration(); + } + + const configurationFile = JSON.parse((await fs.readFile(CONFIGURATION_FILE_PATH)).toString()); + + const allowedProperties = (Object.keys(this) as (keyof ConfigurationSystem)[]).filter((property) => { + return typeof this[property] !== "function" && property !== "instance" && property !== "id" && property !== "log"; + }); + + for (const propertyKey of allowedProperties) { + if (propertyKey in configurationFile) { + // @ts-expect-error We can ignore this as the properties which are read-only are already removed from the allowedProperties by this stage. + this[propertyKey] = configurationFile[propertyKey]; + } + } + + for (const feature of Object.keys(WorkspacesFeatureFlags) as (keyof typeof WorkspacesFeatureFlags)[]) { + this.log.info(`Feature ${feature} -> ${this.enabledFeatures.includes(WorkspacesFeatureFlags[feature])}`); + } + + return true; + } +} diff --git a/instance/src/systems/consoleCommands.ts b/instance/src/systems/consoleCommands.ts index c75d35b..bc5a8da 100644 --- a/instance/src/systems/consoleCommands.ts +++ b/instance/src/systems/consoleCommands.ts @@ -1,6 +1,6 @@ import { promises as fs } from "node:fs"; import path from "node:path"; -import * as readline from "node:readline"; +import type * as readline from "node:readline"; import type { Instance } from "../index.ts"; import System from "../system.ts"; import type Command from "./consoleCommands/command.ts"; @@ -28,7 +28,7 @@ export default class ConsoleCommandsSystem extends System { const commands = await fs.readdir(path.join(this.instance.sys.filesystem.SRC_ROOT, "/systems/consoleCommands/commands/")); for (const cmd of commands) { - const importedCommand = await import(path.join(this.instance.sys.filesystem.SRC_ROOT, "/systems/consoleCommands/commands/", cmd)); + const importedCommand = await import(`file://${path.join(this.instance.sys.filesystem.SRC_ROOT, "/systems/consoleCommands/commands/", cmd)}`); this.commands.push(new importedCommand.default(cmd, this.instance)); this.log.info(`Registered command ${cmd}`); } diff --git a/instance/src/systems/consoleCommands/command.ts b/instance/src/systems/consoleCommands/command.ts index 7aa79cd..ec868ac 100644 --- a/instance/src/systems/consoleCommands/command.ts +++ b/instance/src/systems/consoleCommands/command.ts @@ -44,7 +44,7 @@ export default abstract class Command { this.log._internal_promptMessage(message); } }; - this.log._internal_promptMessage(message + " -> "); + this.log._internal_promptMessage(`${message} -> `); }); } diff --git a/instance/src/systems/consoleCommands/commands/application.ts b/instance/src/systems/consoleCommands/commands/application.ts index a916a27..7de530b 100644 --- a/instance/src/systems/consoleCommands/commands/application.ts +++ b/instance/src/systems/consoleCommands/commands/application.ts @@ -1,33 +1,33 @@ -import Command, { type ICommandRuntimeParameters } from "../command.ts"; - -export default class InstallApplicationCommand extends Command { - override commandId = "application"; - flags = {}; - aliases = ["app"]; - override shortDescription = "Enable / Disable an application"; - - async run(parameters: ICommandRuntimeParameters) { - const targetId = parameters.arguments[0]; - - if (!targetId) { - this.instance.log.system.warning(`Failed to find application '${targetId}' please provide a valid id`); - - return this.finishRun(); - } - - switch (parameters.arguments[1]) { - case "enable": - this.instance.log.system.info(`Enabling application '${targetId}'`); - await this.instance.sys.applications.enableApplication(targetId); - break; - case "disable": - this.instance.log.system.info(`Disabling application '${targetId}'`); - await this.instance.sys.applications.disableApplication(targetId); - break; - default: - this.instance.log.system.warning(`You must provide either 'enable' or 'disable' as an action for the selected application.`); - } - - return this.finishRun(); - } -} +import Command, { type ICommandRuntimeParameters } from "../command.ts"; + +export default class InstallApplicationCommand extends Command { + override commandId = "application"; + flags = {}; + aliases = ["app"]; + override shortDescription = "Enable / Disable an application"; + + async run(parameters: ICommandRuntimeParameters) { + const targetId = parameters.arguments[0]; + + if (!targetId) { + this.instance.log.system.warning(`Failed to find application '${targetId}' please provide a valid id`); + + return this.finishRun(); + } + + switch (parameters.arguments[1]) { + case "enable": + this.instance.log.system.info(`Enabling application '${targetId}'`); + await this.instance.sys.applications.enableApplication(targetId); + break; + case "disable": + this.instance.log.system.info(`Disabling application '${targetId}'`); + await this.instance.sys.applications.disableApplication(targetId); + break; + default: + this.instance.log.system.warning(`You must provide either 'enable' or 'disable' as an action for the selected application.`); + } + + return this.finishRun(); + } +} diff --git a/instance/src/systems/consoleCommands/commands/exit.ts b/instance/src/systems/consoleCommands/commands/exit.ts index 8b81c1d..21b2671 100644 --- a/instance/src/systems/consoleCommands/commands/exit.ts +++ b/instance/src/systems/consoleCommands/commands/exit.ts @@ -1,15 +1,15 @@ -import Command, { type ICommandRuntimeParameters } from "../command.ts"; - -export default class ExitCommand extends Command { - override commandId = "exit"; - flags = {}; - aliases = []; - override shortDescription = "Terminate the Workspaces instance"; - - async run(parameters: ICommandRuntimeParameters) { - await this.instance.shutdown(); - - // Note: do not remove this line of code or Typescript will complain - return this.finishRun(); - } -} +import Command, { type ICommandRuntimeParameters } from "../command.ts"; + +export default class ExitCommand extends Command { + override commandId = "exit"; + flags = {}; + aliases = []; + override shortDescription = "Terminate the Workspaces instance"; + + async run(parameters: ICommandRuntimeParameters) { + await this.instance.shutdown(); + + // Note: do not remove this line of code or Typescript will complain + return this.finishRun(); + } +} diff --git a/instance/src/systems/consoleCommands/commands/feature.ts b/instance/src/systems/consoleCommands/commands/feature.ts index 07d6558..e72664d 100644 --- a/instance/src/systems/consoleCommands/commands/feature.ts +++ b/instance/src/systems/consoleCommands/commands/feature.ts @@ -1,57 +1,57 @@ -import Command, { type ICommandRuntimeParameters } from "../command.ts"; -import chalk from "chalk"; -import { WorkspacesFeatureFlags } from "../../configuration.ts"; - -export default class EnableFeatureCommand extends Command { - override commandId = "feature"; - flags = {}; - aliases = []; - override shortDescription = "Manage instance enabled features"; - - async run(parameters: ICommandRuntimeParameters) { - const action = await this.promptUser("Action", (a) => { - switch (a.toLowerCase()) { - case "enable": - case "disable": - case "help": - case "list": - return true; - default: - return false; - } - }); - - switch (action.toLowerCase()) { - case "enable": { - const featureId = await this.promptUser("FeatureId"); - - this.instance.log.system.info(`Enabling feature '${featureId}'`); - - await this.instance.sys.configuration.enableFeature(featureId); - break; - } - case "disable": { - const featureId = await this.promptUser("FeatureId"); - - this.instance.log.system.info(`Disabling feature '${featureId}'`); - - await this.instance.sys.configuration.disableFeature(featureId); - break; - } - case "help": { - this.instance.log.system.info(`Available commands: 'enable', 'disable', 'help', 'list'`); - break; - } - case "list": { - for (const feat of Object.values(WorkspacesFeatureFlags)) { - this.log.info(`Feature: ${feat} -> ${this.instance.sys.configuration.hasFeature(feat)}`); - } - - this.log.info(`Enabled features -> ${this.instance.sys.configuration.enabledFeatures.join(", ")}`); - break; - } - } - - return this.finishRun(); - } -} +import Command, { type ICommandRuntimeParameters } from "../command.ts"; +import chalk from "chalk"; +import { WorkspacesFeatureFlags } from "../../configuration.ts"; + +export default class EnableFeatureCommand extends Command { + override commandId = "feature"; + flags = {}; + aliases = []; + override shortDescription = "Manage instance enabled features"; + + async run(parameters: ICommandRuntimeParameters) { + const action = await this.promptUser("Action", (a) => { + switch (a.toLowerCase()) { + case "enable": + case "disable": + case "help": + case "list": + return true; + default: + return false; + } + }); + + switch (action.toLowerCase()) { + case "enable": { + const featureId = await this.promptUser("FeatureId"); + + this.instance.log.system.info(`Enabling feature '${featureId}'`); + + await this.instance.sys.configuration.enableFeature(featureId); + break; + } + case "disable": { + const featureId = await this.promptUser("FeatureId"); + + this.instance.log.system.info(`Disabling feature '${featureId}'`); + + await this.instance.sys.configuration.disableFeature(featureId); + break; + } + case "help": { + this.instance.log.system.info(`Available commands: 'enable', 'disable', 'help', 'list'`); + break; + } + case "list": { + for (const feat of Object.values(WorkspacesFeatureFlags)) { + this.log.info(`Feature: ${feat} -> ${this.instance.sys.configuration.hasFeature(feat)}`); + } + + this.log.info(`Enabled features -> ${this.instance.sys.configuration.enabledFeatures.join(", ")}`); + break; + } + } + + return this.finishRun(); + } +} diff --git a/instance/src/systems/consoleCommands/commands/help.ts b/instance/src/systems/consoleCommands/commands/help.ts index 13d2a17..2aea5ef 100644 --- a/instance/src/systems/consoleCommands/commands/help.ts +++ b/instance/src/systems/consoleCommands/commands/help.ts @@ -1,30 +1,30 @@ -import Command, { type ICommandRuntimeParameters } from "../command.ts"; -import chalk from "chalk"; - -export default class HelpCommand extends Command { - override commandId = "help"; - flags = {}; - aliases = []; - override shortDescription = "Display this help information"; - - async run(parameters: ICommandRuntimeParameters) { - const HELP_BANNER_TITLE = " Workspaces Help "; - const LOG_WIDTH = process.stdout.getWindowSize()[0] - (this.instance.log.META_LENGTH + 8); - - this.instance.log.system.info( - "-".repeat((LOG_WIDTH - HELP_BANNER_TITLE.length) / 2) + HELP_BANNER_TITLE + "-".repeat((LOG_WIDTH - HELP_BANNER_TITLE.length) / 2), - ); - - for (const command of this.instance.sys.consoleCommands.commands) { - this.instance.log.system.info( - `${this.instance.log.system.emphasis(command.commandId)}${command.aliases.length > 0 ? ", " : ""}${command.aliases.join(", ")} - ${command.shortDescription}`, - ); - if (Object.keys(command.flags).length > 0) { - this.instance.log.system.info(` ${chalk.bold("flags")}:`); - this.instance.log.system.info(` ${JSON.stringify(command.flags)}`); - } - } - - return this.finishRun(); - } -} +import Command, { type ICommandRuntimeParameters } from "../command.ts"; +import chalk from "chalk"; + +export default class HelpCommand extends Command { + override commandId = "help"; + flags = {}; + aliases = []; + override shortDescription = "Display this help information"; + + async run(parameters: ICommandRuntimeParameters) { + const HELP_BANNER_TITLE = " Workspaces Help "; + const LOG_WIDTH = process.stdout.getWindowSize()[0] - (this.instance.log.META_LENGTH + 8); + + this.instance.log.system.info( + "-".repeat((LOG_WIDTH - HELP_BANNER_TITLE.length) / 2) + HELP_BANNER_TITLE + "-".repeat((LOG_WIDTH - HELP_BANNER_TITLE.length) / 2), + ); + + for (const command of this.instance.sys.consoleCommands.commands) { + this.instance.log.system.info( + `${this.instance.log.system.emphasis(command.commandId)}${command.aliases.length > 0 ? ", " : ""}${command.aliases.join(", ")} - ${command.shortDescription}`, + ); + if (Object.keys(command.flags).length > 0) { + this.instance.log.system.info(` ${chalk.bold("flags")}:`); + this.instance.log.system.info(` ${JSON.stringify(command.flags)}`); + } + } + + return this.finishRun(); + } +} diff --git a/instance/src/systems/consoleCommands/commands/install_application.ts b/instance/src/systems/consoleCommands/commands/install_application.ts index 79afd51..319d1ee 100644 --- a/instance/src/systems/consoleCommands/commands/install_application.ts +++ b/instance/src/systems/consoleCommands/commands/install_application.ts @@ -1,24 +1,24 @@ -import Command, { type ICommandRuntimeParameters } from "../command.ts"; - -export default class InstallApplicationCommand extends Command { - override commandId = "install_application"; - flags = {}; - aliases = []; - override shortDescription = "Install an application by a uri"; - - async run(parameters: ICommandRuntimeParameters) { - if (!parameters.arguments[0]) { - this.instance.log.system.warning(`Failed to install application '' please provide a valid uri`); - - return this.finishRun(); - } - - const applicationURI = parameters.arguments[0]; - - this.instance.log.system.info(`Installing application '${applicationURI}'`); - - await this.instance.sys.applications.installApplication(applicationURI); - - return this.finishRun(); - } -} +import Command, { type ICommandRuntimeParameters } from "../command.ts"; + +export default class InstallApplicationCommand extends Command { + override commandId = "install_application"; + flags = {}; + aliases = []; + override shortDescription = "Install an application by a uri"; + + async run(parameters: ICommandRuntimeParameters) { + if (!parameters.arguments[0]) { + this.instance.log.system.warning(`Failed to install application '' please provide a valid uri`); + + return this.finishRun(); + } + + const applicationURI = parameters.arguments[0]; + + this.instance.log.system.info(`Installing application '${applicationURI}'`); + + await this.instance.sys.applications.installApplication(applicationURI); + + return this.finishRun(); + } +} diff --git a/instance/src/systems/consoleCommands/commands/notify.ts b/instance/src/systems/consoleCommands/commands/notify.ts index 86e46a3..493fb03 100644 --- a/instance/src/systems/consoleCommands/commands/notify.ts +++ b/instance/src/systems/consoleCommands/commands/notify.ts @@ -1,42 +1,42 @@ -import { WorkspacesNotificationPriority } from "../../notifications.ts"; -import Command, { type ICommandRuntimeParameters } from "../command.ts"; - -export default class RestartCommand extends Command { - override commandId = "notify"; - flags = {}; - aliases = []; - override shortDescription = "Send a notification to all administrators"; - - async run(parameters: ICommandRuntimeParameters) { - for (const userId of (await this.instance.sys.users.getAllUsers()).map((u) => u.userId)) { - this.instance.sys.notifications.send( - userId, - "commands.notify", - WorkspacesNotificationPriority.Important, - { - title: "Notification Test 1", - body: "This is a sample notification from the console!", - icon: "person", - }, - { - buttons: [ - { - id: "a", - label: "label", - type: "filled", - }, - { - id: "a", - label: "label", - type: "tonal", - }, - ], - }, - ); - } - - this.log.info("sent notifications"); - - return this.finishRun(); - } -} +import { WorkspacesNotificationPriority } from "../../notifications.ts"; +import Command, { type ICommandRuntimeParameters } from "../command.ts"; + +export default class RestartCommand extends Command { + override commandId = "notify"; + flags = {}; + aliases = []; + override shortDescription = "Send a notification to all administrators"; + + async run(parameters: ICommandRuntimeParameters) { + for (const userId of (await this.instance.sys.users.getAllUsers()).map((u) => u.userId)) { + this.instance.sys.notifications.send( + userId, + "commands.notify", + WorkspacesNotificationPriority.Important, + { + title: "Notification Test 1", + body: "This is a sample notification from the console!", + icon: "person", + }, + { + buttons: [ + { + id: "a", + label: "label", + type: "filled", + }, + { + id: "a", + label: "label", + type: "tonal", + }, + ], + }, + ); + } + + this.log.info("sent notifications"); + + return this.finishRun(); + } +} diff --git a/instance/src/systems/consoleCommands/commands/op.ts b/instance/src/systems/consoleCommands/commands/op.ts index 565edaf..e3a2b7b 100644 --- a/instance/src/systems/consoleCommands/commands/op.ts +++ b/instance/src/systems/consoleCommands/commands/op.ts @@ -1,40 +1,40 @@ -import Command, { type ICommandRuntimeParameters } from "../command.ts"; - -export default class ExitCommand extends Command { - override commandId = "op"; - flags = {}; - aliases = []; - override shortDescription = "Make a user into an administrator"; - - async run(parameters: ICommandRuntimeParameters) { - const self = this; - - let username = ""; - - const log = self.instance.log.createLogger("op_command"); - log._internal_promptMessage("Username -> "); - self.instance.sys.consoleCommands.currentCommandInterface.cb = async (data) => { - username = data.trim(); - if (username !== "") { - let user = await self.instance.sys.users.getUserByUsername(username); - - if (!user) { - log.error(`Invaid user '${username}'`); - username = ""; - log._internal_promptMessage("Username -> "); - return this.continueRun(); - } - - await user.setIsAdministrator(true); - - log.success(`User '${username}' was promoted to administrator successfully!`); - - return this.finishRun(); - } else { - log._internal_promptMessage("Username -> "); - } - }; - - return this.continueRun(); - } -} +import Command, { type ICommandRuntimeParameters } from "../command.ts"; + +export default class ExitCommand extends Command { + override commandId = "op"; + flags = {}; + aliases = []; + override shortDescription = "Make a user into an administrator"; + + async run(parameters: ICommandRuntimeParameters) { + const self = this; + + let username = ""; + + const log = self.instance.log.createLogger("op_command"); + log._internal_promptMessage("Username -> "); + self.instance.sys.consoleCommands.currentCommandInterface.cb = async (data) => { + username = data.trim(); + if (username !== "") { + let user = await self.instance.sys.users.getUserByUsername(username); + + if (!user) { + log.error(`Invaid user '${username}'`); + username = ""; + log._internal_promptMessage("Username -> "); + return this.continueRun(); + } + + await user.setIsAdministrator(true); + + log.success(`User '${username}' was promoted to administrator successfully!`); + + return this.finishRun(); + } else { + log._internal_promptMessage("Username -> "); + } + }; + + return this.continueRun(); + } +} diff --git a/instance/src/systems/consoleCommands/commands/password.ts b/instance/src/systems/consoleCommands/commands/password.ts index a5125fc..e06de6e 100644 --- a/instance/src/systems/consoleCommands/commands/password.ts +++ b/instance/src/systems/consoleCommands/commands/password.ts @@ -1,26 +1,26 @@ -import Command, { type ICommandRuntimeParameters } from "../command.ts"; - -export default class PasswordCommand extends Command { - override commandId = "password"; - flags = {}; - aliases = ["passwd"]; - override shortDescription = "Set a user's password"; - - async run(parameters: ICommandRuntimeParameters) { - const self = this; - - let username = await this.promptUser("Username", async (u) => { - console.log("entered '" + u + "'"); - return (await this.instance.sys.users.getUserByUsername(u)) !== undefined; - }); - let newPassword = await this.promptUser("Password", () => true); - - const userId = (await this.instance.sys.users.getUserByUsername(username))?.userId; - - if (!userId) return this.finishRun(); - - await this.instance.sys.authorization.setPassword(userId, newPassword); - - return this.finishRun(); - } -} +import Command, { type ICommandRuntimeParameters } from "../command.ts"; + +export default class PasswordCommand extends Command { + override commandId = "password"; + flags = {}; + aliases = ["passwd"]; + override shortDescription = "Set a user's password"; + + async run(parameters: ICommandRuntimeParameters) { + const self = this; + + let username = await this.promptUser("Username", async (u) => { + console.log("entered '" + u + "'"); + return (await this.instance.sys.users.getUserByUsername(u)) !== undefined; + }); + let newPassword = await this.promptUser("Password", () => true); + + const userId = (await this.instance.sys.users.getUserByUsername(username))?.userId; + + if (!userId) return this.finishRun(); + + await this.instance.sys.authorization.setPassword(userId, newPassword); + + return this.finishRun(); + } +} diff --git a/instance/src/systems/consoleCommands/commands/restart.ts b/instance/src/systems/consoleCommands/commands/restart.ts index 2e8b033..fed94cb 100644 --- a/instance/src/systems/consoleCommands/commands/restart.ts +++ b/instance/src/systems/consoleCommands/commands/restart.ts @@ -1,26 +1,26 @@ -import Command, { type ICommandRuntimeParameters } from "../command.ts"; - -export default class RestartCommand extends Command { - override commandId = "restart"; - flags = {}; - aliases = ["rs"]; - override shortDescription = "Restart the Workspaces instance"; - - async run(parameters: ICommandRuntimeParameters) { - // this.instance.log.info( - // "command_restart", - // "Restarting Workspaces instance...", - // ); - - this.instance.log.system.error("command_restart", "This command does not work as instance shutdown is unimplemented..."); - - // TODO: implement a shutdown sequence - // this.instance.shutdown() - // this.instance.requestManager.app.server.close(); - // this.instance.commandManager.close(); - - this.instance.shutdown(); - - return this.finishRun(); - } -} +import Command, { type ICommandRuntimeParameters } from "../command.ts"; + +export default class RestartCommand extends Command { + override commandId = "restart"; + flags = {}; + aliases = ["rs"]; + override shortDescription = "Restart the Workspaces instance"; + + async run(parameters: ICommandRuntimeParameters) { + // this.instance.log.info( + // "command_restart", + // "Restarting Workspaces instance...", + // ); + + this.instance.log.system.error("command_restart", "This command does not work as instance shutdown is unimplemented..."); + + // TODO: implement a shutdown sequence + // this.instance.shutdown() + // this.instance.requestManager.app.server.close(); + // this.instance.commandManager.close(); + + this.instance.shutdown(); + + return this.finishRun(); + } +} diff --git a/instance/src/systems/consoleCommands/commands/stop.ts b/instance/src/systems/consoleCommands/commands/stop.ts index f543489..54b47ba 100644 --- a/instance/src/systems/consoleCommands/commands/stop.ts +++ b/instance/src/systems/consoleCommands/commands/stop.ts @@ -1,15 +1,15 @@ -import Command, { type ICommandRuntimeParameters } from "../command.ts"; - -export default class ExitCommand extends Command { - override commandId = "stop"; - flags = {}; - aliases = []; - override shortDescription = "Terminate the Workspaces instance"; - - async run(parameters: ICommandRuntimeParameters) { - await this.instance.shutdown(); - - // Note: do not remove this line of code or TypeScript will complain - return this.finishRun(); - } -} +import Command, { type ICommandRuntimeParameters } from "../command.ts"; + +export default class ExitCommand extends Command { + override commandId = "stop"; + flags = {}; + aliases = []; + override shortDescription = "Terminate the Workspaces instance"; + + async run(parameters: ICommandRuntimeParameters) { + await this.instance.shutdown(); + + // Note: do not remove this line of code or TypeScript will complain + return this.finishRun(); + } +} diff --git a/instance/src/systems/consoleCommands/commands/useradd.ts b/instance/src/systems/consoleCommands/commands/useradd.ts index 524c74c..c40bc7e 100644 --- a/instance/src/systems/consoleCommands/commands/useradd.ts +++ b/instance/src/systems/consoleCommands/commands/useradd.ts @@ -1,89 +1,89 @@ -import Command, { type ICommandRuntimeParameters } from "../command.ts"; - -export default class ExitCommand extends Command { - override commandId = "useradd"; - flags = {}; - aliases = []; - override shortDescription = "Create a new user"; - - async run(parameters: ICommandRuntimeParameters) { - const self = this; - - let username = ""; - let password = ""; - let fullName = ""; - let email = ""; - let gender = "other"; - - const log = self.instance.log.createLogger("useradd_command"); - log._internal_promptMessage("Username -> "); - self.instance.sys.consoleCommands.currentCommandInterface.cb = async (data) => { - username = data.trim(); - if (username !== "") { - log._internal_promptMessage("Password -> "); - self.instance.sys.consoleCommands.currentCommandInterface.cb = async (data) => { - password = data.trim(); - if (password !== "") { - log._internal_promptMessage("Full Name -> "); - self.instance.sys.consoleCommands.currentCommandInterface.cb = async (data) => { - fullName = data.trim(); - if (fullName !== "") { - log._internal_promptMessage("Email -> "); - self.instance.sys.consoleCommands.currentCommandInterface.cb = async (data) => { - email = data.trim(); - if (email !== "") { - log._internal_promptMessage("Gender -> "); - self.instance.sys.consoleCommands.currentCommandInterface.cb = async (data) => { - gender = data.trim(); - if (gender !== "") { - if (gender === "male" || gender === "other" || gender === "female") { - log.rawLog("\n"); - log.info("Creating user..."); - - let uid = await self.instance.sys.users.createUser(username, password); - - if (!uid) { - log.error("Failed to create user"); - return; - } - - let user = await self.instance.sys.users.getUserById(uid); - - if (!user) { - log.error("Failed to get created user"); - return; - } - - await user.setGender(gender); - let fullNameSplit = fullName.split(" "); - await user.setFullName(fullNameSplit.shift() || "Unknown", fullNameSplit.join(" ")); - await user.setEmail(email); - - return this.finishRun(); - } else { - log._internal_promptMessage("Gender -> "); - } - } else { - log._internal_promptMessage("Gender -> "); - } - }; - } else { - log._internal_promptMessage("Email -> "); - } - }; - } else { - log._internal_promptMessage("Full Name -> "); - } - }; - } else { - log._internal_promptMessage("Password -> "); - } - }; - } else { - log._internal_promptMessage("Username -> "); - } - }; - - return this.continueRun(); - } -} +import Command, { type ICommandRuntimeParameters } from "../command.ts"; + +export default class ExitCommand extends Command { + override commandId = "useradd"; + flags = {}; + aliases = []; + override shortDescription = "Create a new user"; + + async run(parameters: ICommandRuntimeParameters) { + const self = this; + + let username = ""; + let password = ""; + let fullName = ""; + let email = ""; + let gender = "other"; + + const log = self.instance.log.createLogger("useradd_command"); + log._internal_promptMessage("Username -> "); + self.instance.sys.consoleCommands.currentCommandInterface.cb = async (data) => { + username = data.trim(); + if (username !== "") { + log._internal_promptMessage("Password -> "); + self.instance.sys.consoleCommands.currentCommandInterface.cb = async (data) => { + password = data.trim(); + if (password !== "") { + log._internal_promptMessage("Full Name -> "); + self.instance.sys.consoleCommands.currentCommandInterface.cb = async (data) => { + fullName = data.trim(); + if (fullName !== "") { + log._internal_promptMessage("Email -> "); + self.instance.sys.consoleCommands.currentCommandInterface.cb = async (data) => { + email = data.trim(); + if (email !== "") { + log._internal_promptMessage("Gender -> "); + self.instance.sys.consoleCommands.currentCommandInterface.cb = async (data) => { + gender = data.trim(); + if (gender !== "") { + if (gender === "male" || gender === "other" || gender === "female") { + log.rawLog("\n"); + log.info("Creating user..."); + + let uid = await self.instance.sys.users.createUser(username, password); + + if (!uid) { + log.error("Failed to create user"); + return; + } + + let user = await self.instance.sys.users.getUserById(uid); + + if (!user) { + log.error("Failed to get created user"); + return; + } + + await user.setGender(gender); + let fullNameSplit = fullName.split(" "); + await user.setFullName(fullNameSplit.shift() || "Unknown", fullNameSplit.join(" ")); + await user.setEmail(email); + + return this.finishRun(); + } else { + log._internal_promptMessage("Gender -> "); + } + } else { + log._internal_promptMessage("Gender -> "); + } + }; + } else { + log._internal_promptMessage("Email -> "); + } + }; + } else { + log._internal_promptMessage("Full Name -> "); + } + }; + } else { + log._internal_promptMessage("Password -> "); + } + }; + } else { + log._internal_promptMessage("Username -> "); + } + }; + + return this.continueRun(); + } +} diff --git a/instance/src/systems/consoleCommands/commands/userdel.ts b/instance/src/systems/consoleCommands/commands/userdel.ts index 7b648c6..058ec86 100644 --- a/instance/src/systems/consoleCommands/commands/userdel.ts +++ b/instance/src/systems/consoleCommands/commands/userdel.ts @@ -1,39 +1,39 @@ -import Command, { type ICommandRuntimeParameters } from "../command.ts"; - -export default class ExitCommand extends Command { - override commandId = "userdel"; - flags = {}; - aliases = []; - override shortDescription = "Delete a user"; - - async run(parameters: ICommandRuntimeParameters) { - const self = this; - - let username = ""; - - const log = self.instance.log.createLogger("userdel_command"); - log._internal_promptMessage("Username -> "); - self.instance.sys.consoleCommands.currentCommandInterface.cb = async (data) => { - username = data.trim(); - if (username !== "") { - let user = await self.instance.sys.users.getUserByUsername(username); - - if (!user) { - username = ""; - log._internal_promptMessage("Username -> "); - return this.continueRun(); - } - - await user.delete(); - - log.success(`User '${username}' was deleted successfully!`); - - return this.finishRun(); - } else { - log._internal_promptMessage("Username -> "); - } - }; - - return this.continueRun(); - } -} +import Command, { type ICommandRuntimeParameters } from "../command.ts"; + +export default class ExitCommand extends Command { + override commandId = "userdel"; + flags = {}; + aliases = []; + override shortDescription = "Delete a user"; + + async run(parameters: ICommandRuntimeParameters) { + const self = this; + + let username = ""; + + const log = self.instance.log.createLogger("userdel_command"); + log._internal_promptMessage("Username -> "); + self.instance.sys.consoleCommands.currentCommandInterface.cb = async (data) => { + username = data.trim(); + if (username !== "") { + let user = await self.instance.sys.users.getUserByUsername(username); + + if (!user) { + username = ""; + log._internal_promptMessage("Username -> "); + return this.continueRun(); + } + + await user.delete(); + + log.success(`User '${username}' was deleted successfully!`); + + return this.finishRun(); + } else { + log._internal_promptMessage("Username -> "); + } + }; + + return this.continueRun(); + } +} diff --git a/instance/src/systems/consoleCommands/commands/users.ts b/instance/src/systems/consoleCommands/commands/users.ts index 95d9c15..9250241 100644 --- a/instance/src/systems/consoleCommands/commands/users.ts +++ b/instance/src/systems/consoleCommands/commands/users.ts @@ -1,25 +1,25 @@ -import Command, { type ICommandRuntimeParameters } from "../command.ts"; - -export default class ExitCommand extends Command { - override commandId = "users"; - flags = {}; - aliases = []; - override shortDescription = "List all users"; - - async run(parameters: ICommandRuntimeParameters) { - const self = this; - - const log = self.instance.log.createLogger("users_command"); - - const db = self.instance.sys.database.postgres(); - - const users = await db`SELECT * FROM users ORDER BY id ASC`; - - log.info(`(ID) | @username | Forename + Surname`); - for (const user of users) { - log.info(`(${user.id}) @${user.username} -> ${user.forename} ${user.surname}`); - } - - return this.finishRun(); - } -} +import Command, { type ICommandRuntimeParameters } from "../command.ts"; + +export default class ExitCommand extends Command { + override commandId = "users"; + flags = {}; + aliases = []; + override shortDescription = "List all users"; + + async run(parameters: ICommandRuntimeParameters) { + const self = this; + + const log = self.instance.log.createLogger("users_command"); + + const db = self.instance.sys.database.postgres(); + + const users = await db`SELECT * FROM users ORDER BY id ASC`; + + log.info(`(ID) | @username | Forename + Surname`); + for (const user of users) { + log.info(`(${user.id}) @${user.username} -> ${user.forename} ${user.surname}`); + } + + return this.finishRun(); + } +} diff --git a/instance/src/systems/database.ts b/instance/src/systems/database.ts index 6a35847..a292fb8 100644 --- a/instance/src/systems/database.ts +++ b/instance/src/systems/database.ts @@ -1,65 +1,65 @@ -import postgres from "postgres"; -import type { Instance } from "../index.ts"; -import System from "../system.ts"; - -export default class DatabaseSystem extends System { - databaseConnections: { [connectionId: string]: postgres.Sql }; - - constructor(instance: Instance) { - super("database", instance); - - this.databaseConnections = {}; - } - - // private sqlite(connectionId: string) { - // if (this.databaseConnections[connectionId]) return this.databaseConnections[connectionId]; - - // const conPath = `sqlite://${path.join(this.instance.sys.filesystem.FS_ROOT, connectionId)}.sqlite`; - - // const con = new SQL({ - // adapter: "sqlite", - // readwrite: true, - // create: true, - // filename: conPath, - // }); - - // this.databaseConnections[connectionId] = con; - - // return con; - // } - - postgres() { - if (this.databaseConnections.postgres) return this.databaseConnections.postgres; - - this.log.info( - `Connecting to database @ '${this.instance.sys.configuration.databases.postgres.host}' named '${this.instance.sys.configuration.databases.postgres.database}'`, - ); - - const con = postgres({ - db: this.instance.sys.configuration.databases.postgres.database, - hostname: this.instance.sys.configuration.databases.postgres.host, - port: this.instance.sys.configuration.databases.postgres.port, - user: this.instance.sys.configuration.databases.postgres.user, - password: this.instance.sys.configuration.databases.postgres.password, - - onnotice: (message) => { - if (message.severity === "NOTICE") return; - - console.log(message); - }, - }); - - this.databaseConnections.postgres = con; - - this.log.info( - `Established connection to database @ '${this.instance.sys.configuration.databases.postgres.host}' named '${this.instance.sys.configuration.databases.postgres.database}'`, - ); - - return con; - } - - override async startup(): Promise { - this.log.info("Starting up..."); - return true; - } -} +import postgres from "postgres"; +import type { Instance } from "../index.ts"; +import System from "../system.ts"; + +export default class DatabaseSystem extends System { + databaseConnections: { [connectionId: string]: postgres.Sql }; + + constructor(instance: Instance) { + super("database", instance); + + this.databaseConnections = {}; + } + + // private sqlite(connectionId: string) { + // if (this.databaseConnections[connectionId]) return this.databaseConnections[connectionId]; + + // const conPath = `sqlite://${path.join(this.instance.sys.filesystem.FS_ROOT, connectionId)}.sqlite`; + + // const con = new SQL({ + // adapter: "sqlite", + // readwrite: true, + // create: true, + // filename: conPath, + // }); + + // this.databaseConnections[connectionId] = con; + + // return con; + // } + + postgres() { + if (this.databaseConnections.postgres) return this.databaseConnections.postgres; + + this.log.info( + `Connecting to database @ '${this.instance.sys.configuration.databases.postgres.host}' named '${this.instance.sys.configuration.databases.postgres.database}'`, + ); + + const con = postgres({ + db: this.instance.sys.configuration.databases.postgres.database, + hostname: this.instance.sys.configuration.databases.postgres.host, + port: this.instance.sys.configuration.databases.postgres.port, + user: this.instance.sys.configuration.databases.postgres.user, + password: this.instance.sys.configuration.databases.postgres.password, + + onnotice: (message) => { + if (message.severity === "NOTICE") return; + + console.log(message); + }, + }); + + this.databaseConnections.postgres = con; + + this.log.info( + `Established connection to database @ '${this.instance.sys.configuration.databases.postgres.host}' named '${this.instance.sys.configuration.databases.postgres.database}'`, + ); + + return con; + } + + override async startup(): Promise { + this.log.info("Starting up..."); + return true; + } +} diff --git a/instance/src/systems/email.ts b/instance/src/systems/email.ts index c07966e..0e9eb42 100644 --- a/instance/src/systems/email.ts +++ b/instance/src/systems/email.ts @@ -1,23 +1,23 @@ -import * as nm from "nodemailer"; -import type { Instance } from "../index.ts"; -import System from "../system.ts"; - -export default class EmailSystem extends System { - transporter!: nm.Transporter; - - constructor(instance: Instance) { - super("email", instance); - } - - override async startup(): Promise { - this.transporter = nm.createTransport(this.instance.sys.configuration.mailServer); - - try { - this.log.info(`Connecting to ${this.instance.sys.configuration.mailServer.host}:${this.instance.sys.configuration.mailServer.port}...`); - await this.transporter.verify(); - return true; - } catch (err) { - return false; - } - } -} +import * as nm from "nodemailer"; +import type { Instance } from "../index.ts"; +import System from "../system.ts"; + +export default class EmailSystem extends System { + transporter!: nm.Transporter; + + constructor(instance: Instance) { + super("email", instance); + } + + override async startup(): Promise { + this.transporter = nm.createTransport(this.instance.sys.configuration.mailServer); + + try { + this.log.info(`Connecting to ${this.instance.sys.configuration.mailServer.host}:${this.instance.sys.configuration.mailServer.port}...`); + await this.transporter.verify(); + return true; + } catch (err) { + return false; + } + } +} diff --git a/instance/src/systems/events.ts b/instance/src/systems/events.ts index b1af9b1..2a6ffc7 100644 --- a/instance/src/systems/events.ts +++ b/instance/src/systems/events.ts @@ -1,101 +1,101 @@ -import type { Instance } from "../index.ts"; -import System from "../system.ts"; - -export enum WorkspacesEvent { - BeforeStartupComplete, - BeforeShutdown, - Weekly, - Daily, - Hourly, - HalfHourly, - QuarterHourly, - Minutely, - ApplicationSettingsChanged, - GlobalApplicationSettingsChanged, - UpdateAvailable, - UpdateComplete, -} - -export default class EventSystem extends System { - __internal_eventListeners: { [key in WorkspacesEvent]?: (() => void)[] } = {}; - - constructor(instance: Instance) { - super("event", instance); - - const minutelyTimer = setInterval(() => { - this.invoke(WorkspacesEvent.Minutely); - }, 60 * 1000); - - const quarterHourlyTimer = setInterval( - () => { - this.invoke(WorkspacesEvent.QuarterHourly); - }, - 15 * 60 * 1000, - ); - - const halfHourlyTimer = setInterval( - () => { - this.invoke(WorkspacesEvent.HalfHourly); - }, - 30 * 60 * 1000, - ); - - const hourlyTimer = setInterval( - () => { - this.invoke(WorkspacesEvent.Hourly); - }, - 60 * 60 * 1000, - ); - - const dailyTimer = setInterval( - () => { - this.invoke(WorkspacesEvent.Daily); - }, - 24 * 60 * 60 * 1000, - ); - - const weeklyTimer = setInterval( - () => { - this.invoke(WorkspacesEvent.Weekly); - }, - 7 * 24 * 60 * 60 * 1000, - ); - - this.on(WorkspacesEvent.BeforeShutdown, () => { - clearInterval(minutelyTimer); - clearInterval(quarterHourlyTimer); - clearInterval(halfHourlyTimer); - clearInterval(hourlyTimer); - clearInterval(dailyTimer); - clearInterval(weeklyTimer); - }); - } - - on(eventType: WorkspacesEvent, cb: () => void) { - if (!this.__internal_eventListeners[eventType]) { - this.__internal_eventListeners[eventType] = []; - } - - this.__internal_eventListeners[eventType].push(cb); - - return this; - } - - invoke(eventType: WorkspacesEvent) { - const events = this.__internal_eventListeners[eventType]; - - if (!events) { - return this; - } - - for (const event of events) { - event(); - } - - return this; - } - - override async startup(): Promise { - return true; - } -} +import type { Instance } from "../index.ts"; +import System from "../system.ts"; + +export enum WorkspacesEvent { + BeforeStartupComplete, + BeforeShutdown, + Weekly, + Daily, + Hourly, + HalfHourly, + QuarterHourly, + Minutely, + ApplicationSettingsChanged, + GlobalApplicationSettingsChanged, + UpdateAvailable, + UpdateComplete, +} + +export default class EventSystem extends System { + __internal_eventListeners: { [key in WorkspacesEvent]?: (() => void)[] } = {}; + + constructor(instance: Instance) { + super("event", instance); + + const minutelyTimer = setInterval(() => { + this.invoke(WorkspacesEvent.Minutely); + }, 60 * 1000); + + const quarterHourlyTimer = setInterval( + () => { + this.invoke(WorkspacesEvent.QuarterHourly); + }, + 15 * 60 * 1000, + ); + + const halfHourlyTimer = setInterval( + () => { + this.invoke(WorkspacesEvent.HalfHourly); + }, + 30 * 60 * 1000, + ); + + const hourlyTimer = setInterval( + () => { + this.invoke(WorkspacesEvent.Hourly); + }, + 60 * 60 * 1000, + ); + + const dailyTimer = setInterval( + () => { + this.invoke(WorkspacesEvent.Daily); + }, + 24 * 60 * 60 * 1000, + ); + + const weeklyTimer = setInterval( + () => { + this.invoke(WorkspacesEvent.Weekly); + }, + 7 * 24 * 60 * 60 * 1000, + ); + + this.on(WorkspacesEvent.BeforeShutdown, () => { + clearInterval(minutelyTimer); + clearInterval(quarterHourlyTimer); + clearInterval(halfHourlyTimer); + clearInterval(hourlyTimer); + clearInterval(dailyTimer); + clearInterval(weeklyTimer); + }); + } + + on(eventType: WorkspacesEvent, cb: () => void) { + if (!this.__internal_eventListeners[eventType]) { + this.__internal_eventListeners[eventType] = []; + } + + this.__internal_eventListeners[eventType].push(cb); + + return this; + } + + invoke(eventType: WorkspacesEvent) { + const events = this.__internal_eventListeners[eventType]; + + if (!events) { + return this; + } + + for (const event of events) { + event(); + } + + return this; + } + + override async startup(): Promise { + return true; + } +} diff --git a/instance/src/systems/filesystem.ts b/instance/src/systems/filesystem.ts index 5353daa..ab55dd5 100644 --- a/instance/src/systems/filesystem.ts +++ b/instance/src/systems/filesystem.ts @@ -1,241 +1,241 @@ -import fs from "node:fs"; -import path from "node:path"; -import type { Instance } from "../index.ts"; -import System from "../system.ts"; -import { WorkspacesEvent } from "./events.ts"; - -export default class FilesystemSystem extends System { - readonly SRC_ROOT = path.resolve("./instance/src/"); - readonly FS_ROOT = path.resolve("./fs/"); - readonly CACHE_PATH = path.join(this.FS_ROOT, "cache"); - readonly SYSTEM_PATH = path.join(this.FS_ROOT, "system"); - readonly AUTOINSTALL_PATH = path.join(process.cwd(), "autoinstall"); - - _internalAssets: Map; - _internalAssetPaths: Map; - - constructor(instance: Instance) { - super("filesystem", instance); - - if (!fs.existsSync(this.FS_ROOT)) { - fs.mkdirSync(this.FS_ROOT, { recursive: true }); - } - - if (!fs.existsSync(this.SYSTEM_PATH)) { - fs.mkdirSync(this.SYSTEM_PATH, { - recursive: true, - }); - } - - if (!fs.existsSync(this.CACHE_PATH)) { - fs.mkdirSync(this.CACHE_PATH, { recursive: true }); - } - - if (!fs.existsSync(path.join(this.FS_ROOT, "assets/login"))) { - fs.mkdirSync(path.join(this.FS_ROOT, "assets/login"), { - recursive: true, - }); - } - - if (!fs.existsSync(path.join(this.FS_ROOT, "assets/login/banner.png"))) { - if (!fs.existsSync(path.join(this.AUTOINSTALL_PATH, "assets/login/banner.png"))) { - fs.cpSync(path.join(this.SRC_ROOT, "assets/placeholder/banner.png"), path.join(this.FS_ROOT, "assets/login/banner.png")); - } else { - fs.cpSync(path.join(this.AUTOINSTALL_PATH, "assets/login/banner.png"), path.join(this.FS_ROOT, "assets/login/banner.png")); - } - } - - if (!fs.existsSync(path.join(this.FS_ROOT, "assets/login/background.png"))) { - fs.cpSync(path.join(this.SRC_ROOT, "assets/wallpapers/pexels-steve-29708303.jpg"), path.join(this.FS_ROOT, "assets/login/background.png")); - } - - if (!fs.existsSync(path.join(this.SYSTEM_PATH, "fs_template_files"))) { - fs.mkdirSync(path.join(this.SYSTEM_PATH, "fs_template_files")); - fs.cpSync(path.join(this.SRC_ROOT, "assets/fs_template_files/"), path.join(this.SYSTEM_PATH, "fs_template_files"), { recursive: true }); - } - - if (!fs.existsSync(path.join(this.SYSTEM_PATH, "vite"))) { - fs.mkdirSync(path.join(this.SYSTEM_PATH, "vite")); - } - - this._internalAssets = new Map(); - this._internalAssetPaths = new Map(); - } - - getApplicationSrc(applicationId: string) { - console.log(this.instance.sys.applications.availableApplications.find((a) => a.manifest?.id === applicationId)?.path); - - return this.instance.sys.applications.availableApplications.find((a) => a.manifest?.id === applicationId)?.path; - } - - // Create a directory if it does not already exist - // @returns {true} if created - // @returns {false} if already exists - async createDirectoryIfNotExists(path: string): Promise { - if ( - await fs.promises - .access(path) - .then(() => true) - .catch(() => false) - ) { - return false; - } - - await fs.promises.mkdir(path, { recursive: true }); - - return true; - } - - getFileType(path: string) { - const extension = path.split(".").pop(); - - switch (extension) { - case "avif": - case "webp": - case "jpg": - case "jpeg": - case "png": - case "gif": - return "image"; - case "txt": - case "json": - case "js": - case "ts": - case "tsx": - case "scss": - case "sass": - case "yml": - case "yaml": - case "xml": - case "py": - case "toml": - case "rs": - case "html": - case "htm": - case "css": - case "jsm": - case "tsm": - case "tsc": - case "jsc": - case "sql": - case "lock": - return "plaintext"; - } - - this.log.warning(`Unknown file format: '${path}' ext: '${extension}'`); - - return undefined; - } - - // returns an endpoint where the asset located at the provided path can be loaded from on the client - // defaults to 3hrs validity - serveFile(userId: number, fsPath: string, isPublic: boolean = false, dontCachePath = false, validMs: number = 21600000): string { - if (!dontCachePath) { - const existingAsset = this._internalAssetPaths.get(fsPath); - - if (existingAsset) { - this._internalAssets.get(existingAsset)!.validUntil = Date.now() + validMs; - - return `/api/asset/raw/${existingAsset}`; - } - } - - const assetId = crypto.randomUUID(); - - this._internalAssets.set(assetId, { - path: fsPath, - userId: userId, - validUntil: Date.now() + validMs, - public: isPublic, - }); - this._internalAssetPaths.set(fsPath, assetId); - - this.log.info(`Serving asset at '${fsPath}' as '${assetId}'`); - - return `/api/asset/raw/${assetId}`; - } - - // TODO: properly implement this instead of this hack. - async getUserPermissions(userId: number, fsPath: string): Promise<{ read: boolean; write: boolean }> { - const user = (await this.instance.sys.users.getUserById(userId))!; - - if (await user.isAdministrator()) - return { - read: true, - write: true, - }; - - if (fsPath.startsWith(path.join(this.FS_ROOT, `/users/${userId}`))) - return { - read: true, - write: true, - }; - - const db = this.instance.sys.database.postgres(); - - const userGroups = (await user.getGroups()) || []; - const userIdArray = userId ? [userId.toString()] : []; - - const validUserGroups = userGroups.filter(Boolean); - - return { - read: false, - write: false, - }; - - // const permissions = await db` - // SELECT - // EXISTS( - // SELECT 1 - // FROM public.filesystem_permission_overrides - // WHERE file_path = ${fsPath} - // AND read_permission_groups && ${validUserGroups}::TEXT[] - // OR read_permission_users @> ARRAY[${userIdArray}::TEXT] - // ) AS read_permission, - // EXISTS( - // SELECT 1 - // FROM public.filesystem_permission_overrides - // WHERE file_path = ${fsPath} - // AND write_permission_groups && ${validUserGroups}::TEXT[] - // OR write_permission_users @> ARRAY[${userIdArray}::TEXT] - // ) AS write_permission - // `; - // return { - // read: permissions[0].read_permission, - // write: permissions[0].write_permission, - // }; - } - - getUserHomeDirectory(userId: number): string { - return path.join(this.FS_ROOT, `/users/${userId}`); - } - - override async startup(): Promise { - await super.startup(); - - this.instance.sys.event.on(WorkspacesEvent.BeforeStartupComplete, async () => { - const db = this.instance.sys.database.postgres(); - - await db`CREATE TABLE IF NOT EXISTS filesystem_permission_overrides ( - file_path TEXT, - recursive BOOL, - read_permission_groups TEXT[], - read_permission_users TEXT[], - write_permission_groups TEXT[], - write_permission_users TEXT[], - owner TEXT[] -)`; - - if (!this.instance.sys.configuration.isDevMode) { - if (fs.existsSync(this.CACHE_PATH)) { - fs.rmSync(this.CACHE_PATH, { recursive: true }); - fs.mkdirSync(this.CACHE_PATH, { recursive: true }); - } - } else { - this.log.warning("Cache was not cleared as we are running in devMode"); - } - }); - - return true; - } -} +import fs from "node:fs"; +import path from "node:path"; +import type { Instance } from "../index.ts"; +import System from "../system.ts"; +import { WorkspacesEvent } from "./events.ts"; + +export default class FilesystemSystem extends System { + readonly SRC_ROOT = path.resolve("./instance/src/"); + readonly FS_ROOT = path.resolve("./fs/"); + readonly CACHE_PATH = path.join(this.FS_ROOT, "cache"); + readonly SYSTEM_PATH = path.join(this.FS_ROOT, "system"); + readonly AUTOINSTALL_PATH = path.join(process.cwd(), "autoinstall"); + + _internalAssets: Map; + _internalAssetPaths: Map; + + constructor(instance: Instance) { + super("filesystem", instance); + + if (!fs.existsSync(this.FS_ROOT)) { + fs.mkdirSync(this.FS_ROOT, { recursive: true }); + } + + if (!fs.existsSync(this.SYSTEM_PATH)) { + fs.mkdirSync(this.SYSTEM_PATH, { + recursive: true, + }); + } + + if (!fs.existsSync(this.CACHE_PATH)) { + fs.mkdirSync(this.CACHE_PATH, { recursive: true }); + } + + if (!fs.existsSync(path.join(this.FS_ROOT, "assets/login"))) { + fs.mkdirSync(path.join(this.FS_ROOT, "assets/login"), { + recursive: true, + }); + } + + if (!fs.existsSync(path.join(this.FS_ROOT, "assets/login/banner.png"))) { + if (!fs.existsSync(path.join(this.AUTOINSTALL_PATH, "assets/login/banner.png"))) { + fs.cpSync(path.join(this.SRC_ROOT, "assets/placeholder/banner.png"), path.join(this.FS_ROOT, "assets/login/banner.png")); + } else { + fs.cpSync(path.join(this.AUTOINSTALL_PATH, "assets/login/banner.png"), path.join(this.FS_ROOT, "assets/login/banner.png")); + } + } + + if (!fs.existsSync(path.join(this.FS_ROOT, "assets/login/background.png"))) { + fs.cpSync(path.join(this.SRC_ROOT, "assets/wallpapers/pexels-steve-29708303.jpg"), path.join(this.FS_ROOT, "assets/login/background.png")); + } + + if (!fs.existsSync(path.join(this.SYSTEM_PATH, "fs_template_files"))) { + fs.mkdirSync(path.join(this.SYSTEM_PATH, "fs_template_files")); + fs.cpSync(path.join(this.SRC_ROOT, "assets/fs_template_files/"), path.join(this.SYSTEM_PATH, "fs_template_files"), { recursive: true }); + } + + if (!fs.existsSync(path.join(this.SYSTEM_PATH, "vite"))) { + fs.mkdirSync(path.join(this.SYSTEM_PATH, "vite")); + } + + this._internalAssets = new Map(); + this._internalAssetPaths = new Map(); + } + + getApplicationSrc(applicationId: string) { + console.log(this.instance.sys.applications.availableApplications.find((a) => a.manifest?.id === applicationId)?.path); + + return this.instance.sys.applications.availableApplications.find((a) => a.manifest?.id === applicationId)?.path; + } + + // Create a directory if it does not already exist + // @returns {true} if created + // @returns {false} if already exists + async createDirectoryIfNotExists(path: string): Promise { + if ( + await fs.promises + .access(path) + .then(() => true) + .catch(() => false) + ) { + return false; + } + + await fs.promises.mkdir(path, { recursive: true }); + + return true; + } + + getFileType(path: string) { + const extension = path.split(".").pop(); + + switch (extension) { + case "avif": + case "webp": + case "jpg": + case "jpeg": + case "png": + case "gif": + return "image"; + case "txt": + case "json": + case "js": + case "ts": + case "tsx": + case "scss": + case "sass": + case "yml": + case "yaml": + case "xml": + case "py": + case "toml": + case "rs": + case "html": + case "htm": + case "css": + case "jsm": + case "tsm": + case "tsc": + case "jsc": + case "sql": + case "lock": + return "plaintext"; + } + + this.log.warning(`Unknown file format: '${path}' ext: '${extension}'`); + + return undefined; + } + + // returns an endpoint where the asset located at the provided path can be loaded from on the client + // defaults to 3hrs validity + serveFile(userId: number, fsPath: string, isPublic: boolean = false, dontCachePath = false, validMs: number = 21600000): string { + if (!dontCachePath) { + const existingAsset = this._internalAssetPaths.get(fsPath); + + if (existingAsset) { + this._internalAssets.get(existingAsset)!.validUntil = Date.now() + validMs; + + return `/api/asset/raw/${existingAsset}`; + } + } + + const assetId = crypto.randomUUID(); + + this._internalAssets.set(assetId, { + path: fsPath, + userId: userId, + validUntil: Date.now() + validMs, + public: isPublic, + }); + this._internalAssetPaths.set(fsPath, assetId); + + this.log.info(`Serving asset at '${fsPath}' as '${assetId}'`); + + return `/api/asset/raw/${assetId}`; + } + + // TODO: properly implement this instead of this hack. + async getUserPermissions(userId: number, fsPath: string): Promise<{ read: boolean; write: boolean }> { + const user = (await this.instance.sys.users.getUserById(userId))!; + + if (await user.isAdministrator()) + return { + read: true, + write: true, + }; + + if (fsPath.startsWith(path.join(this.FS_ROOT, `/users/${userId}`))) + return { + read: true, + write: true, + }; + + const db = this.instance.sys.database.postgres(); + + const userGroups = (await user.getGroups()) || []; + const userIdArray = userId ? [userId.toString()] : []; + + const validUserGroups = userGroups.filter(Boolean); + + return { + read: false, + write: false, + }; + + // const permissions = await db` + // SELECT + // EXISTS( + // SELECT 1 + // FROM public.filesystem_permission_overrides + // WHERE file_path = ${fsPath} + // AND read_permission_groups && ${validUserGroups}::TEXT[] + // OR read_permission_users @> ARRAY[${userIdArray}::TEXT] + // ) AS read_permission, + // EXISTS( + // SELECT 1 + // FROM public.filesystem_permission_overrides + // WHERE file_path = ${fsPath} + // AND write_permission_groups && ${validUserGroups}::TEXT[] + // OR write_permission_users @> ARRAY[${userIdArray}::TEXT] + // ) AS write_permission + // `; + // return { + // read: permissions[0].read_permission, + // write: permissions[0].write_permission, + // }; + } + + getUserHomeDirectory(userId: number): string { + return path.join(this.FS_ROOT, `/users/${userId}`); + } + + override async startup(): Promise { + await super.startup(); + + this.instance.sys.event.on(WorkspacesEvent.BeforeStartupComplete, async () => { + const db = this.instance.sys.database.postgres(); + + await db`CREATE TABLE IF NOT EXISTS filesystem_permission_overrides ( + file_path TEXT, + recursive BOOL, + read_permission_groups TEXT[], + read_permission_users TEXT[], + write_permission_groups TEXT[], + write_permission_users TEXT[], + owner TEXT[] +)`; + + if (!this.instance.sys.configuration.isDevMode) { + if (fs.existsSync(this.CACHE_PATH)) { + fs.rmSync(this.CACHE_PATH, { recursive: true }); + fs.mkdirSync(this.CACHE_PATH, { recursive: true }); + } + } else { + this.log.warning("Cache was not cleared as we are running in devMode"); + } + }); + + return true; + } +} diff --git a/instance/src/systems/image.ts b/instance/src/systems/image.ts index 8e8a91f..ef4953a 100644 --- a/instance/src/systems/image.ts +++ b/instance/src/systems/image.ts @@ -1,185 +1,185 @@ -import * as nodePath from "node:path"; -import sharp from "sharp"; -import type { Instance } from "../index.ts"; -import System from "../system.ts"; - -export default class ImageSystem extends System { - _internalImages: Map< - string, - { - [resolution: string]: { - userId: number; - path: string; - validUntil: number; - public?: boolean; - resize?: { - dimensions: { width: number; height: number }; - changeFormatTo?: "avif" | "jpeg" | "png" | "webp"; - position?: "top" | "right top" | "right" | "right bottom" | "bottom" | "left bottom" | "left" | "left top" | "centre"; - fit?: "cover" | "contain" | "fill"; - background?: string; - }; - }; - } - >; - _internalImagePaths: Map; - - constructor(instance: Instance) { - super("image", instance); - - this._internalImages = new Map(); - this._internalImagePaths = new Map(); - } - - // returns an endpoint where the image located at the provided path can be loaded from on the client - // defaults to 3hrs validity - - async serveImage( - userId: number, - path: string, - options?: { - isPublic?: boolean; - dontCachePath?: boolean; - validMs?: number; - } & ( - | { - crop?: { - x: number; - y: number; - width: number; - height: number; - }; - } - | { - resize?: { - dimensions: - | { width: number; height: number } - | ((originalSize: { width: number; height: number }) => { - width: number; - height: number; - }); - changeFormatTo?: "avif" | "jpeg" | "png" | "webp"; - position?: "top" | "right top" | "right" | "right bottom" | "bottom" | "left bottom" | "left" | "left top" | "centre"; - fit?: "cover" | "contain" | "fill"; - background?: string; - }; - } - ), - ): Promise { - const opts = { - isPublic: options?.isPublic ?? false, - dontCachePath: options?.dontCachePath ?? false, - validMs: options?.validMs ?? 21600000, - crop: options && "crop" in options ? options.crop : undefined, - resize: options && "resize" in options ? options.resize : undefined, - }; - - if (opts.resize?.dimensions) { - if (typeof opts.resize.dimensions === "function") { - const sharpInstance = sharp(path); - const metadata = await sharpInstance.metadata(); - opts.resize.dimensions = opts.resize.dimensions({ - width: metadata.width ?? 0, - height: metadata.height ?? 0, - }); - } - } - - let cropKey = ""; - if (opts.crop) { - cropKey = `crop_${opts.crop.x}_${opts.crop.y}_${opts.crop.width}_${opts.crop.height}`; - } - - let requestResolution = "raw"; - if (opts.resize?.dimensions && typeof opts.resize.dimensions !== "function") { - requestResolution = `${opts.resize.dimensions.width}x${opts.resize.dimensions.height}`; - } - if (cropKey) { - requestResolution += `_${cropKey}`; - } - - if (!opts.dontCachePath) { - const existingImageId = this._internalImagePaths.get(path); - if (existingImageId) { - const existingImage = this._internalImages.get(existingImageId); - if (existingImage) { - const existingImageOfResolution = existingImage[requestResolution]; - if (existingImageOfResolution) { - existingImageOfResolution.validUntil = Date.now() + opts.validMs; - return `/api/asset/image/${existingImageId}/${requestResolution}`; - } - } - } - } - - const imageId = crypto.randomUUID(); - - this._internalImages.set(imageId, { - [requestResolution]: { - path: path, - userId: userId, - validUntil: Date.now() + opts.validMs, - public: opts.isPublic, - resize: { - dimensions: opts.resize?.dimensions as { - width: number; - height: number; - }, - changeFormatTo: opts.resize?.changeFormatTo ?? "jpeg", - position: opts.resize?.position ?? "top", - fit: opts.resize?.fit ?? "cover", - background: opts.resize?.background ?? "white", - }, - }, - }); - - this._internalImagePaths.set(path, imageId); - - this.log.info(`Serving image at '${nodePath.relative(this.instance.sys.filesystem.FS_ROOT, path)}' as '${imageId}'`); - - return `/api/asset/image/${imageId}/${requestResolution}`; - } - - async resizeImage( - inputPath: string, - outputPath: string, - dimensions: - | { width: number; height: number } - | ((originalSize: { width: number; height: number }) => { - width: number; - height: number; - }), - options?: { - changeFormatTo?: "avif" | "jpeg" | "png" | "webp"; - position?: "top" | "right top" | "right" | "right bottom" | "bottom" | "left bottom" | "left" | "left top" | "centre"; - fit?: "cover" | "contain" | "fill"; - background?: string; - }, - ): Promise { - const sharpInstance = sharp(inputPath); - - const originalDimensions = await sharpInstance.metadata(); - - if (typeof dimensions === "function") { - dimensions = dimensions(originalDimensions); - } - - sharpInstance.resize(dimensions.width, dimensions.height, { - withoutEnlargement: true, - position: options?.position, - fit: options?.fit, - background: options?.background, - kernel: originalDimensions.width / 2 > dimensions.width || originalDimensions.height / 2 > dimensions.height ? "cubic" : "mks2021", - }); - - if (options) { - if (options.changeFormatTo) { - sharpInstance.toFormat(options.changeFormatTo, { progressive: true }); - } - } - - await sharpInstance.toFile(outputPath); - - return true; - } -} +import * as nodePath from "node:path"; +import sharp from "sharp"; +import type { Instance } from "../index.ts"; +import System from "../system.ts"; + +export default class ImageSystem extends System { + _internalImages: Map< + string, + { + [resolution: string]: { + userId: number; + path: string; + validUntil: number; + public?: boolean; + resize?: { + dimensions: { width: number; height: number }; + changeFormatTo?: "avif" | "jpeg" | "png" | "webp"; + position?: "top" | "right top" | "right" | "right bottom" | "bottom" | "left bottom" | "left" | "left top" | "centre"; + fit?: "cover" | "contain" | "fill"; + background?: string; + }; + }; + } + >; + _internalImagePaths: Map; + + constructor(instance: Instance) { + super("image", instance); + + this._internalImages = new Map(); + this._internalImagePaths = new Map(); + } + + // returns an endpoint where the image located at the provided path can be loaded from on the client + // defaults to 3hrs validity + + async serveImage( + userId: number, + path: string, + options?: { + isPublic?: boolean; + dontCachePath?: boolean; + validMs?: number; + } & ( + | { + crop?: { + x: number; + y: number; + width: number; + height: number; + }; + } + | { + resize?: { + dimensions: + | { width: number; height: number } + | ((originalSize: { width: number; height: number }) => { + width: number; + height: number; + }); + changeFormatTo?: "avif" | "jpeg" | "png" | "webp"; + position?: "top" | "right top" | "right" | "right bottom" | "bottom" | "left bottom" | "left" | "left top" | "centre"; + fit?: "cover" | "contain" | "fill"; + background?: string; + }; + } + ), + ): Promise { + const opts = { + isPublic: options?.isPublic ?? false, + dontCachePath: options?.dontCachePath ?? false, + validMs: options?.validMs ?? 21600000, + crop: options && "crop" in options ? options.crop : undefined, + resize: options && "resize" in options ? options.resize : undefined, + }; + + if (opts.resize?.dimensions) { + if (typeof opts.resize.dimensions === "function") { + const sharpInstance = sharp(path); + const metadata = await sharpInstance.metadata(); + opts.resize.dimensions = opts.resize.dimensions({ + width: metadata.width ?? 0, + height: metadata.height ?? 0, + }); + } + } + + let cropKey = ""; + if (opts.crop) { + cropKey = `crop_${opts.crop.x}_${opts.crop.y}_${opts.crop.width}_${opts.crop.height}`; + } + + let requestResolution = "raw"; + if (opts.resize?.dimensions && typeof opts.resize.dimensions !== "function") { + requestResolution = `${opts.resize.dimensions.width}x${opts.resize.dimensions.height}`; + } + if (cropKey) { + requestResolution += `_${cropKey}`; + } + + if (!opts.dontCachePath) { + const existingImageId = this._internalImagePaths.get(path); + if (existingImageId) { + const existingImage = this._internalImages.get(existingImageId); + if (existingImage) { + const existingImageOfResolution = existingImage[requestResolution]; + if (existingImageOfResolution) { + existingImageOfResolution.validUntil = Date.now() + opts.validMs; + return `/api/asset/image/${existingImageId}/${requestResolution}`; + } + } + } + } + + const imageId = crypto.randomUUID(); + + this._internalImages.set(imageId, { + [requestResolution]: { + path: path, + userId: userId, + validUntil: Date.now() + opts.validMs, + public: opts.isPublic, + resize: { + dimensions: opts.resize?.dimensions as { + width: number; + height: number; + }, + changeFormatTo: opts.resize?.changeFormatTo ?? "jpeg", + position: opts.resize?.position ?? "top", + fit: opts.resize?.fit ?? "cover", + background: opts.resize?.background ?? "white", + }, + }, + }); + + this._internalImagePaths.set(path, imageId); + + this.log.info(`Serving image at '${nodePath.relative(this.instance.sys.filesystem.FS_ROOT, path)}' as '${imageId}'`); + + return `/api/asset/image/${imageId}/${requestResolution}`; + } + + async resizeImage( + inputPath: string, + outputPath: string, + dimensions: + | { width: number; height: number } + | ((originalSize: { width: number; height: number }) => { + width: number; + height: number; + }), + options?: { + changeFormatTo?: "avif" | "jpeg" | "png" | "webp"; + position?: "top" | "right top" | "right" | "right bottom" | "bottom" | "left bottom" | "left" | "left top" | "centre"; + fit?: "cover" | "contain" | "fill"; + background?: string; + }, + ): Promise { + const sharpInstance = sharp(inputPath); + + const originalDimensions = await sharpInstance.metadata(); + + if (typeof dimensions === "function") { + dimensions = dimensions(originalDimensions); + } + + sharpInstance.resize(dimensions.width, dimensions.height, { + withoutEnlargement: true, + position: options?.position, + fit: options?.fit, + background: options?.background, + kernel: originalDimensions.width / 2 > dimensions.width || originalDimensions.height / 2 > dimensions.height ? "cubic" : "mks2021", + }); + + if (options) { + if (options.changeFormatTo) { + sharpInstance.toFormat(options.changeFormatTo, { progressive: true }); + } + } + + await sharpInstance.toFile(outputPath); + + return true; + } +} diff --git a/instance/src/systems/notifications.ts b/instance/src/systems/notifications.ts index 4e3fae9..ab2a932 100644 --- a/instance/src/systems/notifications.ts +++ b/instance/src/systems/notifications.ts @@ -1,88 +1,88 @@ -import EventEmitter from "node:events"; -import type { Instance } from "../index.ts"; -import System from "../system.ts"; - -export enum WorkspacesNoticeType { - Login, - Signup, -} - -export enum WorkspacesNotificationPriority { - Normal, - Important, - Urgent, -} - -export interface WorkspacesNotificationContent { - title: string; - icon?: string; - body: string; -} - -export enum WorkspacesNotificationEventEmitterEvent { - SendNotification = "send_notification", -} - -export interface WorkspacesNotificationOptions { - buttons: { id: string; label: string; type: "filled" | "tonal" }[]; -} - -export interface WorkspacesNotificationOptionsCallbacks { - onButton(optionId: string): void | { - action: { type: "navigate"; value: string } | { type: "reload" }; - }; -} - -export interface WorkspacesNotification { - recipient: number; - sourceId: string; - priority: WorkspacesNotificationPriority; - content: WorkspacesNotificationContent; - uuid: string; - options?: WorkspacesNotificationOptions; - optionsCallbacks?: WorkspacesNotificationOptionsCallbacks; -} - -export default class NotificationsSystem extends System { - eventEmitter: EventEmitter; - - constructor(instance: Instance) { - super("notifications", instance); - - this.eventEmitter = new EventEmitter(); - } - - // TODO: implement this - // applyNotice(targetUserId: number, noticeType: WorkspacesNoticeType[], noticeTitle: string, noticeBody: string) { - // this.log.warning("Notices are Unimplemented"); - // return this; - // } - - send( - recipient: number, - sourceId: string, - priority: WorkspacesNotificationPriority, - content: WorkspacesNotificationContent, - options?: WorkspacesNotificationOptions, - optionsCallbacks?: WorkspacesNotificationOptionsCallbacks, - ) { - this.eventEmitter.emit(WorkspacesNotificationEventEmitterEvent.SendNotification, { - recipient, - sourceId, - priority, - content, - uuid: crypto.randomUUID(), - options: { - buttons: options?.buttons || [], - }, - optionsCallbacks: optionsCallbacks, - } satisfies WorkspacesNotification); - - return this; - } - - override async startup(): Promise { - this.log.info("Starting up..."); - return true; - } -} +import EventEmitter from "node:events"; +import type { Instance } from "../index.ts"; +import System from "../system.ts"; + +export enum WorkspacesNoticeType { + Login, + Signup, +} + +export enum WorkspacesNotificationPriority { + Normal, + Important, + Urgent, +} + +export interface WorkspacesNotificationContent { + title: string; + icon?: string; + body: string; +} + +export enum WorkspacesNotificationEventEmitterEvent { + SendNotification = "send_notification", +} + +export interface WorkspacesNotificationOptions { + buttons: { id: string; label: string; type: "filled" | "tonal" }[]; +} + +export interface WorkspacesNotificationOptionsCallbacks { + onButton(optionId: string): void | { + action: { type: "navigate"; value: string } | { type: "reload" }; + }; +} + +export interface WorkspacesNotification { + recipient: number; + sourceId: string; + priority: WorkspacesNotificationPriority; + content: WorkspacesNotificationContent; + uuid: string; + options?: WorkspacesNotificationOptions; + optionsCallbacks?: WorkspacesNotificationOptionsCallbacks; +} + +export default class NotificationsSystem extends System { + eventEmitter: EventEmitter; + + constructor(instance: Instance) { + super("notifications", instance); + + this.eventEmitter = new EventEmitter(); + } + + // TODO: implement this + // applyNotice(targetUserId: number, noticeType: WorkspacesNoticeType[], noticeTitle: string, noticeBody: string) { + // this.log.warning("Notices are Unimplemented"); + // return this; + // } + + send( + recipient: number, + sourceId: string, + priority: WorkspacesNotificationPriority, + content: WorkspacesNotificationContent, + options?: WorkspacesNotificationOptions, + optionsCallbacks?: WorkspacesNotificationOptionsCallbacks, + ) { + this.eventEmitter.emit(WorkspacesNotificationEventEmitterEvent.SendNotification, { + recipient, + sourceId, + priority, + content, + uuid: crypto.randomUUID(), + options: { + buttons: options?.buttons || [], + }, + optionsCallbacks: optionsCallbacks, + } satisfies WorkspacesNotification); + + return this; + } + + override async startup(): Promise { + this.log.info("Starting up..."); + return true; + } +} diff --git a/instance/src/systems/reverseProxy.ts b/instance/src/systems/reverseProxy.ts index 96ab357..92d2d1f 100644 --- a/instance/src/systems/reverseProxy.ts +++ b/instance/src/systems/reverseProxy.ts @@ -1,66 +1,66 @@ -import { promises as fs } from "node:fs"; -import path from "node:path"; -import type { Instance } from "../index.ts"; -import System from "../system.ts"; - -export default class ReverseProxySystem extends System { - proxies: { from: string; to: string; alternateDomain?: string }[] = []; - - constructor(instance: Instance) { - super("reverse_proxy", instance); - } - - addNewProxy(from: string, to: string, alternateDomain?: string) { - this.proxies.push({ from, to, alternateDomain }); - - return this; - } - - async generateCaddyFile() { - const OUTPUT_PATH = path.join(this.instance.sys.filesystem.SYSTEM_PATH, "Caddyfile"); - - let outputString = ""; - const domainOutputStrings: { [domain: string]: string } = {}; - - for (const proxy of this.proxies) { - if (!domainOutputStrings[proxy.alternateDomain || "default"]) domainOutputStrings[proxy.alternateDomain || "default"] = ""; - - domainOutputStrings[proxy.alternateDomain || "default"] += ` reverse_proxy ${proxy.from !== "" ? `${proxy.from} ` : ""}${proxy.to} { - header_up X-Real-IP {remote} - header_up X-Forwarded-For {remote} - } -`; - } - - for (const domain of Object.keys(domainOutputStrings)) { - let actualDomain = domain; - - if (actualDomain === "default") { - actualDomain = this.instance.sys.configuration.proxyUrl; - } - - outputString += `${actualDomain} { -${domainOutputStrings[domain]}} -`; - } - - await fs.writeFile( - OUTPUT_PATH, - `## Begin OnlineWorkspace ----- -${outputString}## End OnlineWorkspace -----`, - ); - - return this; - } - - override async startup(): Promise { - // the default backend - this.addNewProxy("/api/*", "http://localhost:3563"); - // web ui - this.addNewProxy("", "http://localhost:5173"); - - await this.generateCaddyFile(); - - return true; - } -} +import { promises as fs } from "node:fs"; +import path from "node:path"; +import type { Instance } from "../index.ts"; +import System from "../system.ts"; + +export default class ReverseProxySystem extends System { + proxies: { from: string; to: string; alternateDomain?: string }[] = []; + + constructor(instance: Instance) { + super("reverse_proxy", instance); + } + + addNewProxy(from: string, to: string, alternateDomain?: string) { + this.proxies.push({ from, to, alternateDomain }); + + return this; + } + + async generateCaddyFile() { + const OUTPUT_PATH = path.join(this.instance.sys.filesystem.SYSTEM_PATH, "Caddyfile"); + + let outputString = ""; + const domainOutputStrings: { [domain: string]: string } = {}; + + for (const proxy of this.proxies) { + if (!domainOutputStrings[proxy.alternateDomain || "default"]) domainOutputStrings[proxy.alternateDomain || "default"] = ""; + + domainOutputStrings[proxy.alternateDomain || "default"] += ` reverse_proxy ${proxy.from !== "" ? `${proxy.from} ` : ""}${proxy.to} { + header_up X-Real-IP {remote} + header_up X-Forwarded-For {remote} + } +`; + } + + for (const domain of Object.keys(domainOutputStrings)) { + let actualDomain = domain; + + if (actualDomain === "default") { + actualDomain = this.instance.sys.configuration.proxyUrl; + } + + outputString += `${actualDomain} { +${domainOutputStrings[domain]}} +`; + } + + await fs.writeFile( + OUTPUT_PATH, + `## Begin OnlineWorkspace ----- +${outputString}## End OnlineWorkspace -----`, + ); + + return this; + } + + override async startup(): Promise { + // the default backend + this.addNewProxy("/api/*", "http://localhost:3563"); + // web ui + this.addNewProxy("", "http://localhost:5173"); + + await this.generateCaddyFile(); + + return true; + } +} diff --git a/instance/src/systems/settings.ts b/instance/src/systems/settings.ts index f1e80ce..4356be5 100644 --- a/instance/src/systems/settings.ts +++ b/instance/src/systems/settings.ts @@ -1,98 +1,98 @@ -import type { Instance } from "../index.ts"; -import System from "../system.ts"; -import { ApplicationSetting, type GlobalApplicationSetting } from "./settings/applicationSetting/applicationSetting.ts"; - -export default class SettingsSystem extends System { - applicationSettings: { - [applicationId: string]: (ApplicationSetting | GlobalApplicationSetting)[]; - }; - - constructor(instance: Instance) { - super("settings", instance); - - this.applicationSettings = {}; - } - - async getUserSettings(userId: number): Promise> { - const db = this.instance.sys.database.postgres(); - - return (await db`SELECT settings FROM public.users WHERE id = ${userId}`)?.[0]?.settings as Record; - } - - async getUserApplicationSetting>( - userId: number, - applicationId: string, - settingId: string, - ): Promise { - return ( - (await this.applicationSettings[applicationId].find((s) => s.id === settingId)?.onValueChange(userId)) ?? - this.applicationSettings[applicationId].find((s) => s.id === settingId)?.defaultValue - ); - } - - async setUserApplicationSetting(userId: number, applicationId: string, settingId: string, value: T): Promise { - const applicationSetting = this.applicationSettings[applicationId].find((s) => s.id === settingId); - - if (!applicationSetting) return false; - - if (applicationSetting instanceof ApplicationSetting) { - await applicationSetting?.setValue(userId, value); - return true; - } else { - return false; - } - } - - async setUserSettings(userId: number, settings: Record): Promise { - const db = this.instance.sys.database.postgres(); - - await db`UPDATE public.users SET settings = ${settings} WHERE id = ${userId}`; - - return true; - } - - async getGlobalSetting(settingId: string): Promise { - const db = this.instance.sys.database.postgres(); - - return (await db`SELECT value FROM public.global_settings WHERE key = ${settingId}`)?.[0]?.value; - } - - async setGlobalSetting(settingId: string, value: any): Promise { - const db = this.instance.sys.database.postgres(); - - await db`INSERT INTO public.global_settings (key, value) VALUES (${settingId}, ${value}) ON CONFLICT (key) DO UPDATE SET value = ${value};`; - - return true; - } - - async getGlobalSettings(): Promise> { - const db = this.instance.sys.database.postgres(); - - return (await db`SELECT * FROM public.global_settings`)?.[0]?.settings as Record; - } - - registerApplicationSetting | GlobalApplicationSetting>(setting: Setting) { - if (!this.applicationSettings[setting.applicationId]) { - this.applicationSettings[setting.applicationId] = []; - } - - setting.instance = this.instance; - this.log.info(`Setting '${setting.id}' was registered for application '${setting.applicationId}'`); - this.applicationSettings[setting.applicationId].push(setting); - - return this; - } - - override async startup(): Promise { - await super.startup(); - - const db = this.instance.sys.database.postgres(); - - await db`CREATE TABLE IF NOT EXISTS global_settings ( - key TEXT, - value TEXT - )`; - - return true; - } -} +import type { Instance } from "../index.ts"; +import System from "../system.ts"; +import { ApplicationSetting, type GlobalApplicationSetting } from "./settings/applicationSetting/applicationSetting.ts"; + +export default class SettingsSystem extends System { + applicationSettings: { + [applicationId: string]: (ApplicationSetting | GlobalApplicationSetting)[]; + }; + + constructor(instance: Instance) { + super("settings", instance); + + this.applicationSettings = {}; + } + + async getUserSettings(userId: number): Promise> { + const db = this.instance.sys.database.postgres(); + + return (await db`SELECT settings FROM public.users WHERE id = ${userId}`)?.[0]?.settings as Record; + } + + async getUserApplicationSetting>( + userId: number, + applicationId: string, + settingId: string, + ): Promise { + return ( + (await this.applicationSettings[applicationId].find((s) => s.id === settingId)?.onValueChange(userId)) ?? + this.applicationSettings[applicationId].find((s) => s.id === settingId)?.defaultValue + ); + } + + async setUserApplicationSetting(userId: number, applicationId: string, settingId: string, value: T): Promise { + const applicationSetting = this.applicationSettings[applicationId].find((s) => s.id === settingId); + + if (!applicationSetting) return false; + + if (applicationSetting instanceof ApplicationSetting) { + await applicationSetting?.setValue(userId, value); + return true; + } else { + return false; + } + } + + async setUserSettings(userId: number, settings: Record): Promise { + const db = this.instance.sys.database.postgres(); + + await db`UPDATE public.users SET settings = ${settings} WHERE id = ${userId}`; + + return true; + } + + async getGlobalSetting(settingId: string): Promise { + const db = this.instance.sys.database.postgres(); + + return (await db`SELECT value FROM public.global_settings WHERE key = ${settingId}`)?.[0]?.value; + } + + async setGlobalSetting(settingId: string, value: any): Promise { + const db = this.instance.sys.database.postgres(); + + await db`INSERT INTO public.global_settings (key, value) VALUES (${settingId}, ${value}) ON CONFLICT (key) DO UPDATE SET value = ${value};`; + + return true; + } + + async getGlobalSettings(): Promise> { + const db = this.instance.sys.database.postgres(); + + return (await db`SELECT * FROM public.global_settings`)?.[0]?.settings as Record; + } + + registerApplicationSetting | GlobalApplicationSetting>(setting: Setting) { + if (!this.applicationSettings[setting.applicationId]) { + this.applicationSettings[setting.applicationId] = []; + } + + setting.instance = this.instance; + this.log.info(`Setting '${setting.id}' was registered for application '${setting.applicationId}'`); + this.applicationSettings[setting.applicationId].push(setting); + + return this; + } + + override async startup(): Promise { + await super.startup(); + + const db = this.instance.sys.database.postgres(); + + await db`CREATE TABLE IF NOT EXISTS global_settings ( + key TEXT, + value TEXT + )`; + + return true; + } +} diff --git a/instance/src/systems/settings/applicationSetting/applicationSetting.ts b/instance/src/systems/settings/applicationSetting/applicationSetting.ts index e5f36df..0b7dcd6 100644 --- a/instance/src/systems/settings/applicationSetting/applicationSetting.ts +++ b/instance/src/systems/settings/applicationSetting/applicationSetting.ts @@ -1,31 +1,31 @@ -import type { Instance } from "../../../index.ts"; - -export abstract class ApplicationSetting { - applicationId!: string; - id!: string; - displayName!: string; - defaultValue!: T; - type!: string; - instance!: Instance; - description!: string; - hidden!: boolean; - - abstract onValueChange(userId: number): Promise; - abstract setValue(userId: number, value: T): Promise; - abstract setHidden(hidden: boolean): this; -} - -export abstract class GlobalApplicationSetting { - applicationId!: string; - id!: string; - displayName!: string; - defaultValue!: T; - type!: string; - instance!: Instance; - description!: string; - hidden!: boolean; - - abstract onValueChange(): Promise; - abstract setValue(value: T): Promise; - abstract setHidden(hidden: boolean): this; -} +import type { Instance } from "../../../index.ts"; + +export abstract class ApplicationSetting { + applicationId!: string; + id!: string; + displayName!: string; + defaultValue!: T; + type!: string; + instance!: Instance; + description!: string; + hidden!: boolean; + + abstract onValueChange(userId: number): Promise; + abstract setValue(userId: number, value: T): Promise; + abstract setHidden(hidden: boolean): this; +} + +export abstract class GlobalApplicationSetting { + applicationId!: string; + id!: string; + displayName!: string; + defaultValue!: T; + type!: string; + instance!: Instance; + description!: string; + hidden!: boolean; + + abstract onValueChange(): Promise; + abstract setValue(value: T): Promise; + abstract setHidden(hidden: boolean): this; +} diff --git a/instance/src/systems/settings/applicationSetting/booleanSetting.ts b/instance/src/systems/settings/applicationSetting/booleanSetting.ts index ac88ecf..e1a3391 100644 --- a/instance/src/systems/settings/applicationSetting/booleanSetting.ts +++ b/instance/src/systems/settings/applicationSetting/booleanSetting.ts @@ -1,98 +1,98 @@ -import { ApplicationSetting, GlobalApplicationSetting } from "./applicationSetting.ts"; - -export class BooleanApplicationSetting extends ApplicationSetting { - constructor(applicationId: string, id: string, defaultValue: boolean) { - super(); - - this.applicationId = applicationId; - this.id = id; - this.defaultValue = defaultValue; - this.displayName = id; - this.type = "boolean"; - this.description = "No description provided"; - this.hidden = false; - } - - async setValue(userId: number, value: boolean) { - const userSettings = await this.instance.sys.settings.getUserSettings(userId); - - userSettings[`app:${this.applicationId}:${this.id}`] = value; - - await this.instance.sys.settings.setUserSettings(userId, userSettings); - - return true; - } - - async onValueChange(userId: number): Promise { - const userSettings = await this.instance.sys.settings.getUserSettings(userId); - - const settingValue = userSettings[`app:${this.applicationId}:${this.id}`]; - - if (settingValue === undefined) return this.defaultValue; - - return settingValue; - } - - setDisplayName(displayName: string): this { - this.displayName = displayName; - - return this; - } - - setDescription(description: string): this { - this.description = description; - - return this; - } - - setHidden(hidden: boolean) { - this.hidden = hidden; - - return this; - } -} - -export class GlobalBooleanApplicationSetting extends GlobalApplicationSetting { - constructor(applicationId: string, id: string, defaultValue: boolean) { - super(); - - this.applicationId = applicationId; - this.id = id; - this.defaultValue = defaultValue; - this.type = "boolean"; - this.description = "No description provided"; - this.hidden = false; - } - - async setValue(value: boolean) { - await this.instance.sys.settings.setGlobalSetting(`app:${this.applicationId}:${this.id}`, value); - - return true; - } - - async onValueChange(): Promise { - const settingValue = await this.instance.sys.settings.getGlobalSetting(`app:${this.applicationId}:${this.id}`); - - if (settingValue === undefined) return this.defaultValue; - - return settingValue; - } - - setDisplayName(displayName: string): this { - this.displayName = displayName; - - return this; - } - - setDescription(description: string): this { - this.description = description; - - return this; - } - - setHidden(hidden: boolean) { - this.hidden = hidden; - - return this; - } -} +import { ApplicationSetting, GlobalApplicationSetting } from "./applicationSetting.ts"; + +export class BooleanApplicationSetting extends ApplicationSetting { + constructor(applicationId: string, id: string, defaultValue: boolean) { + super(); + + this.applicationId = applicationId; + this.id = id; + this.defaultValue = defaultValue; + this.displayName = id; + this.type = "boolean"; + this.description = "No description provided"; + this.hidden = false; + } + + async setValue(userId: number, value: boolean) { + const userSettings = await this.instance.sys.settings.getUserSettings(userId); + + userSettings[`app:${this.applicationId}:${this.id}`] = value; + + await this.instance.sys.settings.setUserSettings(userId, userSettings); + + return true; + } + + async onValueChange(userId: number): Promise { + const userSettings = await this.instance.sys.settings.getUserSettings(userId); + + const settingValue = userSettings[`app:${this.applicationId}:${this.id}`]; + + if (settingValue === undefined) return this.defaultValue; + + return settingValue; + } + + setDisplayName(displayName: string): this { + this.displayName = displayName; + + return this; + } + + setDescription(description: string): this { + this.description = description; + + return this; + } + + setHidden(hidden: boolean) { + this.hidden = hidden; + + return this; + } +} + +export class GlobalBooleanApplicationSetting extends GlobalApplicationSetting { + constructor(applicationId: string, id: string, defaultValue: boolean) { + super(); + + this.applicationId = applicationId; + this.id = id; + this.defaultValue = defaultValue; + this.type = "boolean"; + this.description = "No description provided"; + this.hidden = false; + } + + async setValue(value: boolean) { + await this.instance.sys.settings.setGlobalSetting(`app:${this.applicationId}:${this.id}`, value); + + return true; + } + + async onValueChange(): Promise { + const settingValue = await this.instance.sys.settings.getGlobalSetting(`app:${this.applicationId}:${this.id}`); + + if (settingValue === undefined) return this.defaultValue; + + return settingValue; + } + + setDisplayName(displayName: string): this { + this.displayName = displayName; + + return this; + } + + setDescription(description: string): this { + this.description = description; + + return this; + } + + setHidden(hidden: boolean) { + this.hidden = hidden; + + return this; + } +} diff --git a/instance/src/systems/settings/applicationSetting/numberSetting.ts b/instance/src/systems/settings/applicationSetting/numberSetting.ts index 7776d05..94afbe8 100644 --- a/instance/src/systems/settings/applicationSetting/numberSetting.ts +++ b/instance/src/systems/settings/applicationSetting/numberSetting.ts @@ -1,97 +1,97 @@ -import { ApplicationSetting, GlobalApplicationSetting } from "./applicationSetting.ts"; - -export class NumberApplicationSetting extends ApplicationSetting { - constructor(applicationId: string, id: string, defaultValue: number) { - super(); - - this.applicationId = applicationId; - this.id = id; - this.defaultValue = defaultValue; - this.displayName = id; - this.type = "number"; - this.description = "No description provided"; - this.hidden = false; - } - - async setValue(userId: number, value: number) { - const userSettings = await this.instance.sys.settings.getUserSettings(userId); - - userSettings[`app:${this.applicationId}:${this.id}`] = value.toString(); - - await this.instance.sys.settings.setUserSettings(userId, userSettings); - - return true; - } - - async onValueChange(userId: number): Promise { - const userSettings = await this.instance.sys.settings.getUserSettings(userId); - const settingValue = userSettings[`app:${this.applicationId}:${this.id}`] as string | undefined; - - if (settingValue === undefined) return this.defaultValue; - - return Number(settingValue); - } - - setDisplayName(displayName: string): this { - this.displayName = displayName; - - return this; - } - - setDescription(description: string): this { - this.description = description; - - return this; - } - - setHidden(hidden: boolean) { - this.hidden = hidden; - - return this; - } -} - -export class GlobalNumberApplicationSetting extends GlobalApplicationSetting { - constructor(applicationId: string, id: string, defaultValue: number) { - super(); - - this.applicationId = applicationId; - this.id = id; - this.defaultValue = defaultValue; - this.type = "number"; - this.description = "No description provided"; - this.hidden = false; - } - - async setValue(value: number) { - await this.instance.sys.settings.setGlobalSetting(`app:${this.applicationId}:${this.id}`, value.toString()); - - return true; - } - - async onValueChange(): Promise { - const settingValue = await this.instance.sys.settings.getGlobalSetting(`app:${this.applicationId}:${this.id}`); - - if (settingValue === undefined) return this.defaultValue; - - return Number(settingValue); - } - - setDisplayName(displayName: string): this { - this.displayName = displayName; - - return this; - } - - setDescription(description: string): this { - this.description = description; - - return this; - } - - setHidden(hidden: boolean) { - this.hidden = hidden; - - return this; - } -} +import { ApplicationSetting, GlobalApplicationSetting } from "./applicationSetting.ts"; + +export class NumberApplicationSetting extends ApplicationSetting { + constructor(applicationId: string, id: string, defaultValue: number) { + super(); + + this.applicationId = applicationId; + this.id = id; + this.defaultValue = defaultValue; + this.displayName = id; + this.type = "number"; + this.description = "No description provided"; + this.hidden = false; + } + + async setValue(userId: number, value: number) { + const userSettings = await this.instance.sys.settings.getUserSettings(userId); + + userSettings[`app:${this.applicationId}:${this.id}`] = value.toString(); + + await this.instance.sys.settings.setUserSettings(userId, userSettings); + + return true; + } + + async onValueChange(userId: number): Promise { + const userSettings = await this.instance.sys.settings.getUserSettings(userId); + const settingValue = userSettings[`app:${this.applicationId}:${this.id}`] as string | undefined; + + if (settingValue === undefined) return this.defaultValue; + + return Number(settingValue); + } + + setDisplayName(displayName: string): this { + this.displayName = displayName; + + return this; + } + + setDescription(description: string): this { + this.description = description; + + return this; + } + + setHidden(hidden: boolean) { + this.hidden = hidden; + + return this; + } +} + +export class GlobalNumberApplicationSetting extends GlobalApplicationSetting { + constructor(applicationId: string, id: string, defaultValue: number) { + super(); + + this.applicationId = applicationId; + this.id = id; + this.defaultValue = defaultValue; + this.type = "number"; + this.description = "No description provided"; + this.hidden = false; + } + + async setValue(value: number) { + await this.instance.sys.settings.setGlobalSetting(`app:${this.applicationId}:${this.id}`, value.toString()); + + return true; + } + + async onValueChange(): Promise { + const settingValue = await this.instance.sys.settings.getGlobalSetting(`app:${this.applicationId}:${this.id}`); + + if (settingValue === undefined) return this.defaultValue; + + return Number(settingValue); + } + + setDisplayName(displayName: string): this { + this.displayName = displayName; + + return this; + } + + setDescription(description: string): this { + this.description = description; + + return this; + } + + setHidden(hidden: boolean) { + this.hidden = hidden; + + return this; + } +} diff --git a/instance/src/systems/settings/applicationSetting/stringListSetting.ts b/instance/src/systems/settings/applicationSetting/stringListSetting.ts index 3798676..c5a4c03 100644 --- a/instance/src/systems/settings/applicationSetting/stringListSetting.ts +++ b/instance/src/systems/settings/applicationSetting/stringListSetting.ts @@ -1,153 +1,153 @@ -import { ApplicationSetting, GlobalApplicationSetting } from "./applicationSetting.ts"; - -export class StringListApplicationSetting extends ApplicationSetting { - allowedValues?: string[]; - allowDuplicateValues?: boolean; - - constructor(applicationId: string, id: string, defaultValue: string[], options?: { allowedValues: string[]; allowDuplicateValues?: boolean }) { - super(); - - this.applicationId = applicationId; - this.id = id; - this.defaultValue = defaultValue; - this.displayName = id; - this.type = "stringList"; - this.description = "No description provided"; - this.allowedValues = options?.allowedValues; - this.allowDuplicateValues = options?.allowDuplicateValues; - this.hidden = false; - } - - async setValue(userId: number, value: string[]) { - if (this.allowedValues) { - for (const val of value) { - if (!this.allowedValues.includes(val)) { - this.instance.log.system.warning( - `Unable to set setting '${this.applicationId}:${this.id}' for user ${userId} as it contains invalid value '${value}'`, - ); - return false; - } - } - } - - const userSettings = await this.instance.sys.settings.getUserSettings(userId); - - userSettings[`app:${this.applicationId}:${this.id}`] = JSON.stringify(value); - - await this.instance.sys.settings.setUserSettings(userId, userSettings); - - return true; - } - - async addValue(userId: number, value: string) { - const userSettings = await this.instance.sys.settings.getUserSettings(userId); - - userSettings[`app:${this.applicationId}:${this.id}`] = JSON.stringify([...JSON.parse(userSettings[`app:${this.applicationId}:${this.id}`]), value]); - - await this.instance.sys.settings.setUserSettings(userId, userSettings); - - return this; - } - - async onValueChange(userId: number): Promise { - const userSettings = await this.instance.sys.settings.getUserSettings(userId); - - const settingValue = userSettings[`app:${this.applicationId}:${this.id}`]; - - if (settingValue === undefined) return this.defaultValue; - - return JSON.parse(settingValue); - } - - setDisplayName(displayName: string): this { - this.displayName = displayName; - - return this; - } - - setDescription(description: string): this { - this.description = description; - - return this; - } - - setHidden(hidden: boolean) { - this.hidden = hidden; - - return this; - } -} - -export class GlobalStringListApplicationSetting extends GlobalApplicationSetting { - allowedValues?: string[]; - allowDuplicateValues?: boolean; - - constructor(applicationId: string, id: string, defaultValue: string[], options?: { allowedValues: string[]; allowDuplicateValues?: boolean }) { - super(); - - this.applicationId = applicationId; - this.id = id; - this.defaultValue = defaultValue; - this.type = "string"; - this.description = "No description provided"; - this.allowedValues = options?.allowedValues; - this.allowDuplicateValues = options?.allowDuplicateValues; - this.hidden = false; - } - - async setValue(value: string[]) { - if (this.allowedValues) { - for (const val of value) { - if (!this.allowedValues.includes(val)) { - this.instance.log.system.warning(`Unable to set setting '${this.applicationId}:${this.id}' as it contains invalid value '${value}'`); - return false; - } - } - } - - await this.instance.sys.settings.setGlobalSetting(`app:${this.applicationId}:${this.id}`, JSON.stringify(value)); - - return true; - } - - async addValue(value: string) { - const rawSettingValue = await this.instance.sys.settings.getGlobalSetting(`app:${this.applicationId}:${this.id}`); - let settingValue: string[]; - - if (rawSettingValue === undefined) { - settingValue = []; - } else { - settingValue = JSON.parse(rawSettingValue); - } - - await this.instance.sys.settings.setGlobalSetting(`app:${this.applicationId}:${this.id}`, JSON.stringify([...settingValue, value])); - - return this; - } - - async onValueChange(): Promise { - const settingValue = await this.instance.sys.settings.getGlobalSetting(`app:${this.applicationId}:${this.id}`); - - if (settingValue === undefined) return this.defaultValue; - - return JSON.parse(settingValue); - } - - setDisplayName(displayName: string): this { - this.displayName = displayName; - - return this; - } - - setDescription(description: string): this { - this.description = description; - - return this; - } - - setHidden(hidden: boolean) { - this.hidden = hidden; - - return this; - } -} +import { ApplicationSetting, GlobalApplicationSetting } from "./applicationSetting.ts"; + +export class StringListApplicationSetting extends ApplicationSetting { + allowedValues?: string[]; + allowDuplicateValues?: boolean; + + constructor(applicationId: string, id: string, defaultValue: string[], options?: { allowedValues: string[]; allowDuplicateValues?: boolean }) { + super(); + + this.applicationId = applicationId; + this.id = id; + this.defaultValue = defaultValue; + this.displayName = id; + this.type = "stringList"; + this.description = "No description provided"; + this.allowedValues = options?.allowedValues; + this.allowDuplicateValues = options?.allowDuplicateValues; + this.hidden = false; + } + + async setValue(userId: number, value: string[]) { + if (this.allowedValues) { + for (const val of value) { + if (!this.allowedValues.includes(val)) { + this.instance.log.system.warning( + `Unable to set setting '${this.applicationId}:${this.id}' for user ${userId} as it contains invalid value '${value}'`, + ); + return false; + } + } + } + + const userSettings = await this.instance.sys.settings.getUserSettings(userId); + + userSettings[`app:${this.applicationId}:${this.id}`] = JSON.stringify(value); + + await this.instance.sys.settings.setUserSettings(userId, userSettings); + + return true; + } + + async addValue(userId: number, value: string) { + const userSettings = await this.instance.sys.settings.getUserSettings(userId); + + userSettings[`app:${this.applicationId}:${this.id}`] = JSON.stringify([...JSON.parse(userSettings[`app:${this.applicationId}:${this.id}`]), value]); + + await this.instance.sys.settings.setUserSettings(userId, userSettings); + + return this; + } + + async onValueChange(userId: number): Promise { + const userSettings = await this.instance.sys.settings.getUserSettings(userId); + + const settingValue = userSettings[`app:${this.applicationId}:${this.id}`]; + + if (settingValue === undefined) return this.defaultValue; + + return JSON.parse(settingValue); + } + + setDisplayName(displayName: string): this { + this.displayName = displayName; + + return this; + } + + setDescription(description: string): this { + this.description = description; + + return this; + } + + setHidden(hidden: boolean) { + this.hidden = hidden; + + return this; + } +} + +export class GlobalStringListApplicationSetting extends GlobalApplicationSetting { + allowedValues?: string[]; + allowDuplicateValues?: boolean; + + constructor(applicationId: string, id: string, defaultValue: string[], options?: { allowedValues: string[]; allowDuplicateValues?: boolean }) { + super(); + + this.applicationId = applicationId; + this.id = id; + this.defaultValue = defaultValue; + this.type = "string"; + this.description = "No description provided"; + this.allowedValues = options?.allowedValues; + this.allowDuplicateValues = options?.allowDuplicateValues; + this.hidden = false; + } + + async setValue(value: string[]) { + if (this.allowedValues) { + for (const val of value) { + if (!this.allowedValues.includes(val)) { + this.instance.log.system.warning(`Unable to set setting '${this.applicationId}:${this.id}' as it contains invalid value '${value}'`); + return false; + } + } + } + + await this.instance.sys.settings.setGlobalSetting(`app:${this.applicationId}:${this.id}`, JSON.stringify(value)); + + return true; + } + + async addValue(value: string) { + const rawSettingValue = await this.instance.sys.settings.getGlobalSetting(`app:${this.applicationId}:${this.id}`); + let settingValue: string[]; + + if (rawSettingValue === undefined) { + settingValue = []; + } else { + settingValue = JSON.parse(rawSettingValue); + } + + await this.instance.sys.settings.setGlobalSetting(`app:${this.applicationId}:${this.id}`, JSON.stringify([...settingValue, value])); + + return this; + } + + async onValueChange(): Promise { + const settingValue = await this.instance.sys.settings.getGlobalSetting(`app:${this.applicationId}:${this.id}`); + + if (settingValue === undefined) return this.defaultValue; + + return JSON.parse(settingValue); + } + + setDisplayName(displayName: string): this { + this.displayName = displayName; + + return this; + } + + setDescription(description: string): this { + this.description = description; + + return this; + } + + setHidden(hidden: boolean) { + this.hidden = hidden; + + return this; + } +} diff --git a/instance/src/systems/settings/applicationSetting/stringSetting.ts b/instance/src/systems/settings/applicationSetting/stringSetting.ts index 1f4e8c1..10171d0 100644 --- a/instance/src/systems/settings/applicationSetting/stringSetting.ts +++ b/instance/src/systems/settings/applicationSetting/stringSetting.ts @@ -1,98 +1,98 @@ -import { ApplicationSetting, GlobalApplicationSetting } from "./applicationSetting.ts"; - -export class StringApplicationSetting extends ApplicationSetting { - constructor(applicationId: string, id: string, defaultValue: string) { - super(); - - this.applicationId = applicationId; - this.id = id; - this.defaultValue = defaultValue; - this.displayName = id; - this.type = "string"; - this.description = "No description provided"; - this.hidden = false; - } - - async setValue(userId: number, value: string) { - const userSettings = await this.instance.sys.settings.getUserSettings(userId); - - userSettings[`app:${this.applicationId}:${this.id}`] = value; - - await this.instance.sys.settings.setUserSettings(userId, userSettings); - - return true; - } - - async onValueChange(userId: number): Promise { - const userSettings = await this.instance.sys.settings.getUserSettings(userId); - - const settingValue = userSettings[`app:${this.applicationId}:${this.id}`]; - - if (settingValue === undefined) return this.defaultValue; - - return settingValue; - } - - setDisplayName(displayName: string): this { - this.displayName = displayName; - - return this; - } - - setDescription(description: string): this { - this.description = description; - - return this; - } - - setHidden(hidden: boolean) { - this.hidden = hidden; - - return this; - } -} - -export class GlobalStringApplicationSetting extends GlobalApplicationSetting { - constructor(applicationId: string, id: string, defaultValue: string) { - super(); - - this.applicationId = applicationId; - this.id = id; - this.defaultValue = defaultValue; - this.type = "string"; - this.description = "No description provided"; - this.hidden = false; - } - - async setValue(value: string) { - await this.instance.sys.settings.setGlobalSetting(`app:${this.applicationId}:${this.id}`, value); - - return true; - } - - async onValueChange(): Promise { - const settingValue = await this.instance.sys.settings.getGlobalSetting(`app:${this.applicationId}:${this.id}`); - - if (settingValue === undefined) return this.defaultValue; - - return settingValue; - } - - setDisplayName(displayName: string): this { - this.displayName = displayName; - - return this; - } - - setDescription(description: string): this { - this.description = description; - - return this; - } - - setHidden(hidden: boolean) { - this.hidden = hidden; - - return this; - } -} +import { ApplicationSetting, GlobalApplicationSetting } from "./applicationSetting.ts"; + +export class StringApplicationSetting extends ApplicationSetting { + constructor(applicationId: string, id: string, defaultValue: string) { + super(); + + this.applicationId = applicationId; + this.id = id; + this.defaultValue = defaultValue; + this.displayName = id; + this.type = "string"; + this.description = "No description provided"; + this.hidden = false; + } + + async setValue(userId: number, value: string) { + const userSettings = await this.instance.sys.settings.getUserSettings(userId); + + userSettings[`app:${this.applicationId}:${this.id}`] = value; + + await this.instance.sys.settings.setUserSettings(userId, userSettings); + + return true; + } + + async onValueChange(userId: number): Promise { + const userSettings = await this.instance.sys.settings.getUserSettings(userId); + + const settingValue = userSettings[`app:${this.applicationId}:${this.id}`]; + + if (settingValue === undefined) return this.defaultValue; + + return settingValue; + } + + setDisplayName(displayName: string): this { + this.displayName = displayName; + + return this; + } + + setDescription(description: string): this { + this.description = description; + + return this; + } + + setHidden(hidden: boolean) { + this.hidden = hidden; + + return this; + } +} + +export class GlobalStringApplicationSetting extends GlobalApplicationSetting { + constructor(applicationId: string, id: string, defaultValue: string) { + super(); + + this.applicationId = applicationId; + this.id = id; + this.defaultValue = defaultValue; + this.type = "string"; + this.description = "No description provided"; + this.hidden = false; + } + + async setValue(value: string) { + await this.instance.sys.settings.setGlobalSetting(`app:${this.applicationId}:${this.id}`, value); + + return true; + } + + async onValueChange(): Promise { + const settingValue = await this.instance.sys.settings.getGlobalSetting(`app:${this.applicationId}:${this.id}`); + + if (settingValue === undefined) return this.defaultValue; + + return settingValue; + } + + setDisplayName(displayName: string): this { + this.displayName = displayName; + + return this; + } + + setDescription(description: string): this { + this.description = description; + + return this; + } + + setHidden(hidden: boolean) { + this.hidden = hidden; + + return this; + } +} diff --git a/instance/src/systems/terminalUI.ts b/instance/src/systems/terminalUI.ts index cdbdb8e..e983b7f 100644 --- a/instance/src/systems/terminalUI.ts +++ b/instance/src/systems/terminalUI.ts @@ -1,50 +1,50 @@ -import type { Instance } from "../index.ts"; -import System from "../system.ts"; -import Terminal from "./terminalUI/terminal.ts"; -import TerminalBorderView from "./terminalUI/views/borderView.ts"; -import TerminalContainerView from "./terminalUI/views/container.ts"; -import TerminalCrossView from "./terminalUI/views/crossView.ts"; -import TerminalTextInputView from "./terminalUI/views/textInput.ts"; - -export default class TerminalUISystem extends System { - constructor(instance: Instance) { - super("terminal_ui", instance); - } - - override async startup(): Promise { - if (!process.stdout) return false; - - await super.startup(); - - const terminal = new Terminal(); - - // biome-ignore format: TUI description - terminal.screen.childView.addChild( - TerminalContainerView, v => v.setFlowDirection("y") - .addChild( - TerminalBorderView, v => v - .addChild(TerminalContainerView, v => v.setFlowDirection("y") - .addChild( - TerminalTextInputView, v => v - .setPlaceholder("Placeholder Text") - ) - .addChild( - TerminalContainerView, v => v.setFlowDirection("x") - .addChild(TerminalCrossView) - .addChild(TerminalCrossView) - ) - ) - ) - // .addChild( - // TerminalBorderView, v=>v - // .setDimensions({width: { unit: "%", value: 100 }, height: { unit: "px", value: 5 } }) - // ) - ); - - setInterval(async () => { - await terminal.draw(); - }, 100); - - return true; - } -} +import type { Instance } from "../index.ts"; +import System from "../system.ts"; +import Terminal from "./terminalUI/terminal.ts"; +import TerminalBorderView from "./terminalUI/views/borderView.ts"; +import TerminalContainerView from "./terminalUI/views/container.ts"; +import TerminalCrossView from "./terminalUI/views/crossView.ts"; +import TerminalTextInputView from "./terminalUI/views/textInput.ts"; + +export default class TerminalUISystem extends System { + constructor(instance: Instance) { + super("terminal_ui", instance); + } + + override async startup(): Promise { + if (!process.stdout) return false; + + await super.startup(); + + const terminal = new Terminal(); + + // biome-ignore format: TUI description + terminal.screen.childView.addChild( + TerminalContainerView, v => v.setFlowDirection("y") + .addChild( + TerminalBorderView, v => v + .addChild(TerminalContainerView, v => v.setFlowDirection("y") + .addChild( + TerminalTextInputView, v => v + .setPlaceholder("Placeholder Text") + ) + .addChild( + TerminalContainerView, v => v.setFlowDirection("x") + .addChild(TerminalCrossView) + .addChild(TerminalCrossView) + ) + ) + ) + // .addChild( + // TerminalBorderView, v=>v + // .setDimensions({width: { unit: "%", value: 100 }, height: { unit: "px", value: 5 } }) + // ) + ); + + setInterval(async () => { + await terminal.draw(); + }, 100); + + return true; + } +} diff --git a/instance/src/systems/terminalUI/effect.ts b/instance/src/systems/terminalUI/effect.ts index aed3aa0..fb73d1b 100644 --- a/instance/src/systems/terminalUI/effect.ts +++ b/instance/src/systems/terminalUI/effect.ts @@ -1,194 +1,194 @@ -export enum TerminalColor { - Black = 1, - Red, - Green, - Yellow, - Blue, - Magenta, - Cyan, - White, - BrightBlack, - BrightRed, - BrightGreen, - BrightYellow, - BrightBlue, - BrightMagenta, - BrightCyan, - BrightWhite, -} - -export default class TerminalEffect { - private foregroundColor?: TerminalColor; - private backgroundColor?: TerminalColor; - private bold?: boolean; - private underline?: boolean; - - setBold() { - this.bold = true; - - return this; - } - - setUnderline() { - this.underline = true; - - return this; - } - - setColor(color: TerminalColor) { - this.foregroundColor = color; - - return this; - } - - setBackgroundColor(color: TerminalColor) { - this.backgroundColor = color; - - return this; - } - - async _internal_apply(): Promise { - let outputString = ""; - - if (this.bold) outputString += "\x1b[1m"; - if (this.underline) outputString += "\x1b[4m"; - if (this.foregroundColor) { - switch (this.foregroundColor) { - case TerminalColor.Black: { - outputString += "\x1b[30m"; - break; - } - case TerminalColor.Red: { - outputString += "\x1b[31m"; - break; - } - case TerminalColor.Green: { - outputString += "\x1b[32m"; - break; - } - case TerminalColor.Yellow: { - outputString += "\x1b[33m"; - break; - } - case TerminalColor.Blue: { - outputString += "\x1b[34m"; - break; - } - case TerminalColor.Magenta: { - outputString += "\x1b[35m"; - break; - } - case TerminalColor.Cyan: { - outputString += "\x1b[36m"; - break; - } - case TerminalColor.White: { - outputString += "\x1b[37m"; - break; - } - case TerminalColor.BrightBlack: { - outputString += "\x1b[90m"; - break; - } - case TerminalColor.BrightRed: { - outputString += "\x1b[91m"; - break; - } - case TerminalColor.BrightGreen: { - outputString += "\x1b[92m"; - break; - } - case TerminalColor.BrightYellow: { - outputString += "\x1b[93m"; - break; - } - case TerminalColor.BrightBlue: { - outputString += "\x1b[94m"; - break; - } - case TerminalColor.BrightMagenta: { - outputString += "\x1b[95m"; - break; - } - case TerminalColor.BrightCyan: { - outputString += "\x1b[96m"; - break; - } - case TerminalColor.BrightWhite: { - outputString += "\x1b[97m"; - break; - } - } - } - if (this.backgroundColor) { - switch (this.backgroundColor) { - case TerminalColor.Black: { - outputString += "\x1b[40m"; - break; - } - case TerminalColor.Red: { - outputString += "\x1b[41m"; - break; - } - case TerminalColor.Green: { - outputString += "\x1b[42m"; - break; - } - case TerminalColor.Yellow: { - outputString += "\x1b[43m"; - break; - } - case TerminalColor.Blue: { - outputString += "\x1b[44m"; - break; - } - case TerminalColor.Magenta: { - outputString += "\x1b[45m"; - break; - } - case TerminalColor.Cyan: { - outputString += "\x1b[46m"; - break; - } - case TerminalColor.White: { - outputString += "\x1b[47m"; - break; - } - case TerminalColor.BrightBlack: { - outputString += "\x1b[100m"; - break; - } - case TerminalColor.BrightRed: { - outputString += "\x1b[101m"; - break; - } - case TerminalColor.BrightGreen: { - outputString += "\x1b[102m"; - break; - } - case TerminalColor.BrightYellow: { - outputString += "\x1b[103m"; - break; - } - case TerminalColor.BrightBlue: { - outputString += "\x1b[104m"; - break; - } - case TerminalColor.BrightMagenta: { - outputString += "\x1b[105m"; - break; - } - case TerminalColor.BrightCyan: { - outputString += "\x1b[106m"; - break; - } - case TerminalColor.BrightWhite: { - outputString += "\x1b[107m"; - break; - } - } - } - - return outputString; - } -} +export enum TerminalColor { + Black = 1, + Red, + Green, + Yellow, + Blue, + Magenta, + Cyan, + White, + BrightBlack, + BrightRed, + BrightGreen, + BrightYellow, + BrightBlue, + BrightMagenta, + BrightCyan, + BrightWhite, +} + +export default class TerminalEffect { + private foregroundColor?: TerminalColor; + private backgroundColor?: TerminalColor; + private bold?: boolean; + private underline?: boolean; + + setBold() { + this.bold = true; + + return this; + } + + setUnderline() { + this.underline = true; + + return this; + } + + setColor(color: TerminalColor) { + this.foregroundColor = color; + + return this; + } + + setBackgroundColor(color: TerminalColor) { + this.backgroundColor = color; + + return this; + } + + async _internal_apply(): Promise { + let outputString = ""; + + if (this.bold) outputString += "\x1b[1m"; + if (this.underline) outputString += "\x1b[4m"; + if (this.foregroundColor) { + switch (this.foregroundColor) { + case TerminalColor.Black: { + outputString += "\x1b[30m"; + break; + } + case TerminalColor.Red: { + outputString += "\x1b[31m"; + break; + } + case TerminalColor.Green: { + outputString += "\x1b[32m"; + break; + } + case TerminalColor.Yellow: { + outputString += "\x1b[33m"; + break; + } + case TerminalColor.Blue: { + outputString += "\x1b[34m"; + break; + } + case TerminalColor.Magenta: { + outputString += "\x1b[35m"; + break; + } + case TerminalColor.Cyan: { + outputString += "\x1b[36m"; + break; + } + case TerminalColor.White: { + outputString += "\x1b[37m"; + break; + } + case TerminalColor.BrightBlack: { + outputString += "\x1b[90m"; + break; + } + case TerminalColor.BrightRed: { + outputString += "\x1b[91m"; + break; + } + case TerminalColor.BrightGreen: { + outputString += "\x1b[92m"; + break; + } + case TerminalColor.BrightYellow: { + outputString += "\x1b[93m"; + break; + } + case TerminalColor.BrightBlue: { + outputString += "\x1b[94m"; + break; + } + case TerminalColor.BrightMagenta: { + outputString += "\x1b[95m"; + break; + } + case TerminalColor.BrightCyan: { + outputString += "\x1b[96m"; + break; + } + case TerminalColor.BrightWhite: { + outputString += "\x1b[97m"; + break; + } + } + } + if (this.backgroundColor) { + switch (this.backgroundColor) { + case TerminalColor.Black: { + outputString += "\x1b[40m"; + break; + } + case TerminalColor.Red: { + outputString += "\x1b[41m"; + break; + } + case TerminalColor.Green: { + outputString += "\x1b[42m"; + break; + } + case TerminalColor.Yellow: { + outputString += "\x1b[43m"; + break; + } + case TerminalColor.Blue: { + outputString += "\x1b[44m"; + break; + } + case TerminalColor.Magenta: { + outputString += "\x1b[45m"; + break; + } + case TerminalColor.Cyan: { + outputString += "\x1b[46m"; + break; + } + case TerminalColor.White: { + outputString += "\x1b[47m"; + break; + } + case TerminalColor.BrightBlack: { + outputString += "\x1b[100m"; + break; + } + case TerminalColor.BrightRed: { + outputString += "\x1b[101m"; + break; + } + case TerminalColor.BrightGreen: { + outputString += "\x1b[102m"; + break; + } + case TerminalColor.BrightYellow: { + outputString += "\x1b[103m"; + break; + } + case TerminalColor.BrightBlue: { + outputString += "\x1b[104m"; + break; + } + case TerminalColor.BrightMagenta: { + outputString += "\x1b[105m"; + break; + } + case TerminalColor.BrightCyan: { + outputString += "\x1b[106m"; + break; + } + case TerminalColor.BrightWhite: { + outputString += "\x1b[107m"; + break; + } + } + } + + return outputString; + } +} diff --git a/instance/src/systems/terminalUI/events/keyPressEvent.ts b/instance/src/systems/terminalUI/events/keyPressEvent.ts index 7a14e79..8384967 100644 --- a/instance/src/systems/terminalUI/events/keyPressEvent.ts +++ b/instance/src/systems/terminalUI/events/keyPressEvent.ts @@ -1,12 +1,12 @@ -import TerminalEvent, { TerminalEventType } from "../terminalEvent.ts"; - -export default class KeyPressEvent extends TerminalEvent { - type: TerminalEventType = TerminalEventType.KeyPress as const; - key: string; - - constructor(key: string) { - super(); - - this.key = key; - } -} +import TerminalEvent, { TerminalEventType } from "../terminalEvent.ts"; + +export default class KeyPressEvent extends TerminalEvent { + type: TerminalEventType = TerminalEventType.KeyPress as const; + key: string; + + constructor(key: string) { + super(); + + this.key = key; + } +} diff --git a/instance/src/systems/terminalUI/events/mouseClickEvent.ts b/instance/src/systems/terminalUI/events/mouseClickEvent.ts index 97bea31..f591992 100644 --- a/instance/src/systems/terminalUI/events/mouseClickEvent.ts +++ b/instance/src/systems/terminalUI/events/mouseClickEvent.ts @@ -1,12 +1,12 @@ -import TerminalEvent, { TerminalEventType } from "../terminalEvent.ts"; - -export default class MouseClickEvent extends TerminalEvent { - type: TerminalEventType = TerminalEventType.MouseClick as const; - position: { x: number; y: number }; - - constructor(position: MouseClickEvent["position"]) { - super(); - - this.position = position; - } -} +import TerminalEvent, { TerminalEventType } from "../terminalEvent.ts"; + +export default class MouseClickEvent extends TerminalEvent { + type: TerminalEventType = TerminalEventType.MouseClick as const; + position: { x: number; y: number }; + + constructor(position: MouseClickEvent["position"]) { + super(); + + this.position = position; + } +} diff --git a/instance/src/systems/terminalUI/events/resizeScreenEvent.ts b/instance/src/systems/terminalUI/events/resizeScreenEvent.ts index c41638d..c457602 100644 --- a/instance/src/systems/terminalUI/events/resizeScreenEvent.ts +++ b/instance/src/systems/terminalUI/events/resizeScreenEvent.ts @@ -1,12 +1,12 @@ -import TerminalEvent, { TerminalEventType } from "../terminalEvent.ts"; - -export default class ResizeScreenEvent extends TerminalEvent { - type: TerminalEventType = TerminalEventType.ResizeScreen as const; - dimensions: { width: number; height: number }; - - constructor(dimensions: ResizeScreenEvent["dimensions"]) { - super(); - - this.dimensions = dimensions; - } -} +import TerminalEvent, { TerminalEventType } from "../terminalEvent.ts"; + +export default class ResizeScreenEvent extends TerminalEvent { + type: TerminalEventType = TerminalEventType.ResizeScreen as const; + dimensions: { width: number; height: number }; + + constructor(dimensions: ResizeScreenEvent["dimensions"]) { + super(); + + this.dimensions = dimensions; + } +} diff --git a/instance/src/systems/terminalUI/events/scrollDownEvent.ts b/instance/src/systems/terminalUI/events/scrollDownEvent.ts index 87a90f4..6744128 100644 --- a/instance/src/systems/terminalUI/events/scrollDownEvent.ts +++ b/instance/src/systems/terminalUI/events/scrollDownEvent.ts @@ -1,12 +1,12 @@ -import TerminalEvent, { TerminalEventType } from "../terminalEvent.ts"; - -export default class ScrollDownEvent extends TerminalEvent { - type: TerminalEventType = TerminalEventType.ScrollDown as const; - yVector: number; - - constructor(yVector: ScrollDownEvent["yVector"]) { - super(); - - this.yVector = yVector * -1; - } -} +import TerminalEvent, { TerminalEventType } from "../terminalEvent.ts"; + +export default class ScrollDownEvent extends TerminalEvent { + type: TerminalEventType = TerminalEventType.ScrollDown as const; + yVector: number; + + constructor(yVector: ScrollDownEvent["yVector"]) { + super(); + + this.yVector = yVector * -1; + } +} diff --git a/instance/src/systems/terminalUI/events/scrollUpEvent.ts b/instance/src/systems/terminalUI/events/scrollUpEvent.ts index 47fe1e3..02425f1 100644 --- a/instance/src/systems/terminalUI/events/scrollUpEvent.ts +++ b/instance/src/systems/terminalUI/events/scrollUpEvent.ts @@ -1,12 +1,12 @@ -import TerminalEvent, { TerminalEventType } from "../terminalEvent.ts"; - -export default class ScrollUpEvent extends TerminalEvent { - type: TerminalEventType = TerminalEventType.ScrollUp as const; - yVector: number; - - constructor(yVector: ScrollUpEvent["yVector"]) { - super(); - - this.yVector = yVector; - } -} +import TerminalEvent, { TerminalEventType } from "../terminalEvent.ts"; + +export default class ScrollUpEvent extends TerminalEvent { + type: TerminalEventType = TerminalEventType.ScrollUp as const; + yVector: number; + + constructor(yVector: ScrollUpEvent["yVector"]) { + super(); + + this.yVector = yVector; + } +} diff --git a/instance/src/systems/terminalUI/notes.md b/instance/src/systems/terminalUI/notes.md new file mode 100644 index 0000000..e39cba1 --- /dev/null +++ b/instance/src/systems/terminalUI/notes.md @@ -0,0 +1,33 @@ +# View Struct + +- viewProperties + - width : TerminalScalarValue + - height : TerminalScalarValue + - contentWidth : TerminalScalarValue + - contentHeight : TerminalScalarValue + - contentOffsetX : TerminalScalarValue + - contentOffsetY : TerminalScalarValue + - _absolute // Autogenerated (DO NOT EDIT) + - drawOriginX: number // Calculated by the parent's calculateAbsoluteProperties(); + - drawOriginY: number // Calculated by the parent's calculateAbsoluteProperties(); + - width : number + - height : number + - contentWidth : number + - contentHeight : number + - contentOffsetX : number + - contentOffsetY : number +- viewContext + - screen + - drawIdx + - parentView +- calculateAbsoluteProperties() +- draw() + +# View Size Calculation Steps + +- get available space +- get all absolute widths and heights for children with px values (include min px values if the normal val uses non px values) +- get remaining space for x & y +- calculate all total % dimensions for children +- calculate the value of a width & height percent using the remaining space +- get all absolute widths and heights for children with % values diff --git a/instance/src/systems/terminalUI/renderError.ts b/instance/src/systems/terminalUI/renderError.ts index e651923..ba85239 100644 --- a/instance/src/systems/terminalUI/renderError.ts +++ b/instance/src/systems/terminalUI/renderError.ts @@ -1,25 +1,25 @@ -import type TerminalScreen from "./screen.ts"; - -export default class RenderError { - private errorMessage: string; - private flash: number; - - constructor(errorMessage: string) { - this.errorMessage = errorMessage; - this.flash = 0; - } - - async draw(screen: TerminalScreen) { - const errorMessage = `RenderError! ${this.errorMessage}`; - const xOrigin = Math.floor(screen.width / 2) - Math.floor(errorMessage.length / 2); - - this.flash += 0.25; - - await screen._rawCursorTo(xOrigin, 0); - await screen._rawWrite(`${this.flash % 2 === 0 ? "\x1b[90;41m" : "\x1b[91;40m"}\x1b[1m ${" ".repeat(errorMessage.length)} `); - await screen._rawCursorTo(xOrigin, 1); - await screen._rawWrite(`${this.flash % 2 === 0 ? "\x1b[90;41m" : "\x1b[91;40m"}\x1b[1m ${errorMessage} `); - await screen._rawCursorTo(xOrigin, 2); - await screen._rawWrite(`${this.flash % 2 === 0 ? "\x1b[90;41m" : "\x1b[91;40m"}\x1b[1m ${" ".repeat(errorMessage.length)} `); - } -} +import type TerminalScreen from "./screen.ts"; + +export default class RenderError { + private errorMessage: string; + private flash: number; + + constructor(errorMessage: string) { + this.errorMessage = errorMessage; + this.flash = 0; + } + + async draw(screen: TerminalScreen) { + const errorMessage = `RenderError! ${this.errorMessage}`; + const xOrigin = Math.floor(screen.width / 2) - Math.floor(errorMessage.length / 2); + + this.flash += 0.25; + + await screen._rawCursorTo(xOrigin, 0); + await screen._rawWrite(`${this.flash % 2 === 0 ? "\x1b[90;41m" : "\x1b[91;40m"}\x1b[1m ${" ".repeat(errorMessage.length)} `); + await screen._rawCursorTo(xOrigin, 1); + await screen._rawWrite(`${this.flash % 2 === 0 ? "\x1b[90;41m" : "\x1b[91;40m"}\x1b[1m ${errorMessage} `); + await screen._rawCursorTo(xOrigin, 2); + await screen._rawWrite(`${this.flash % 2 === 0 ? "\x1b[90;41m" : "\x1b[91;40m"}\x1b[1m ${" ".repeat(errorMessage.length)} `); + } +} diff --git a/instance/src/systems/terminalUI/scalarValue.ts b/instance/src/systems/terminalUI/scalarValue.ts index 1986da7..f9eb65b 100644 --- a/instance/src/systems/terminalUI/scalarValue.ts +++ b/instance/src/systems/terminalUI/scalarValue.ts @@ -11,15 +11,21 @@ enum TerminalScalarValueOperation { } export enum TerminalScalarValueUnit { - Pixel, + Cell, Percentage, } export default class TerminalScalarValue { operationChain: [TerminalScalarValueOperation, number?, TerminalScalarValueUnit?][]; - constructor() { + constructor(); + constructor(value: number, unit: TerminalScalarValueUnit); + constructor(value?: number, unit?: TerminalScalarValueUnit) { this.operationChain = []; + + if (value !== undefined && unit !== undefined) { + this.set(value, unit); + } } set(value: number, unit: TerminalScalarValueUnit) { @@ -59,13 +65,21 @@ export default class TerminalScalarValue { _internal_calculateFromView(view: TerminalView, valueType: "width" | "height"): number { let maxSize = 0; + + if (valueType === "height") { + maxSize = view.viewProperties._absolute.contentHeight; + } + if (valueType === "width") { + maxSize = view.viewProperties._absolute.contentWidth; + } + let val = 0; for (const operation of this.operationChain) { switch (operation[0]) { case TerminalScalarValueOperation.Set: { switch (operation[2]) { - case TerminalScalarValueUnit.Pixel: { + case TerminalScalarValueUnit.Cell: { val = operation[1]!; break; } @@ -78,7 +92,7 @@ export default class TerminalScalarValue { } case TerminalScalarValueOperation.Add: { switch (operation[2]) { - case TerminalScalarValueUnit.Pixel: { + case TerminalScalarValueUnit.Cell: { val += operation[1]!; break; } @@ -91,7 +105,7 @@ export default class TerminalScalarValue { } case TerminalScalarValueOperation.Subtract: { switch (operation[2]) { - case TerminalScalarValueUnit.Pixel: { + case TerminalScalarValueUnit.Cell: { val -= operation[1]!; break; } diff --git a/instance/src/systems/terminalUI/screen.ts b/instance/src/systems/terminalUI/screen.ts index 8045541..e48c9b1 100644 --- a/instance/src/systems/terminalUI/screen.ts +++ b/instance/src/systems/terminalUI/screen.ts @@ -1,3 +1,4 @@ +import { timeStamp } from "node:console"; import type TerminalEffect from "./effect.ts"; import type Terminal from "./terminal.ts"; import type TerminalView from "./view.ts"; @@ -23,7 +24,7 @@ export default class TerminalScreen { this._internal_isDrawingFrame = false; this.width = process.stdout.columns; this.height = process.stdout.rows; - this.childView = new TerminalContainerView({ screen: this }); + this.childView = new TerminalContainerView({ screen: this, parentView: undefined }); } cursorTo(x: number, y?: number) { @@ -85,8 +86,17 @@ export default class TerminalScreen { if (this._internal_isDrawingFrame) return; this._internal_isDrawingFrame = true; - this.childView.calculateSize({ width: this.width, height: this.height }, { width: this.width, height: this.height }); - await this.childView.draw(this, { x: 0, y: 0 }); + this.childView.calculateAbsoluteProperties(); + await this.childView.draw({ + drawOriginX: 0, + drawOriginY: 0, + width: this.width, + height: this.height, + contentWidth: this.width, + contentHeight: this.height, + contentOffsetX: 0, + contentOffsetY: 0, + }); let remBuf = this.contentBuffer; diff --git a/instance/src/systems/terminalUI/terminal.ts b/instance/src/systems/terminalUI/terminal.ts index a3622e3..68e204b 100644 --- a/instance/src/systems/terminalUI/terminal.ts +++ b/instance/src/systems/terminalUI/terminal.ts @@ -1,32 +1,32 @@ -import type RenderError from "./renderError.ts"; -import TerminalScreen from "./screen.ts"; - -export default class Terminal { - screen: TerminalScreen; - renderError?: RenderError; - - constructor() { - this.screen = new TerminalScreen(this); - this.screen.onResize(); - - process.stdout.on("resize", async () => { - await this.screen.onResize(); - }); - - // process.stdin.setRawMode(true); - - globalThis.addEventListener("unload", () => { - this.end(); - }); - } - - async draw() { - await this.screen.draw(); - await this.renderError?.draw(this.screen); - } - - end() { - this.screen._rawWrite(`\x1b[?47l`); - // process.stdin.setRawMode(false); - } -} +import type RenderError from "./renderError.ts"; +import TerminalScreen from "./screen.ts"; + +export default class Terminal { + screen: TerminalScreen; + renderError?: RenderError; + + constructor() { + this.screen = new TerminalScreen(this); + this.screen.onResize(); + + process.stdout.on("resize", async () => { + await this.screen.onResize(); + }); + + // process.stdin.setRawMode(true); + + globalThis.addEventListener("unload", () => { + this.end(); + }); + } + + async draw() { + await this.screen.draw(); + await this.renderError?.draw(this.screen); + } + + end() { + this.screen._rawWrite(`\x1b[?47l`); + // process.stdin.setRawMode(false); + } +} diff --git a/instance/src/systems/terminalUI/terminalEvent.ts b/instance/src/systems/terminalUI/terminalEvent.ts index fcb2892..363548e 100644 --- a/instance/src/systems/terminalUI/terminalEvent.ts +++ b/instance/src/systems/terminalUI/terminalEvent.ts @@ -1,27 +1,27 @@ -import type KeyPressEvent from "./events/keyPressEvent.ts"; -import type MouseClickEvent from "./events/mouseClickEvent.ts"; -import type ResizeScreenEvent from "./events/resizeScreenEvent.ts"; -import type ScrollDownEvent from "./events/scrollDownEvent.ts"; -import type ScrollUpEvent from "./events/scrollUpEvent.ts"; - -export enum TerminalEventType { - MouseClick, - ScrollUp, - ScrollDown, - KeyPress, - ResizeScreen, -} - -export default abstract class TerminalEvent { - abstract type: TerminalEventType; -} - -type TerminalEventMap = { - [TerminalEventType.MouseClick]: MouseClickEvent; - [TerminalEventType.ScrollUp]: ScrollUpEvent; - [TerminalEventType.ScrollDown]: ScrollDownEvent; - [TerminalEventType.KeyPress]: KeyPressEvent; - [TerminalEventType.ResizeScreen]: ResizeScreenEvent; -}; - -export type TerminalEventListener = { type: Ty; cb: (event: TerminalEventMap[Ty]) => void }; +import type KeyPressEvent from "./events/keyPressEvent.ts"; +import type MouseClickEvent from "./events/mouseClickEvent.ts"; +import type ResizeScreenEvent from "./events/resizeScreenEvent.ts"; +import type ScrollDownEvent from "./events/scrollDownEvent.ts"; +import type ScrollUpEvent from "./events/scrollUpEvent.ts"; + +export enum TerminalEventType { + MouseClick, + ScrollUp, + ScrollDown, + KeyPress, + ResizeScreen, +} + +export default abstract class TerminalEvent { + abstract type: TerminalEventType; +} + +type TerminalEventMap = { + [TerminalEventType.MouseClick]: MouseClickEvent; + [TerminalEventType.ScrollUp]: ScrollUpEvent; + [TerminalEventType.ScrollDown]: ScrollDownEvent; + [TerminalEventType.KeyPress]: KeyPressEvent; + [TerminalEventType.ResizeScreen]: ResizeScreenEvent; +}; + +export type TerminalEventListener = { type: Ty; cb: (event: TerminalEventMap[Ty]) => void }; diff --git a/instance/src/systems/terminalUI/view.ts b/instance/src/systems/terminalUI/view.ts index 010e71a..cbd6e11 100644 --- a/instance/src/systems/terminalUI/view.ts +++ b/instance/src/systems/terminalUI/view.ts @@ -6,98 +6,46 @@ import type { TerminalEventListener, TerminalEventType } from "./terminalEvent.t export type TerminalViewContext = TerminalView["viewContext"]; export default abstract class TerminalView { - private viewContext!: { screen: TerminalScreen }; - - definitions: { - dimensions: { - width: TerminalScalarValue; - height: TerminalScalarValue; - minWidth?: TerminalScalarValue; - minHeight?: TerminalScalarValue; - maxWidth?: TerminalScalarValue; - maxHeight?: TerminalScalarValue; - }; - content: { - offset: { - width: TerminalScalarValue; - height: TerminalScalarValue; - }; - dimensions: { - width: TerminalScalarValue; - height: TerminalScalarValue; - }; - }; - absolute: { - dimensions: { - width: number; - height: number; - }; - content: { - offset: { - width: number; - height: number; - }; - dimensions: { - width: number; - height: number; - }; - }; + viewContext!: { screen: TerminalScreen; parentView?: TerminalView }; + + viewProperties: { + width: TerminalScalarValue; + height: TerminalScalarValue; + contentHeight: TerminalScalarValue; + contentWidth: TerminalScalarValue; + contentOffsetX: TerminalScalarValue; + contentOffsetY: TerminalScalarValue; + // managed by calculateAbsoluteProperties (DO NOT EDIT) + _absolute: { + drawOriginX: number; + drawOriginY: number; + width: number; + height: number; + contentWidth: number; + contentHeight: number; + contentOffsetX: number; + contentOffsetY: number; }; } = { - dimensions: { - width: new TerminalScalarValue().set(0, TerminalScalarValueUnit.Pixel), - height: new TerminalScalarValue().set(0, TerminalScalarValueUnit.Pixel), - }, - content: { - offset: { - width: new TerminalScalarValue().set(0, TerminalScalarValueUnit.Pixel), - height: new TerminalScalarValue().set(0, TerminalScalarValueUnit.Pixel), - }, - dimensions: { - width: new TerminalScalarValue().set(0, TerminalScalarValueUnit.Pixel), - height: new TerminalScalarValue().set(0, TerminalScalarValueUnit.Pixel), - }, - }, - absolute: { - content: { - dimensions: { - width: 0, - height: 0, - }, - offset: { - width: 0, - height: 0, - }, - }, - dimensions: { - width: 0, - height: 0, - }, + width: new TerminalScalarValue().set(0, TerminalScalarValueUnit.Cell), + height: new TerminalScalarValue().set(0, TerminalScalarValueUnit.Cell), + contentHeight: new TerminalScalarValue().set(0, TerminalScalarValueUnit.Cell), + contentWidth: new TerminalScalarValue().set(0, TerminalScalarValueUnit.Cell), + contentOffsetX: new TerminalScalarValue().set(0, TerminalScalarValueUnit.Cell), + contentOffsetY: new TerminalScalarValue().set(0, TerminalScalarValueUnit.Cell), + // managed by calculateAbsoluteProperties (DO NOT EDIT) + _absolute: { + drawOriginX: 0, + drawOriginY: 0, + width: 0, + height: 0, + contentWidth: 0, + contentHeight: 0, + contentOffsetX: 0, + contentOffsetY: 0, }, }; - _contentAbsoluteDimensions: { - width: number; - height: number; - } = { - width: 1, - height: 1, - }; - _contentAbsoluteOffset: { - width: number; - height: number; - } = { - width: 1, - height: 1, - }; - _absoluteDimensions: { - width: number; - height: number; - } = { - width: 1, - height: 1, - }; - eventListeners: TerminalEventListener[]; childViews: TerminalView[]; childViewFlowDirection: "x" | "y" = "x"; @@ -111,29 +59,22 @@ export default abstract class TerminalView { this.eventListeners = []; } - _calculateSize(availableSpace: { width: number; height: number }) { - this._absoluteDimensions.width = 16; - this._absoluteDimensions.height = 8; - this._contentAbsoluteDimensions.width = 16; - this._contentAbsoluteDimensions.height = 8; - this._contentAbsoluteOffset.width = 0; - this._contentAbsoluteOffset.height = 0; - - // Dimensions + calculateAbsoluteProperties() { + /* // Dimensions // px - if (this.definitions.dimensions.width.unit === "px") { - this._absoluteDimensions.width = this.definitions.dimensions.width.value; + if (this.viewProperties.dimensions.width.unit === "px") { + this._absoluteDimensions.width = this.viewProperties.dimensions.width.value; } - if (this.definitions.dimensions.height.unit === "px") { - this._absoluteDimensions.height = this.definitions.dimensions.height.value; + if (this.viewProperties.dimensions.height.unit === "px") { + this._absoluteDimensions.height = this.viewProperties.dimensions.height.value; } // % - if (this.definitions.dimensions.width.unit === "%") { - this._absoluteDimensions.width = Math.floor((this.definitions.dimensions.width.value / 100) * parentContentAbsoluteDimensions.width); + if (this.viewProperties.dimensions.width.unit === "%") { + this._absoluteDimensions.width = Math.floor((this.viewProperties.dimensions.width.value / 100) * parentContentAbsoluteDimensions.width); } - if (this.definitions.dimensions.height.unit === "%") { - this._absoluteDimensions.height = Math.floor((this.definitions.dimensions.height.value / 100) * parentContentAbsoluteDimensions.height); + if (this.viewProperties.dimensions.height.unit === "%") { + this._absoluteDimensions.height = Math.floor((this.viewProperties.dimensions.height.value / 100) * parentContentAbsoluteDimensions.height); } if (this._absoluteDimensions.width > parentContentAbsoluteDimensions.width) { @@ -226,11 +167,17 @@ export default abstract class TerminalView { ); break; } + } */ + + if (this.childViewFlowDirection === "x") { + let xWidthPercentageTotal = 0; + for (const childView of this.childViews) { + } } } addChild(view: new (viewContext: TerminalViewContext) => TV, cb?: (view: TV) => void) { - const av = new view(this.viewContext); + const av = new view({ ...this.viewContext, parentView: this }); this.childViews.push(av); @@ -239,14 +186,9 @@ export default abstract class TerminalView { return this; } - async draw(screen: TerminalScreen, parentDrawOrigin: { x: number; y: number }) { - const previousViewOrigin = { x: parentDrawOrigin.x, y: parentDrawOrigin.y }; - + async draw(drawProperties: TerminalView["viewProperties"]["_absolute"]) { for (const childView of this.childViews) { - await childView.draw(screen, previousViewOrigin); - if (this.childViewFlowDirection === "x") previousViewOrigin.x += childView._absoluteDimensions.width; - if (this.childViewFlowDirection === "y") previousViewOrigin.y += childView._absoluteDimensions.height; - // screen.write(JSON.stringify({ parentDrawOrigin, type: childView.constructor.name })); + await childView.draw(drawProperties); } } } diff --git a/instance/src/systems/terminalUI/views/borderView.ts b/instance/src/systems/terminalUI/views/borderView.ts index de0337a..34de2e3 100644 --- a/instance/src/systems/terminalUI/views/borderView.ts +++ b/instance/src/systems/terminalUI/views/borderView.ts @@ -1,32 +1,34 @@ import TerminalEffect, { TerminalColor } from "../effect.ts"; -import type TerminalScreen from "../screen.ts"; +import TerminalScalarValue, { TerminalScalarValueUnit } from "../scalarValue.ts"; import TerminalView, { type TerminalViewContext } from "../view.ts"; export default class TerminalBorderView extends TerminalView { constructor(viewContext: TerminalViewContext) { super(viewContext); - this.definitions.dimensions.width = { unit: "%", value: 100 }; - this.definitions.dimensions.height = { unit: "%", value: 100 }; - this.definitions.contentDimensions.width = { unit: "%", value: 100 }; - this.definitions.contentDimensions.height = { unit: "%", value: 100 }; - this.definitions.contentOffset.width = { unit: "px", value: 1 }; - this.definitions.contentOffset.height = { unit: "px", value: 1 }; + this.viewProperties.width = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.height = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.contentWidth = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.contentHeight = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.contentOffsetX = new TerminalScalarValue(1, TerminalScalarValueUnit.Cell); + this.viewProperties.contentOffsetY = new TerminalScalarValue(1, TerminalScalarValueUnit.Cell); } - override async draw(screen: TerminalScreen, drawOrigin: { x: number; y: number }): Promise { - screen.cursorTo(drawOrigin.x, drawOrigin.y); - screen.write(`┌${"─".repeat(this.absoluteDimensions.width - 2)}┐`, new TerminalEffect().setColor(TerminalColor.BrightBlack)); + override async draw(drawProperties: TerminalView["viewProperties"]["_absolute"]) { + const screen = this.viewContext.screen; - for (let i = 1; i < this.absoluteDimensions.height - 1; i++) { - screen.cursorTo(drawOrigin.x, drawOrigin.y + i); - screen.write(`│${" ".repeat(this.absoluteDimensions.width - 2)}│`, new TerminalEffect().setColor(TerminalColor.BrightBlack)); + screen.cursorTo(drawProperties.drawOriginX, drawProperties.drawOriginY); + screen.write(`┌${"─".repeat(drawProperties.width - 2)}┐`, new TerminalEffect().setColor(TerminalColor.BrightBlack)); + + for (let i = 1; i < drawProperties.height - 1; i++) { + screen.cursorTo(drawProperties.drawOriginX, drawProperties.drawOriginY + i); + screen.write(`│${" ".repeat(drawProperties.width - 2)}│`, new TerminalEffect().setColor(TerminalColor.BrightBlack)); } - screen.cursorTo(drawOrigin.x, this.absoluteDimensions.height); - screen.write(`└${"─".repeat(this.absoluteDimensions.width - 2)}┘`, new TerminalEffect().setColor(TerminalColor.BrightBlack)); + screen.cursorTo(drawProperties.drawOriginX, drawProperties.height); + screen.write(`└${"─".repeat(drawProperties.width - 2)}┘`, new TerminalEffect().setColor(TerminalColor.BrightBlack)); // screen.write(JSON.stringify({ x: drawOrigin.x + this.contentAbsoluteOffset.width, y: drawOrigin.y + this.contentAbsoluteOffset.height })); - await super.draw(screen, { x: drawOrigin.x + this.contentAbsoluteOffset.width, y: drawOrigin.y + this.contentAbsoluteOffset.height }); + await super.draw(drawProperties); } } diff --git a/instance/src/systems/terminalUI/views/container.ts b/instance/src/systems/terminalUI/views/container.ts index 23f387d..5337121 100644 --- a/instance/src/systems/terminalUI/views/container.ts +++ b/instance/src/systems/terminalUI/views/container.ts @@ -1,16 +1,16 @@ -import type TerminalScreen from "../screen.ts"; +import TerminalScalarValue, { TerminalScalarValueUnit } from "../scalarValue.ts"; import TerminalView, { type TerminalViewContext } from "../view.ts"; export default class TerminalContainerView extends TerminalView { constructor(viewContext: TerminalViewContext) { super(viewContext); - this.dimensions.width = { unit: "%", value: 100 }; - this.dimensions.height = { unit: "%", value: 100 }; - this.contentDimensions.width = { unit: "%", value: 100 }; - this.contentDimensions.height = { unit: "%", value: 100 }; - this.contentOffset.width = { unit: "px", value: 0 }; - this.contentOffset.height = { unit: "px", value: 0 }; + this.viewProperties.width = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.height = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.contentWidth = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.contentHeight = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.contentOffsetX = new TerminalScalarValue(0, TerminalScalarValueUnit.Cell); + this.viewProperties.contentOffsetY = new TerminalScalarValue(0, TerminalScalarValueUnit.Cell); } setFlowDirection(flowDirection: "x" | "y") { @@ -19,7 +19,7 @@ export default class TerminalContainerView extends TerminalView { return this; } - override async draw(screen: TerminalScreen, drawOrigin: { x: number; y: number }): Promise { - await super.draw(screen, { x: drawOrigin.x + this.contentAbsoluteOffset.width, y: drawOrigin.y + this.contentAbsoluteOffset.height }); + override async draw(drawProperties: TerminalView["viewProperties"]["_absolute"]): Promise { + await super.draw(drawProperties); } } diff --git a/instance/src/systems/terminalUI/views/crossView.ts b/instance/src/systems/terminalUI/views/crossView.ts index 10f4d9b..0575219 100644 --- a/instance/src/systems/terminalUI/views/crossView.ts +++ b/instance/src/systems/terminalUI/views/crossView.ts @@ -1,4 +1,5 @@ import TerminalEffect, { TerminalColor } from "../effect.ts"; +import TerminalScalarValue, { TerminalScalarValueUnit } from "../scalarValue.ts"; import type TerminalScreen from "../screen.ts"; import TerminalView, { type TerminalViewContext } from "../view.ts"; @@ -6,17 +7,19 @@ export default class TerminalCrossView extends TerminalView { constructor(viewContext: TerminalViewContext) { super(viewContext); - this.dimensions.width = { unit: "%", value: 100 }; - this.dimensions.height = { unit: "%", value: 100 }; - this.contentDimensions.width = { unit: "%", value: 100 }; - this.contentDimensions.height = { unit: "%", value: 100 }; - this.contentOffset.width = { unit: "px", value: 0 }; - this.contentOffset.height = { unit: "px", value: 0 }; + this.viewProperties.width = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.height = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.contentWidth = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.contentHeight = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.contentOffsetX = new TerminalScalarValue(0, TerminalScalarValueUnit.Cell); + this.viewProperties.contentOffsetY = new TerminalScalarValue(0, TerminalScalarValueUnit.Cell); } - override async draw(screen: TerminalScreen, drawOrigin: { x: number; y: number }): Promise { - if (this.absoluteDimensions.width < 31 || this.absoluteDimensions.height < 3) { - screen.cursorTo(drawOrigin.x, drawOrigin.y); + override async draw(drawProperties: TerminalView["viewProperties"]["_absolute"]): Promise { + const screen = this.viewContext.screen; + + if (drawProperties.width < 31 || drawProperties.height < 3) { + screen.cursorTo(drawProperties.drawOriginX, drawProperties.drawOriginY); screen.write("Too Small to display CrossView"); return; } @@ -33,60 +36,60 @@ export default class TerminalCrossView extends TerminalView { let horizontalAlignment: HorizontalAlignment; let verticalAlignment: VerticalAlignment; - if (this.absoluteDimensions.width % 2 === 0) { + if (drawProperties.width % 2 === 0) { horizontalAlignment = HorizontalAlignment.Even; } else { horizontalAlignment = HorizontalAlignment.Odd; } - if (this.absoluteDimensions.height % 2 === 0) { + if (drawProperties.height % 2 === 0) { verticalAlignment = VerticalAlignment.Even; } else { verticalAlignment = VerticalAlignment.Odd; } - const labelText = `${this.absoluteDimensions.width}x${this.absoluteDimensions.height}`; + const labelText = `${drawProperties.width}x${drawProperties.height}`; let labelTextOffsetX = 0; let labelTextOffsetY = 0; - screen.cursorTo(drawOrigin.x, drawOrigin.y); + screen.cursorTo(drawProperties.drawOriginX, drawProperties.drawOriginY); if (horizontalAlignment === HorizontalAlignment.Odd) { - screen.write(`${" ".repeat((this.absoluteDimensions.width - 1) / 2)}▲${" ".repeat((this.absoluteDimensions.width - 1) / 2)}`); + screen.write(`${" ".repeat((drawProperties.width - 1) / 2)}▲${" ".repeat((drawProperties.width - 1) / 2)}`); - for (let i = 1; i < this.absoluteDimensions.height - 1; i++) { - screen.cursorTo(drawOrigin.x, drawOrigin.y + i); - screen.write(`${" ".repeat((this.absoluteDimensions.width - 1) / 2)}│${" ".repeat((this.absoluteDimensions.width - 1) / 2)}`); + for (let i = 1; i < drawProperties.height - 1; i++) { + screen.cursorTo(drawProperties.drawOriginX, drawProperties.drawOriginY + i); + screen.write(`${" ".repeat((drawProperties.width - 1) / 2)}│${" ".repeat((drawProperties.width - 1) / 2)}`); labelTextOffsetX = - drawOrigin.x + (this.absoluteDimensions.width - 1) / 2 - (labelText.length % 2 === 0 ? labelText.length / 2 : (labelText.length - 1) / 2); + drawProperties.drawOriginX + (drawProperties.width - 1) / 2 - (labelText.length % 2 === 0 ? labelText.length / 2 : (labelText.length - 1) / 2); } - screen.cursorTo(drawOrigin.x, drawOrigin.y + (this.absoluteDimensions.height - 1)); - screen.write(`${" ".repeat((this.absoluteDimensions.width - 1) / 2)}▼${" ".repeat((this.absoluteDimensions.width - 1) / 2)}`); + screen.cursorTo(drawProperties.drawOriginX, drawProperties.drawOriginY + (drawProperties.height - 1)); + screen.write(`${" ".repeat((drawProperties.width - 1) / 2)}▼${" ".repeat((drawProperties.width - 1) / 2)}`); } else { - screen.write(`${" ".repeat(this.absoluteDimensions.width / 2 - 1)}▲${" ".repeat(this.absoluteDimensions.width / 2)}`); + screen.write(`${" ".repeat(drawProperties.width / 2 - 1)}▲${" ".repeat(drawProperties.width / 2)}`); - for (let i = 1; i < this.absoluteDimensions.height - 1; i++) { - screen.cursorTo(drawOrigin.x, drawOrigin.y + i); - screen.write(`${" ".repeat(this.absoluteDimensions.width / 2 - 1)}│${" ".repeat(this.absoluteDimensions.width / 2)}`); + for (let i = 1; i < drawProperties.height - 1; i++) { + screen.cursorTo(drawProperties.drawOriginX, drawProperties.drawOriginY + i); + screen.write(`${" ".repeat(drawProperties.width / 2 - 1)}│${" ".repeat(drawProperties.width / 2)}`); labelTextOffsetX = - drawOrigin.x + this.absoluteDimensions.width / 2 - 1 - (labelText.length % 2 === 0 ? labelText.length / 2 : (labelText.length - 1) / 2); + drawProperties.drawOriginX + drawProperties.width / 2 - 1 - (labelText.length % 2 === 0 ? labelText.length / 2 : (labelText.length - 1) / 2); } - screen.cursorTo(drawOrigin.x, drawOrigin.y + this.absoluteDimensions.height - 1); - screen.write(`${" ".repeat(this.absoluteDimensions.width / 2 - 1)}▼${" ".repeat(this.absoluteDimensions.width / 2)}`); + screen.cursorTo(drawProperties.drawOriginX, drawProperties.drawOriginY + drawProperties.height - 1); + screen.write(`${" ".repeat(drawProperties.width / 2 - 1)}▼${" ".repeat(drawProperties.width / 2)}`); } if (verticalAlignment === VerticalAlignment.Odd) { - screen.cursorTo(drawOrigin.x, drawOrigin.y + (this.absoluteDimensions.height - 1) / 2); - screen.write(`◀${"─".repeat(this.absoluteDimensions.width - 2)}▶`); + screen.cursorTo(drawProperties.drawOriginX, drawProperties.drawOriginY + (drawProperties.height - 1) / 2); + screen.write(`◀${"─".repeat(drawProperties.width - 2)}▶`); - labelTextOffsetY = drawOrigin.y + (this.absoluteDimensions.height - 1) / 2; + labelTextOffsetY = drawProperties.drawOriginY + (drawProperties.height - 1) / 2; } else { - screen.cursorTo(drawOrigin.x, drawOrigin.y + this.absoluteDimensions.height / 2 - 1); - screen.write(`◀${"─".repeat(this.absoluteDimensions.width - 2)}▶`); - labelTextOffsetY = drawOrigin.y + this.absoluteDimensions.height / 2 - 1; + screen.cursorTo(drawProperties.drawOriginX, drawProperties.drawOriginY + drawProperties.height / 2 - 1); + screen.write(`◀${"─".repeat(drawProperties.width - 2)}▶`); + labelTextOffsetY = drawProperties.drawOriginY + drawProperties.height / 2 - 1; } screen.cursorTo(labelTextOffsetX, labelTextOffsetY); @@ -94,20 +97,20 @@ export default class TerminalCrossView extends TerminalView { screen.write("x", new TerminalEffect().setColor(TerminalColor.White)); screen.write(labelText.split("x")[1], new TerminalEffect().setColor(TerminalColor.BrightWhite).setBold()); - // screen.write(`${" ".repeat(Math.floor((this.absoluteDimensions.width - 1) / 2))} ▲${" ".repeat(Math.floor((this.absoluteDimensions.width - 1) / 2))}`); + // screen.write(`${" ".repeat(Math.floor((drawProperties.width - 1) / 2))} ▲${" ".repeat(Math.floor((drawProperties.width - 1) / 2))}`); - // for (let i = 1; i < this.absoluteDimensions.height; i++) { - // screen.cursorTo(drawOrigin.x, drawOrigin.y + i); - // if (i === Math.floor(this.absoluteDimensions.height / 2) - 1) { - // const dashLen = Math.floor((this.absoluteDimensions.width - dimensionText.length) / 2) - 2; + // for (let i = 1; i < drawProperties.height; i++) { + // screen.cursorTo(drawProperties.drawOriginX, drawProperties.drawOriginY + i); + // if (i === Math.floor(drawProperties.height / 2) - 1) { + // const dashLen = Math.floor((drawProperties.width - dimensionText.length) / 2) - 2; // screen.write(`◀${"─".repeat(dashLen)}${dimensionText}${"─".repeat(dashLen)}▶`); // } else { - // screen.write(`${" ".repeat(Math.floor((this.absoluteDimensions.width - 1) / 2))} │${" ".repeat(Math.floor((this.absoluteDimensions.width - 1) / 2))}`); + // screen.write(`${" ".repeat(Math.floor((drawProperties.width - 1) / 2))} │${" ".repeat(Math.floor((drawProperties.width - 1) / 2))}`); // } // } - // screen.cursorTo(drawOrigin.x, drawOrigin.y + this.absoluteDimensions.height); - // screen.write(`${" ".repeat(Math.floor((this.absoluteDimensions.width - 1) / 2))} ▼${" ".repeat(Math.floor((this.absoluteDimensions.width - 1) / 2))}`); + // screen.cursorTo(drawProperties.drawOriginX, drawProperties.drawOriginY + drawProperties.height); + // screen.write(`${" ".repeat(Math.floor((drawProperties.width - 1) / 2))} ▼${" ".repeat(Math.floor((drawProperties.width - 1) / 2))}`); - await super.draw(screen, { x: drawOrigin.x + this.contentAbsoluteOffset.width, y: drawOrigin.y + this.contentAbsoluteOffset.height }); + await super.draw(drawProperties); } } diff --git a/instance/src/systems/terminalUI/views/textInput.ts b/instance/src/systems/terminalUI/views/textInput.ts index a2f7f3a..d921de2 100644 --- a/instance/src/systems/terminalUI/views/textInput.ts +++ b/instance/src/systems/terminalUI/views/textInput.ts @@ -1,4 +1,5 @@ import TerminalEffect from "../effect.ts"; +import TerminalScalarValue, { TerminalScalarValueUnit } from "../scalarValue.ts"; import type TerminalScreen from "../screen.ts"; import TerminalView, { type TerminalViewContext } from "../view.ts"; @@ -9,12 +10,12 @@ export default class TerminalTextInputView extends TerminalView { constructor(viewContext: TerminalViewContext) { super(viewContext); - this.dimensions.width = { unit: "%", value: 100 }; - this.dimensions.height = { unit: "px", value: 1 }; - this.contentDimensions.width = { unit: "%", value: 100 }; - this.contentDimensions.height = { unit: "%", value: 100 }; - this.contentOffset.width = { unit: "px", value: 0 }; - this.contentOffset.height = { unit: "px", value: 0 }; + this.viewProperties.width = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.height = new TerminalScalarValue(1, TerminalScalarValueUnit.Cell); + this.viewProperties.contentWidth = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.contentHeight = new TerminalScalarValue(100, TerminalScalarValueUnit.Percentage); + this.viewProperties.contentOffsetX = new TerminalScalarValue(0, TerminalScalarValueUnit.Cell); + this.viewProperties.contentOffsetY = new TerminalScalarValue(0, TerminalScalarValueUnit.Cell); this.value = ""; this.placeholder = undefined; @@ -26,12 +27,14 @@ export default class TerminalTextInputView extends TerminalView { return this; } - override async draw(screen: TerminalScreen, drawOrigin: { x: number; y: number }): Promise { - screen.cursorTo(drawOrigin.x, drawOrigin.y); - screen.write(`${" ".repeat(this.absoluteDimensions.width)}`, new TerminalEffect().setUnderline()); - screen.cursorTo(drawOrigin.x, drawOrigin.y); + override async draw(drawProperties: TerminalView["viewProperties"]["_absolute"]): Promise { + const screen = this.viewContext.screen; + + screen.cursorTo(drawProperties.drawOriginX, drawProperties.drawOriginY); + screen.write(`${" ".repeat(drawProperties.width)}`, new TerminalEffect().setUnderline()); + screen.cursorTo(drawProperties.drawOriginX, drawProperties.drawOriginY); if (this.value === "" && this.placeholder !== undefined) screen.write(`${this.placeholder}`, new TerminalEffect().setUnderline()); - await super.draw(screen, { x: drawOrigin.x + this.contentAbsoluteOffset.width, y: drawOrigin.y + this.contentAbsoluteOffset.height }); + await super.draw(drawProperties); } } diff --git a/instance/src/systems/trpc.ts b/instance/src/systems/trpc.ts index 4d14b75..327b604 100644 --- a/instance/src/systems/trpc.ts +++ b/instance/src/systems/trpc.ts @@ -1,89 +1,89 @@ -import type { TRPCBuiltRouter } from "@trpc/server"; -import { type FetchCreateContextFnOptions, fetchRequestHandler } from "@trpc/server/adapters/fetch"; -import type { BunRequest, Server } from "bun"; -import type { Instance } from "../index.ts"; -import System from "../system.ts"; -import type { createTRPCContext } from "./trpcRouter.ts"; - -export default class TRPCSystem extends System { - registeredRouters: { - basePath: string; - router: TRPCBuiltRouter; - createContext: (opts: FetchCreateContextFnOptions, server: Server>) => object; - }[]; - - constructor(instance: Instance) { - super("trpc", instance); - - this.registeredRouters = []; - } - - override async startup(): Promise { - this.log.info("Starting up..."); - return true; - } - - private attemptTRPCRequest(req: BunRequest, server: Server>) { - const url = new URL(req.url); - - for (const router of this.registeredRouters) { - if (!url.pathname.startsWith(router.basePath)) { - continue; - } - - return fetchRequestHandler({ - createContext: (opts) => router.createContext(opts, server), - req, - endpoint: router.basePath ?? "", - router: router.router, - }); - } - - return; - } - - // private bunWebSocketHandler() {} - - serve(options: { - routes: { - [path: string]: { - GET?: (req: BunRequest) => Promise; - POST?: (req: BunRequest) => Promise; - DELETE?: (req: BunRequest) => Promise; - PUT?: (req: BunRequest) => Promise; - }; - }; - fetch(request: any, server: any): Response; - development: boolean; - }) { - const self = this; - - return { - ...options, - port: 3563, - hostname: "0.0.0.0", - async fetch(req: BunRequest, server: Server>) { - try { - const trpcResponse = await self.attemptTRPCRequest(req, server); - if (trpcResponse) { - return trpcResponse; - } else { - return new Response("Hello from Workspaces!"); - } - } catch (err) { - self.log.error(err); - console.error(new Error("tRPC -----").stack); - return new Response("TRPC failed"); - } - }, - onError: (...p: any[]) => { - // Do nothing as the error is most-likely from bun.serve for tRPC contentType, (i have no clue why as everything else is working) - if (p[0].type === "unknown") return; - if (p[0].error.code === "UNAUTHORIZED") return; - - console.error(p[0].error); - this.log.error("^"); - }, - }; - } -} +import type { TRPCBuiltRouter } from "@trpc/server"; +import { type FetchCreateContextFnOptions, fetchRequestHandler } from "@trpc/server/adapters/fetch"; +import type { BunRequest, Server } from "bun"; +import type { Instance } from "../index.ts"; +import System from "../system.ts"; +import type { createTRPCContext } from "./trpcRouter.ts"; + +export default class TRPCSystem extends System { + registeredRouters: { + basePath: string; + router: TRPCBuiltRouter; + createContext: (opts: FetchCreateContextFnOptions, server: Server>) => object; + }[]; + + constructor(instance: Instance) { + super("trpc", instance); + + this.registeredRouters = []; + } + + override async startup(): Promise { + this.log.info("Starting up..."); + return true; + } + + private attemptTRPCRequest(req: BunRequest, server: Server>) { + const url = new URL(req.url); + + for (const router of this.registeredRouters) { + if (!url.pathname.startsWith(router.basePath)) { + continue; + } + + return fetchRequestHandler({ + createContext: (opts) => router.createContext(opts, server), + req, + endpoint: router.basePath ?? "", + router: router.router, + }); + } + + return; + } + + // private bunWebSocketHandler() {} + + serve(options: { + routes: { + [path: string]: { + GET?: (req: BunRequest) => Promise; + POST?: (req: BunRequest) => Promise; + DELETE?: (req: BunRequest) => Promise; + PUT?: (req: BunRequest) => Promise; + }; + }; + fetch(request: any, server: any): Response; + development: boolean; + }) { + const self = this; + + return { + ...options, + port: 3563, + hostname: "0.0.0.0", + async fetch(req: BunRequest, server: Server>) { + try { + const trpcResponse = await self.attemptTRPCRequest(req, server); + if (trpcResponse) { + return trpcResponse; + } else { + return new Response("Hello from Workspaces!"); + } + } catch (err) { + self.log.error(err); + console.error(new Error("tRPC -----").stack); + return new Response("TRPC failed"); + } + }, + onError: (...p: any[]) => { + // Do nothing as the error is most-likely from bun.serve for tRPC contentType, (i have no clue why as everything else is working) + if (p[0].type === "unknown") return; + if (p[0].error.code === "UNAUTHORIZED") return; + + console.error(p[0].error); + this.log.error("^"); + }, + }; + } +} diff --git a/instance/src/systems/trpcRouter.ts b/instance/src/systems/trpcRouter.ts index 1d31ed3..80b4db3 100644 --- a/instance/src/systems/trpcRouter.ts +++ b/instance/src/systems/trpcRouter.ts @@ -1,745 +1,745 @@ -import * as nodeCrypto from "node:crypto"; -import { on } from "node:events"; -import { initTRPC, TRPCError } from "@trpc/server"; -import type { FetchCreateContextFnOptions } from "@trpc/server/adapters/fetch"; -import type { Server } from "bun"; -import * as hiBase32 from "hi-base32"; -import * as OTPAuth from "otpauth"; -import z from "zod"; -import type { Instance } from "../index.ts"; -import { AuthorizedDeviceType } from "./authorization.ts"; -import { WorkspacesFeatureFlags } from "./configuration.ts"; -import { type WorkspacesNotification, WorkspacesNotificationEventEmitterEvent } from "./notifications.ts"; -import type { WorkspacesUser } from "./users.ts"; - -export const createTRPCContext = (instance: Instance) => (opt: FetchCreateContextFnOptions, server: Server) => { - return { - rawRequest: { - req: opt.req, - resHeaders: opt.resHeaders, - server: server, - }, - instance: instance, - }; -}; - -export const t = initTRPC.context>().create({ - sse: { - ping: { - // Enable periodic ping messages to keep connection alive - enabled: true, - // Send ping message every 2s - intervalMs: 4000, - }, - client: { - reconnectAfterInactivityMs: 5000, - }, - }, -}); - -export const publicProcedure = t.procedure.use(async (opt) => { - return opt.next({ - ctx: { - userId: "THIS CAN ONLY BE ACCESSED FROM A NON-PUBLIC PROCEDURE", - }, - }); -}); -export const procedure = t.procedure.use(async (opt) => { - // console.log(opt.ctx.req.headers); - - /* - if (!ctx.user?.isAdmin) { - throw new TRPCError({ code: 'UNAUTHORIZED' }); - } - */ - - const cookieString = opt.ctx.rawRequest.req.headers?.get("cookie"); - - if (cookieString === null) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "missing auth cookie", - }); - } - - const parsedCookie = Bun.Cookie.parse(cookieString); - - const userId = await opt.ctx.instance.sys.authorization.verifySession(decodeURIComponent(parsedCookie.value)); - - if (userId === undefined) { - throw new TRPCError({ code: "UNAUTHORIZED", message: "invalid session" }); - } - - return opt.next({ - ctx: { - userId: userId, - user: (): Promise => - // @ts-ignore - opt.ctx.instance.sys.users.getUserById(userId), - }, - }); -}); -export const adminProcedure = procedure.use(async (opt) => { - const user = await opt.ctx.instance.sys.users.getUserById(opt.ctx.userId); - - if (!user) { - throw new TRPCError({ code: "UNAUTHORIZED", message: "invalid session" }); - } - - if (!(await user.isAdministrator())) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "user lacks administrator permissions", - }); - } - - return opt.next(); -}); - -const temporaryTwoFactorSecrets: Map = new Map(); -const emailSignupVerificationCodes: Map = new Map(); -const notifications: WorkspacesNotification[] = []; - -export const workspacesRouter = t.router({ - authorization: { - signupRequirements: publicProcedure - .output( - z.object({ - email: z.boolean(), - twoFactorAuthentication: z.boolean(), - passwordMinimumLength: z.number().optional(), - passwordContains: z - .object({ - minimumUppercase: z.number().optional(), - minimumLowercase: z.number().optional(), - minimumNumbers: z.number().optional(), - minimumSymbols: z.number().optional(), - }) - .optional(), - }), - ) - .query(async (opt) => { - return opt.ctx.instance.sys.configuration.signupRequirements; - }), - checkEmailAddressOwnership: publicProcedure - .input(z.object({ emailAddress: z.string() })) - .output(z.boolean().or(z.string())) - .mutation(async (opt) => { - if (emailSignupVerificationCodes.has(opt.input.emailAddress)) { - return "An email has already been sent, please wait 5 minutes before sending another."; - } - - let emailCode = ""; - const CODE_LENGTH = 8; - const CODE_VALID_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - for (let i = CODE_LENGTH; i > 0; --i) emailCode += CODE_VALID_CHARS[Math.floor(Math.random() * CODE_VALID_CHARS.length)]; - - emailSignupVerificationCodes.set(opt.input.emailAddress, emailCode); - // TODO: send an email... - opt.ctx.instance.log.system.info(`Email code for email '${opt.input.emailAddress}' is '${emailCode}'`); - - return true; - }), - validateEmailCode: publicProcedure.input(z.object({ emailAddress: z.string(), emailCode: z.string() })).query(async (opt) => { - if (emailSignupVerificationCodes.get(opt.input.emailAddress) === opt.input.emailCode) { - return true; - } - - return false; - }), - isUsernameValid: publicProcedure.input(z.string()).query(async (opt) => { - if ((await opt.ctx.instance.sys.users.getUserByUsername(opt.input)) === undefined) return true; - - return false; - }), - canSignup: publicProcedure.query(async (opt) => { - if (opt.ctx.instance.sys.configuration.hasFeature(WorkspacesFeatureFlags.AllowUserSignups)) return true; - - return false; - }), - signup: publicProcedure - .input( - z.union([ - z.object({ - username: z.string(), - password: z.string(), - emailAddress: z.string(), - emailCode: z.string(), - displayName: z.string(), - gender: z.string(), - bio: z.string(), - }), - z.object({ - username: z.string(), - password: z.string(), - displayName: z.string(), - gender: z.string(), - bio: z.string(), - }), - ]), - ) - .output( - z.union([ - z.object({ type: z.literal("error"), message: z.string() }), - z.object({ - type: z.literal("success"), - sessionToken: z.string(), - notice: z.boolean().optional(), - }), - ]), - ) - .mutation(async (opt) => { - if (!opt.ctx.instance.sys.configuration.hasFeature(WorkspacesFeatureFlags.AllowUserSignups)) - return { - type: "error", - message: "This instance has disabled user signups", - }; - - const username = opt.input.username.toLowerCase(); - - if (opt.ctx.instance.sys.configuration.signupRequirements.email) { - if (!("emailAddress" in opt.input)) { - return { - type: "error", - message: "This instance requires an email address for signups!", - }; - } - - if (opt.input.emailCode !== emailSignupVerificationCodes.get(opt.input.emailAddress)) - return { - type: "error", - message: "The email code did not match!", - }; - } - - const uid = await opt.ctx.instance.sys.users.createUser(username, opt.input.password); - - if (uid === undefined) - return { - type: "error", - message: "Failed to create the user", - }; - - const user = await opt.ctx.instance.sys.users.getUserById(uid); - - if (user === undefined) - return { - type: "error", - message: "Failed to fetch the user", - }; - - const splitDisplayName = opt.input.displayName.split(" "); - await user.setFullName(splitDisplayName[0], splitDisplayName.slice(1).join(" ")); - - if ("emailAddress" in opt.input) { - await user.setEmail(opt.input.emailAddress); - } - - await user.setBio(opt.input.bio); - - if (opt.input.gender === "male" || opt.input.gender === "female" || opt.input.gender === "other") await user.setGender(opt.input.gender); - - // TODO: get default quota size from the instance config - await user.setQuota(20); - - const session = await opt.ctx.instance.sys.authorization.createPasswordSession( - user.userId, - opt.input.password, - AuthorizedDeviceType.UnknownBrowser, - undefined, - opt.ctx.rawRequest.req.headers.get("X-Real-IP")?.split(":")?.[0] || "missing-caddy-ip", - ); - - if (session === undefined) { - return { - type: "error", - message: "Failed to create a session?", - }; - } - - opt.ctx.rawRequest.resHeaders.set( - "set-cookie", - Bun.Cookie.from("Authorization", session, { - secure: false, - expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 14).toUTCString(), - }).serialize(), - ); - - return { - type: "success", - sessionToken: session, - }; - }), - confirmTwoFactor: procedure.input(z.object({ twoFactorCode: z.string() })).mutation(async (opt) => { - const user = await opt.ctx.user(); - const secretString = temporaryTwoFactorSecrets.get(user.userId); - - if (secretString === undefined) { - opt.ctx.instance.log.system.warning( - `(${user.userId})${await user.getUsername()} Tried to confirm a two factor code, but they lacked a temporary secret?`, - ); - - return false; - } - - const totp = new OTPAuth.TOTP({ - issuer: opt.ctx.instance.sys.configuration.proxyUrl[0], - label: `${opt.ctx.instance.sys.configuration.displayName} (Workspace)`, - algorithm: "SHA1", - digits: 6, - secret: secretString, - }); - - if (totp.validate({ token: opt.input.twoFactorCode }) !== null) { - temporaryTwoFactorSecrets.delete(user.userId); - await opt.ctx.instance.sys.authorization.setTwoFactorAuthenticationSecret(user.userId, secretString); - opt.ctx.instance.log.system.success(`(${user.userId})${await user.getUsername()} Setup two-factor authentication on their account!`); - - return true; - } - - return false; - }), - enableTwoFactor: procedure - .output( - z - .object({ - twoFactorSecret: z.string(), - twoFactorSecretURI: z.string(), - }) - .optional(), - ) - .mutation(async (opt) => { - const generateSecretString = () => { - const buffer = nodeCrypto.randomBytes(15); - const base32 = hiBase32.encode(buffer).replace(/=/g, "").substring(0, 24); - return base32; - }; - - const user = await opt.ctx.user(); - - if (await opt.ctx.instance.sys.authorization.hasTwoFactorAuthenticationSecret(user.userId)) { - opt.ctx.instance.log.system.warning( - `User (${user.userId})${await user.getUsername()} has attempted to re-setup their two factor from the signup method... this is suspicious...`, - ); - - return undefined; - } - - let secretString = generateSecretString(); - const prevSecretString = temporaryTwoFactorSecrets.get(user.userId); - - if (prevSecretString) { - secretString = prevSecretString; - } - - const totp = new OTPAuth.TOTP({ - issuer: opt.ctx.instance.sys.configuration.proxyUrl[0], - label: `${opt.ctx.instance.sys.configuration.displayName} (Workspace)`, - algorithm: "SHA1", - digits: 6, - secret: secretString, - }); - - temporaryTwoFactorSecrets.set(user.userId, secretString); - - return { - twoFactorSecretURI: totp.toString(), - twoFactorSecret: secretString, - }; - }), - passwordSignin: publicProcedure - .input( - z.object({ - username: z.string(), - password: z.string(), - twoFactorCode: z.string().optional(), - }), - ) - .output( - z.union([ - z.object({ type: z.literal("error"), message: z.string() }), - z.object({ type: z.literal("success"), sessionToken: z.string() }), - z.object({ type: z.literal("twofactor") }), - ]), - ) - .mutation(async (opt) => { - const username = opt.input.username.toLowerCase(); - const user = await opt.ctx.instance.sys.users.getUserByUsername(username); - - if (user === undefined) - return { - type: "error", - message: "Failed to find the user", - }; - - if (await opt.ctx.instance.sys.authorization.hasTwoFactorAuthenticationSecret(user.userId)) { - if (opt.input.twoFactorCode === undefined) - return { - type: "twofactor", - }; - } - - const session = await opt.ctx.instance.sys.authorization.createPasswordSession( - user.userId, - opt.input.password, - AuthorizedDeviceType.UnknownBrowser, - opt.input.twoFactorCode, - opt.ctx.rawRequest.req.headers.get("X-Real-IP")?.split(":")?.[0] || "missing-caddy-ip", - ); - - if (session === undefined) { - return { - type: "error", - message: "Failed to create a session?", - }; - } - - opt.ctx.rawRequest.resHeaders.set( - "set-cookie", - Bun.Cookie.from("Authorization", session, { - secure: false, - expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 14).toUTCString(), - }).serialize(), - ); - - return { - type: "success", - sessionToken: session, - }; - }), - passkeyRequestSignin: publicProcedure - .input( - z.object({ - username: z.string(), - }), - ) - .query(async (opt) => { - const user = await opt.ctx.instance.sys.users.getUserByUsername(opt.input.username.toLowerCase()); - - if (user === undefined) { - return undefined; - } - - return opt.ctx.instance.sys.authorization.requestPasskeySession(user.userId); - }), - passkeyCompleteSignin: publicProcedure - .input( - z.object({ - username: z.string(), - passkeyResponse: z.any(), - }), - ) - .mutation(async (opt) => { - const user = await opt.ctx.instance.sys.users.getUserByUsername(opt.input.username.toLowerCase()); - - if (user === undefined) { - throw new TRPCError({ - code: "NOT_FOUND", - message: "Failed to find the user", - }); - } - - const session = await opt.ctx.instance.sys.authorization.createPasskeySession( - user.userId, - AuthorizedDeviceType.UnknownBrowser, - opt.input.passkeyResponse, - opt.ctx.rawRequest.req.headers.get("X-Real-IP")?.split(":")?.[0] || "missing-caddy-ip", - ); - - if (session === undefined) { - return { - type: "error", - message: "Failed to create a session?", - }; - } - - opt.ctx.rawRequest.resHeaders.set( - "set-cookie", - Bun.Cookie.from("Authorization", session, { - secure: false, - expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 14).toUTCString(), - }).serialize(), - ); - - return { - type: "success", - sessionToken: session, - }; - }), - isAuthenticated: publicProcedure.output(z.object({ authenticated: z.boolean() })).query(async (opt) => { - const cookieString = opt.ctx.rawRequest.req.headers?.get("cookie"); - - if (cookieString === null) { - return { - authenticated: false, - }; - } - - const parsedCookie = Bun.Cookie.parse(cookieString); - - const userId = await opt.ctx.instance.sys.authorization.verifySession(decodeURIComponent(parsedCookie.value)); - - if (userId === undefined) { - return { - authenticated: false, - }; - } - - return { - authenticated: true, - }; - }), - logout: procedure.output(z.object({ success: z.literal(true) })).mutation(async (opt) => { - const cookieString = opt.ctx.rawRequest.req.headers?.get("cookie"); - - if (cookieString === null) { - return { - success: true, - }; - } - - const parsedCookie = Bun.Cookie.parse(cookieString); - - await opt.ctx.instance.sys.authorization.endSessionByToken(decodeURIComponent(parsedCookie.value)); - - return { - success: true, - }; - }), - }, - termsOfUse: publicProcedure.query(async (opt) => { - const date = new Date(opt.ctx.instance.sys.configuration.termsOfUse.lastUpdated); - - const localeDateString: string = date.toLocaleDateString("en-GB", { - day: "numeric", - month: "long", - year: "numeric", - }); - - const getOrdinalSuffix = (day: number): string => { - if (day > 3 && day < 21) return "th"; - switch (day % 10) { - case 1: - return "st"; - case 2: - return "nd"; - case 3: - return "rd"; - default: - return "th"; - } - }; - - const day: number = date.getDate(); - const formattedDate: string = `${day}${getOrdinalSuffix(day)} ${localeDateString.split(" ")[1]}, ${localeDateString.split(" ")[2]}`; - - return `Terms of Use: ${opt.ctx.instance.sys.configuration.displayName} -Effective Date: ${formattedDate} - -${opt.ctx.instance.sys.configuration.termsOfUse.message}`; - }), - app: { - navigation: { - user: { - name: procedure - .output( - z.object({ - username: z.string(), - forename: z.string(), - surname: z.string(), - }), - ) - .query(async (opt) => { - const db = opt.ctx.instance.sys.database.postgres(); - - const user = (await db`SELECT username, forename, surname FROM users WHERE id = ${opt.ctx.userId};`)?.[0]; - - if (!user) { - throw new TRPCError({ - code: "NOT_FOUND", - cause: { message: "User does not exist" }, - }); - } - - return { - username: user.username || "@", - forename: user.forename || "Unknown", - surname: user.surname || "", - }; - }), - }, - getApplications: procedure - .output( - z.array( - z.object({ - location: z.object({ - type: z.union([z.literal("local"), z.literal("remote")]), - value: z.string(), - }), - icon: z.object({ - type: z.union([z.literal("icon"), z.literal("image")]), - value: z.string(), - }), - label: z.string(), - id: z.string(), - }), - ), - ) - .query(async (opt) => { - const applications = opt.ctx.instance.sys.applications.getEnabledApplications(); - - return applications.map((app) => { - let icon = { - type: "icon" as "icon" | "image", - value: "indeterminate_question_box", - }; - - if (app.manifest?.icon) { - if (app.manifest.icon.type === "image") { - icon = { - type: "image", - value: `${opt.ctx.instance.sys.configuration.proxyUrl}/api/application/${app.manifest.id}/icon/`, - }; - } else { - icon = { - type: "icon", - value: `${opt.ctx.instance.sys.configuration.proxyUrl}/api/application/${app.manifest.id}/icon/`, - }; - } - } - - return { - icon: icon, - label: app.manifest?.displayName || "Unknown", - location: { - type: "local", - value: `/app/${app.manifest?.id}` || "/404", - }, - id: app.manifest?.id || "unknown", - }; - }); - }), - getQuickShortcuts: procedure.query(async (opt) => { - const a = opt.ctx.instance.sys.settings.applicationSettings["core"].find((s) => s.id === "quick_shortcuts"); - - if (!a) throw "The core:quick_shortcuts setting is somehow missing???"; - - const quickShortcuts = (await a.onValueChange(opt.ctx.userId)) as string[]; - - const applications = opt.ctx.instance.sys.applications.getEnabledApplications(); - - return quickShortcuts - .map((shortcut) => { - const app = applications.find((a) => a.manifest?.id === shortcut); - - if (!app) return undefined; - - let icon = { - type: "icon" as "icon" | "image", - // TODO: replace this with an image link! - value: "indeterminate_question_box", - }; - - if (app.manifest?.icon) { - if (app.manifest.icon.type === "image") { - icon = { - type: "image", - value: `${opt.ctx.instance.sys.configuration.proxyUrl}/api/application/${app.manifest.id}/icon/`, - }; - } else { - icon = { - type: "icon", - value: `${opt.ctx.instance.sys.configuration.proxyUrl}/api/application/${app.manifest.id}/icon/`, - }; - } - } - - return { - icon: icon, - label: app.manifest?.displayName || "Unknown", - location: { - type: "local", - value: `/app/${app.manifest?.id}` || "/404", - }, - id: app.manifest?.id || "unknown", - }; - }) - .filter((qs) => qs !== undefined); - }), - }, - notifications: { - listener: procedure - // @ts-ignore - .subscription(async function* (opt) { - for await (const [data] of on(opt.ctx.instance.sys.notifications.eventEmitter, WorkspacesNotificationEventEmitterEvent.SendNotification, { - signal: opt.signal, - })) { - const notification = data as WorkspacesNotification; - if (notification.recipient === opt.ctx.userId) { - notifications.push(notification); - - yield notification; - } - } - }), - respond: procedure - .input( - z.object({ - uuid: z.string(), - responseType: z.literal("button"), - value: z.string(), - }), - ) - .output( - z.object({ - ok: z.boolean(), - action: z - .object({ type: z.literal("navigate"), value: z.string() }) - .or(z.object({ type: z.literal("reload") })) - .optional(), - }), - ) - .mutation(async (_) => { - // const notification = notifications.find((n) => n.uuid === opt.input.uuid); - - // if (notification) { - // let output: - // | { - // type: "navigate"; - // value: string; - // } - // | { - // type: "reload"; - // }; - - // if (opt.input.responseType === "button") { - // output = notification.optionsCallbacks?.onButton(opt.input.value); - // } - - // notifications = notifications.filter((n) => n.uuid !== notification.uuid); - - // if (output !== undefined) { - // return { ok: true, action: output.action }; - // } else { - // return { ok: true }; - // } - // } - - return { ok: false }; - }), - }, - }, - theme: { - get: procedure.output(z.any().or(z.literal(false))).query(async (opt) => { - const db = opt.ctx.instance.sys.database.postgres(); - - // biome-ignore lint/suspicious/noExplicitAny: unrequired - const themeValues = (await db`SELECT color_scheme FROM public.users WHERE id = ${opt.ctx.userId}`) as any; - - return themeValues?.[0]?.color_scheme || false; - }), - }, -}); - -export type WorkspacesTRPCRouter = typeof workspacesRouter; +import * as nodeCrypto from "node:crypto"; +import { on } from "node:events"; +import { initTRPC, TRPCError } from "@trpc/server"; +import type { FetchCreateContextFnOptions } from "@trpc/server/adapters/fetch"; +import type { Server } from "bun"; +import * as hiBase32 from "hi-base32"; +import * as OTPAuth from "otpauth"; +import z from "zod"; +import type { Instance } from "../index.ts"; +import { AuthorizedDeviceType } from "./authorization.ts"; +import { WorkspacesFeatureFlags } from "./configuration.ts"; +import { type WorkspacesNotification, WorkspacesNotificationEventEmitterEvent } from "./notifications.ts"; +import type { WorkspacesUser } from "./users.ts"; + +export const createTRPCContext = (instance: Instance) => (opt: FetchCreateContextFnOptions, server: Server) => { + return { + rawRequest: { + req: opt.req, + resHeaders: opt.resHeaders, + server: server, + }, + instance: instance, + }; +}; + +export const t = initTRPC.context>().create({ + sse: { + ping: { + // Enable periodic ping messages to keep connection alive + enabled: true, + // Send ping message every 2s + intervalMs: 4000, + }, + client: { + reconnectAfterInactivityMs: 5000, + }, + }, +}); + +export const publicProcedure = t.procedure.use(async (opt) => { + return opt.next({ + ctx: { + userId: "THIS CAN ONLY BE ACCESSED FROM A NON-PUBLIC PROCEDURE", + }, + }); +}); +export const procedure = t.procedure.use(async (opt) => { + // console.log(opt.ctx.req.headers); + + /* + if (!ctx.user?.isAdmin) { + throw new TRPCError({ code: 'UNAUTHORIZED' }); + } + */ + + const cookieString = opt.ctx.rawRequest.req.headers?.get("cookie"); + + if (cookieString === null) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "missing auth cookie", + }); + } + + const parsedCookie = Bun.Cookie.parse(cookieString); + + const userId = await opt.ctx.instance.sys.authorization.verifySession(decodeURIComponent(parsedCookie.value)); + + if (userId === undefined) { + throw new TRPCError({ code: "UNAUTHORIZED", message: "invalid session" }); + } + + return opt.next({ + ctx: { + userId: userId, + user: (): Promise => + // @ts-ignore + opt.ctx.instance.sys.users.getUserById(userId), + }, + }); +}); +export const adminProcedure = procedure.use(async (opt) => { + const user = await opt.ctx.instance.sys.users.getUserById(opt.ctx.userId); + + if (!user) { + throw new TRPCError({ code: "UNAUTHORIZED", message: "invalid session" }); + } + + if (!(await user.isAdministrator())) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "user lacks administrator permissions", + }); + } + + return opt.next(); +}); + +const temporaryTwoFactorSecrets: Map = new Map(); +const emailSignupVerificationCodes: Map = new Map(); +const notifications: WorkspacesNotification[] = []; + +export const workspacesRouter = t.router({ + authorization: { + signupRequirements: publicProcedure + .output( + z.object({ + email: z.boolean(), + twoFactorAuthentication: z.boolean(), + passwordMinimumLength: z.number().optional(), + passwordContains: z + .object({ + minimumUppercase: z.number().optional(), + minimumLowercase: z.number().optional(), + minimumNumbers: z.number().optional(), + minimumSymbols: z.number().optional(), + }) + .optional(), + }), + ) + .query(async (opt) => { + return opt.ctx.instance.sys.configuration.signupRequirements; + }), + checkEmailAddressOwnership: publicProcedure + .input(z.object({ emailAddress: z.string() })) + .output(z.boolean().or(z.string())) + .mutation(async (opt) => { + if (emailSignupVerificationCodes.has(opt.input.emailAddress)) { + return "An email has already been sent, please wait 5 minutes before sending another."; + } + + let emailCode = ""; + const CODE_LENGTH = 8; + const CODE_VALID_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + for (let i = CODE_LENGTH; i > 0; --i) emailCode += CODE_VALID_CHARS[Math.floor(Math.random() * CODE_VALID_CHARS.length)]; + + emailSignupVerificationCodes.set(opt.input.emailAddress, emailCode); + // TODO: send an email... + opt.ctx.instance.log.system.info(`Email code for email '${opt.input.emailAddress}' is '${emailCode}'`); + + return true; + }), + validateEmailCode: publicProcedure.input(z.object({ emailAddress: z.string(), emailCode: z.string() })).query(async (opt) => { + if (emailSignupVerificationCodes.get(opt.input.emailAddress) === opt.input.emailCode) { + return true; + } + + return false; + }), + isUsernameValid: publicProcedure.input(z.string()).query(async (opt) => { + if ((await opt.ctx.instance.sys.users.getUserByUsername(opt.input)) === undefined) return true; + + return false; + }), + canSignup: publicProcedure.query(async (opt) => { + if (opt.ctx.instance.sys.configuration.hasFeature(WorkspacesFeatureFlags.AllowUserSignups)) return true; + + return false; + }), + signup: publicProcedure + .input( + z.union([ + z.object({ + username: z.string(), + password: z.string(), + emailAddress: z.string(), + emailCode: z.string(), + displayName: z.string(), + gender: z.string(), + bio: z.string(), + }), + z.object({ + username: z.string(), + password: z.string(), + displayName: z.string(), + gender: z.string(), + bio: z.string(), + }), + ]), + ) + .output( + z.union([ + z.object({ type: z.literal("error"), message: z.string() }), + z.object({ + type: z.literal("success"), + sessionToken: z.string(), + notice: z.boolean().optional(), + }), + ]), + ) + .mutation(async (opt) => { + if (!opt.ctx.instance.sys.configuration.hasFeature(WorkspacesFeatureFlags.AllowUserSignups)) + return { + type: "error", + message: "This instance has disabled user signups", + }; + + const username = opt.input.username.toLowerCase(); + + if (opt.ctx.instance.sys.configuration.signupRequirements.email) { + if (!("emailAddress" in opt.input)) { + return { + type: "error", + message: "This instance requires an email address for signups!", + }; + } + + if (opt.input.emailCode !== emailSignupVerificationCodes.get(opt.input.emailAddress)) + return { + type: "error", + message: "The email code did not match!", + }; + } + + const uid = await opt.ctx.instance.sys.users.createUser(username, opt.input.password); + + if (uid === undefined) + return { + type: "error", + message: "Failed to create the user", + }; + + const user = await opt.ctx.instance.sys.users.getUserById(uid); + + if (user === undefined) + return { + type: "error", + message: "Failed to fetch the user", + }; + + const splitDisplayName = opt.input.displayName.split(" "); + await user.setFullName(splitDisplayName[0], splitDisplayName.slice(1).join(" ")); + + if ("emailAddress" in opt.input) { + await user.setEmail(opt.input.emailAddress); + } + + await user.setBio(opt.input.bio); + + if (opt.input.gender === "male" || opt.input.gender === "female" || opt.input.gender === "other") await user.setGender(opt.input.gender); + + // TODO: get default quota size from the instance config + await user.setQuota(20); + + const session = await opt.ctx.instance.sys.authorization.createPasswordSession( + user.userId, + opt.input.password, + AuthorizedDeviceType.UnknownBrowser, + undefined, + opt.ctx.rawRequest.req.headers.get("X-Real-IP")?.split(":")?.[0] || "missing-caddy-ip", + ); + + if (session === undefined) { + return { + type: "error", + message: "Failed to create a session?", + }; + } + + opt.ctx.rawRequest.resHeaders.set( + "set-cookie", + Bun.Cookie.from("Authorization", session, { + secure: false, + expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 14).toUTCString(), + }).serialize(), + ); + + return { + type: "success", + sessionToken: session, + }; + }), + confirmTwoFactor: procedure.input(z.object({ twoFactorCode: z.string() })).mutation(async (opt) => { + const user = await opt.ctx.user(); + const secretString = temporaryTwoFactorSecrets.get(user.userId); + + if (secretString === undefined) { + opt.ctx.instance.log.system.warning( + `(${user.userId})${await user.getUsername()} Tried to confirm a two factor code, but they lacked a temporary secret?`, + ); + + return false; + } + + const totp = new OTPAuth.TOTP({ + issuer: opt.ctx.instance.sys.configuration.proxyUrl[0], + label: `${opt.ctx.instance.sys.configuration.displayName} (Workspace)`, + algorithm: "SHA1", + digits: 6, + secret: secretString, + }); + + if (totp.validate({ token: opt.input.twoFactorCode }) !== null) { + temporaryTwoFactorSecrets.delete(user.userId); + await opt.ctx.instance.sys.authorization.setTwoFactorAuthenticationSecret(user.userId, secretString); + opt.ctx.instance.log.system.success(`(${user.userId})${await user.getUsername()} Setup two-factor authentication on their account!`); + + return true; + } + + return false; + }), + enableTwoFactor: procedure + .output( + z + .object({ + twoFactorSecret: z.string(), + twoFactorSecretURI: z.string(), + }) + .optional(), + ) + .mutation(async (opt) => { + const generateSecretString = () => { + const buffer = nodeCrypto.randomBytes(15); + const base32 = hiBase32.encode(buffer).replace(/=/g, "").substring(0, 24); + return base32; + }; + + const user = await opt.ctx.user(); + + if (await opt.ctx.instance.sys.authorization.hasTwoFactorAuthenticationSecret(user.userId)) { + opt.ctx.instance.log.system.warning( + `User (${user.userId})${await user.getUsername()} has attempted to re-setup their two factor from the signup method... this is suspicious...`, + ); + + return undefined; + } + + let secretString = generateSecretString(); + const prevSecretString = temporaryTwoFactorSecrets.get(user.userId); + + if (prevSecretString) { + secretString = prevSecretString; + } + + const totp = new OTPAuth.TOTP({ + issuer: opt.ctx.instance.sys.configuration.proxyUrl[0], + label: `${opt.ctx.instance.sys.configuration.displayName} (Workspace)`, + algorithm: "SHA1", + digits: 6, + secret: secretString, + }); + + temporaryTwoFactorSecrets.set(user.userId, secretString); + + return { + twoFactorSecretURI: totp.toString(), + twoFactorSecret: secretString, + }; + }), + passwordSignin: publicProcedure + .input( + z.object({ + username: z.string(), + password: z.string(), + twoFactorCode: z.string().optional(), + }), + ) + .output( + z.union([ + z.object({ type: z.literal("error"), message: z.string() }), + z.object({ type: z.literal("success"), sessionToken: z.string() }), + z.object({ type: z.literal("twofactor") }), + ]), + ) + .mutation(async (opt) => { + const username = opt.input.username.toLowerCase(); + const user = await opt.ctx.instance.sys.users.getUserByUsername(username); + + if (user === undefined) + return { + type: "error", + message: "Failed to find the user", + }; + + if (await opt.ctx.instance.sys.authorization.hasTwoFactorAuthenticationSecret(user.userId)) { + if (opt.input.twoFactorCode === undefined) + return { + type: "twofactor", + }; + } + + const session = await opt.ctx.instance.sys.authorization.createPasswordSession( + user.userId, + opt.input.password, + AuthorizedDeviceType.UnknownBrowser, + opt.input.twoFactorCode, + opt.ctx.rawRequest.req.headers.get("X-Real-IP")?.split(":")?.[0] || "missing-caddy-ip", + ); + + if (session === undefined) { + return { + type: "error", + message: "Failed to create a session?", + }; + } + + opt.ctx.rawRequest.resHeaders.set( + "set-cookie", + Bun.Cookie.from("Authorization", session, { + secure: false, + expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 14).toUTCString(), + }).serialize(), + ); + + return { + type: "success", + sessionToken: session, + }; + }), + passkeyRequestSignin: publicProcedure + .input( + z.object({ + username: z.string(), + }), + ) + .query(async (opt) => { + const user = await opt.ctx.instance.sys.users.getUserByUsername(opt.input.username.toLowerCase()); + + if (user === undefined) { + return undefined; + } + + return opt.ctx.instance.sys.authorization.requestPasskeySession(user.userId); + }), + passkeyCompleteSignin: publicProcedure + .input( + z.object({ + username: z.string(), + passkeyResponse: z.any(), + }), + ) + .mutation(async (opt) => { + const user = await opt.ctx.instance.sys.users.getUserByUsername(opt.input.username.toLowerCase()); + + if (user === undefined) { + throw new TRPCError({ + code: "NOT_FOUND", + message: "Failed to find the user", + }); + } + + const session = await opt.ctx.instance.sys.authorization.createPasskeySession( + user.userId, + AuthorizedDeviceType.UnknownBrowser, + opt.input.passkeyResponse, + opt.ctx.rawRequest.req.headers.get("X-Real-IP")?.split(":")?.[0] || "missing-caddy-ip", + ); + + if (session === undefined) { + return { + type: "error", + message: "Failed to create a session?", + }; + } + + opt.ctx.rawRequest.resHeaders.set( + "set-cookie", + Bun.Cookie.from("Authorization", session, { + secure: false, + expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 14).toUTCString(), + }).serialize(), + ); + + return { + type: "success", + sessionToken: session, + }; + }), + isAuthenticated: publicProcedure.output(z.object({ authenticated: z.boolean() })).query(async (opt) => { + const cookieString = opt.ctx.rawRequest.req.headers?.get("cookie"); + + if (cookieString === null) { + return { + authenticated: false, + }; + } + + const parsedCookie = Bun.Cookie.parse(cookieString); + + const userId = await opt.ctx.instance.sys.authorization.verifySession(decodeURIComponent(parsedCookie.value)); + + if (userId === undefined) { + return { + authenticated: false, + }; + } + + return { + authenticated: true, + }; + }), + logout: procedure.output(z.object({ success: z.literal(true) })).mutation(async (opt) => { + const cookieString = opt.ctx.rawRequest.req.headers?.get("cookie"); + + if (cookieString === null) { + return { + success: true, + }; + } + + const parsedCookie = Bun.Cookie.parse(cookieString); + + await opt.ctx.instance.sys.authorization.endSessionByToken(decodeURIComponent(parsedCookie.value)); + + return { + success: true, + }; + }), + }, + termsOfUse: publicProcedure.query(async (opt) => { + const date = new Date(opt.ctx.instance.sys.configuration.termsOfUse.lastUpdated); + + const localeDateString: string = date.toLocaleDateString("en-GB", { + day: "numeric", + month: "long", + year: "numeric", + }); + + const getOrdinalSuffix = (day: number): string => { + if (day > 3 && day < 21) return "th"; + switch (day % 10) { + case 1: + return "st"; + case 2: + return "nd"; + case 3: + return "rd"; + default: + return "th"; + } + }; + + const day: number = date.getDate(); + const formattedDate: string = `${day}${getOrdinalSuffix(day)} ${localeDateString.split(" ")[1]}, ${localeDateString.split(" ")[2]}`; + + return `Terms of Use: ${opt.ctx.instance.sys.configuration.displayName} +Effective Date: ${formattedDate} + +${opt.ctx.instance.sys.configuration.termsOfUse.message}`; + }), + app: { + navigation: { + user: { + name: procedure + .output( + z.object({ + username: z.string(), + forename: z.string(), + surname: z.string(), + }), + ) + .query(async (opt) => { + const db = opt.ctx.instance.sys.database.postgres(); + + const user = (await db`SELECT username, forename, surname FROM users WHERE id = ${opt.ctx.userId};`)?.[0]; + + if (!user) { + throw new TRPCError({ + code: "NOT_FOUND", + cause: { message: "User does not exist" }, + }); + } + + return { + username: user.username || "@", + forename: user.forename || "Unknown", + surname: user.surname || "", + }; + }), + }, + getApplications: procedure + .output( + z.array( + z.object({ + location: z.object({ + type: z.union([z.literal("local"), z.literal("remote")]), + value: z.string(), + }), + icon: z.object({ + type: z.union([z.literal("icon"), z.literal("image")]), + value: z.string(), + }), + label: z.string(), + id: z.string(), + }), + ), + ) + .query(async (opt) => { + const applications = opt.ctx.instance.sys.applications.getEnabledApplications(); + + return applications.map((app) => { + let icon = { + type: "icon" as "icon" | "image", + value: "indeterminate_question_box", + }; + + if (app.manifest?.icon) { + if (app.manifest.icon.type === "image") { + icon = { + type: "image", + value: `${opt.ctx.instance.sys.configuration.proxyUrl}/api/application/${app.manifest.id}/icon/`, + }; + } else { + icon = { + type: "icon", + value: `${opt.ctx.instance.sys.configuration.proxyUrl}/api/application/${app.manifest.id}/icon/`, + }; + } + } + + return { + icon: icon, + label: app.manifest?.displayName || "Unknown", + location: { + type: "local", + value: `/app/${app.manifest?.id}` || "/404", + }, + id: app.manifest?.id || "unknown", + }; + }); + }), + getQuickShortcuts: procedure.query(async (opt) => { + const a = opt.ctx.instance.sys.settings.applicationSettings["core"].find((s) => s.id === "quick_shortcuts"); + + if (!a) throw "The core:quick_shortcuts setting is somehow missing???"; + + const quickShortcuts = (await a.onValueChange(opt.ctx.userId)) as string[]; + + const applications = opt.ctx.instance.sys.applications.getEnabledApplications(); + + return quickShortcuts + .map((shortcut) => { + const app = applications.find((a) => a.manifest?.id === shortcut); + + if (!app) return undefined; + + let icon = { + type: "icon" as "icon" | "image", + // TODO: replace this with an image link! + value: "indeterminate_question_box", + }; + + if (app.manifest?.icon) { + if (app.manifest.icon.type === "image") { + icon = { + type: "image", + value: `${opt.ctx.instance.sys.configuration.proxyUrl}/api/application/${app.manifest.id}/icon/`, + }; + } else { + icon = { + type: "icon", + value: `${opt.ctx.instance.sys.configuration.proxyUrl}/api/application/${app.manifest.id}/icon/`, + }; + } + } + + return { + icon: icon, + label: app.manifest?.displayName || "Unknown", + location: { + type: "local", + value: `/app/${app.manifest?.id}` || "/404", + }, + id: app.manifest?.id || "unknown", + }; + }) + .filter((qs) => qs !== undefined); + }), + }, + notifications: { + listener: procedure + // @ts-ignore + .subscription(async function* (opt) { + for await (const [data] of on(opt.ctx.instance.sys.notifications.eventEmitter, WorkspacesNotificationEventEmitterEvent.SendNotification, { + signal: opt.signal, + })) { + const notification = data as WorkspacesNotification; + if (notification.recipient === opt.ctx.userId) { + notifications.push(notification); + + yield notification; + } + } + }), + respond: procedure + .input( + z.object({ + uuid: z.string(), + responseType: z.literal("button"), + value: z.string(), + }), + ) + .output( + z.object({ + ok: z.boolean(), + action: z + .object({ type: z.literal("navigate"), value: z.string() }) + .or(z.object({ type: z.literal("reload") })) + .optional(), + }), + ) + .mutation(async (_) => { + // const notification = notifications.find((n) => n.uuid === opt.input.uuid); + + // if (notification) { + // let output: + // | { + // type: "navigate"; + // value: string; + // } + // | { + // type: "reload"; + // }; + + // if (opt.input.responseType === "button") { + // output = notification.optionsCallbacks?.onButton(opt.input.value); + // } + + // notifications = notifications.filter((n) => n.uuid !== notification.uuid); + + // if (output !== undefined) { + // return { ok: true, action: output.action }; + // } else { + // return { ok: true }; + // } + // } + + return { ok: false }; + }), + }, + }, + theme: { + get: procedure.output(z.any().or(z.literal(false))).query(async (opt) => { + const db = opt.ctx.instance.sys.database.postgres(); + + // biome-ignore lint/suspicious/noExplicitAny: unrequired + const themeValues = (await db`SELECT color_scheme FROM public.users WHERE id = ${opt.ctx.userId}`) as any; + + return themeValues?.[0]?.color_scheme || false; + }), + }, +}); + +export type WorkspacesTRPCRouter = typeof workspacesRouter; diff --git a/instance/src/systems/users.ts b/instance/src/systems/users.ts index ab7c447..a187a63 100644 --- a/instance/src/systems/users.ts +++ b/instance/src/systems/users.ts @@ -1,627 +1,627 @@ -import { promises as fs, existsSync as fsExistsSync } from "node:fs"; -import path from "node:path"; -import sharp from "sharp"; -import type { Instance } from "../index.ts"; -import System from "../system.ts"; - -export interface IUserDatabaseUser { - id: number; - username: string; - forename: string; - surname: string; -} - -// WARNING!: do not call new WorkspacesUser() it is only to be created by the UsersSubsystem -export class WorkspacesUser { - userId: number; - private instance: Instance; - - constructor(instance: Instance, userId: number) { - this.instance = instance; - this.userId = userId; - } - - getPath(): string { - return path.join(this.instance.sys.filesystem.FS_ROOT, `users/${this.userId}`); - } - - /** - Sets the user's username to username - @return `false` - failed to change the username - @return `true` - successfully changed the username - */ - async setUsername(username: string): Promise { - const db = this.instance.sys.database.postgres(); - - try { - if ((await db`SELECT username FROM public.users WHERE username = ${username}`).count !== 0) return false; - - await db`UPDATE public.users SET username = ${username} WHERE id = ${this.userId}`; - return true; - } catch (_) { - this.instance.sys.users.log.error(`Failed to set username for ${this.userId}`); - return false; - } - } - - /** - Get the user's username - @return `string` - the users username - @return `undefined` - could not get the user's username - */ - async getUsername(): Promise { - const db = this.instance.sys.database.postgres(); - - return (await db`SELECT username FROM public.users WHERE id = ${this.userId}`)?.[0]?.username || undefined; - } - - /** - Sets the user's forename to forename - @return `false` - failed to change the forename - @return `true` - successfully changed the forename - */ - async setForename(forename: string): Promise { - const db = this.instance.sys.database.postgres(); - - try { - await db`UPDATE public.users SET forename = ${forename} WHERE id = ${this.userId}`; - - return true; - } catch (_) { - this.instance.sys.users.log.error(`Failed to set forename for ${this.userId}`); - return false; - } - } - - /** - Get the user's forename - @return `string` - the users forename - @return `undefined` - could not get the user's forename - */ - async getForename(): Promise { - const db = this.instance.sys.database.postgres(); - - return (await db`SELECT forename FROM public.users WHERE id = ${this.userId}`)?.[0]?.forename || undefined; - } - - /** - Sets the user's surname to surname - @return `false` - failed to change the surname - @return `true` - successfully changed the surname - */ - async setSurname(surname: string): Promise { - const db = this.instance.sys.database.postgres(); - - try { - this.instance.log.system.info(`Set Surname to '${surname}' for ${this.userId}`); - - await db`UPDATE public.users SET surname = ${surname} WHERE id = ${this.userId}`; - - return true; - } catch (_) { - this.instance.sys.users.log.error(`Failed to set surname for ${this.userId}`); - return false; - } - } - - /** - Get the user's surname - @return `string` - the users surname - @return `undefined` - could not get the user's surname - */ - async getSurname(): Promise { - const db = this.instance.sys.database.postgres(); - - return (await db`SELECT surname FROM public.users WHERE id = ${this.userId}`)?.[0]?.surname || undefined; - } - - /** - Sets the user's forename and surname to the provided forename and surname - @return `false` - failed to change the surname - @return `true` - successfully changed the surname - */ - async setFullName(forename: string, surname: string): Promise { - const forenameRes = await this.setForename(forename); - const surnameRes = await this.setSurname(surname); - - return forenameRes && surnameRes; - } - - /** - Gets the user's forename and surname - */ - async getFullName(): Promise<{ forename?: string; surname?: string }> { - const forenameRes = await this.getForename(); - const surnameRes = await this.getSurname(); - - return { forename: forenameRes, surname: surnameRes }; - } - - /** - Sets the user's quota to the provided quota in bits - @returns `false` - failed to set the quota - @returns `true` - successfully set the quota - */ - async setQuota(quota: number): Promise { - const db = this.instance.sys.database.postgres(); - - try { - await db`UPDATE public.users SET storage_quota = ${quota} WHERE id = ${this.userId}`; - return true; - } catch (_) { - this.instance.sys.users.log.error(`Failed to set storage quota for ${this.userId}`); - return false; - } - } - - /** - Get the user's quota in bits - @returns `number` - the users quota - @returns `undefined` - could not get the user's quota - */ - async getQuota(): Promise { - const db = this.instance.sys.database.postgres(); - - return (await db`SELECT storage_quota FROM public.users WHERE id = ${this.userId}`)?.[0]?.storage_quota || undefined; - } - - /** - Sets the user's bio to bio - @returns `false` - failed to change the bio - @returns `true` - successfully changed the bio - */ - async setBio(bio: string): Promise { - const db = this.instance.sys.database.postgres(); - - try { - await db`UPDATE public.users SET bio = ${bio} WHERE id = ${this.userId}`; - return true; - } catch (_) { - this.instance.sys.users.log.error(`Failed to set bio for ${this.userId}`); - return false; - } - } - - /** - Get the user's bio - @returns `string` - the users bio - @returns `undefined` - could not get the user's bio - */ - async getBio(): Promise { - const db = this.instance.sys.database.postgres(); - - return (await db`SELECT bio FROM public.users WHERE id = ${this.userId}`)?.[0]?.bio || undefined; - } - - /** - Sets the user's email to email - @returns `false` - failed to change the email - @returns `true` - successfully changed the email - */ - async setEmail(email: string): Promise { - const db = this.instance.sys.database.postgres(); - try { - await db`UPDATE public.users SET email = ${email} WHERE id = ${this.userId}`; - return true; - } catch (_) { - this.instance.sys.users.log.error(`Failed to set email for ${this.userId}`); - return false; - } - } - - /** - Get the user's email - @returns `string` - the users email - @returns `undefined` - could not get the user's email - */ - async getEmail(): Promise { - const db = this.instance.sys.database.postgres(); - - return (await db`SELECT email FROM public.users WHERE id = ${this.userId}`)?.[0]?.email || undefined; - } - - /** - Sets the user's gender to gender - @returns `false` - failed to change the gender - @returns `true` - successfully changed the gender - */ - async setGender(gender: "female" | "male" | "other"): Promise { - const db = this.instance.sys.database.postgres(); - - try { - await db`UPDATE public.users SET gender = ${gender} WHERE id = ${this.userId}`; - return true; - } catch (_) { - this.instance.sys.users.log.error(`Failed to set gender for ${this.userId}`); - return false; - } - } - - /** - Get the user's gender - @returns `"female" | "male" | "other"` - the users gender - @returns `undefined` - could not get the user's gender - */ - async getGender(): Promise { - const db = this.instance.sys.database.postgres(); - - return (await db`SELECT gender FROM public.users WHERE id = ${this.userId}`)?.[0]?.gender || undefined; - } - - /** - Join a specified group for the user. - @returns `true` - if successfully joined the group - @returns `false` - if already a member or an error occurred. - */ - async joinGroup(groupId: string): Promise { - const db = this.instance.sys.database.postgres(); - - try { - const existingGroups = await this.getGroups(); - - if (existingGroups.includes(groupId)) { - return false; - } - - await db` - UPDATE public.users - SET groups = array_append(groups, ${groupId}) - WHERE id = ${this.userId} - `; - - return true; - } catch (error) { - console.error("Error joining group:", error); - return false; - } - } - - /** - Leave a specified group for the user. - @returns `true` - if successfully left the group - @returns `false` - if not a member or an error occurred. - */ - async leaveGroup(groupId: string): Promise { - const db = this.instance.sys.database.postgres(); - - try { - const existingGroups = await this.getGroups(); - - if (!existingGroups.includes(groupId)) { - return false; - } - - await db` - UPDATE public.users - SET groups = array_remove(groups, ${groupId}) - WHERE id = ${this.userId} - `; - - return true; - } catch (error) { - console.error("Error leaving group:", error); - return false; - } - } - - /** - Returns an array of groups the user belongs to. - @returns `string[]` - An array of group IDs the user is a member of, or an empty array if none. - */ - async getGroups(): Promise { - const db = this.instance.sys.database.postgres(); - - return (await db`SELECT groups FROM public.users WHERE id = ${this.userId}`)?.[0].groups || []; - } - - /** - Get if the user is an administrator - @returns `boolean` - if the user an administrator - */ - async isAdministrator(): Promise { - const db = this.instance.sys.database.postgres(); - - return (await db`SELECT is_administrator FROM public.users WHERE id = ${this.userId}`)?.[0]?.is_administrator || false; - } - - /** - Sets if user is an administrator - @returns `false` - failed to change the administrator status - @returns `true` - successfully changed the administrator status - */ - async setIsAdministrator(administrator: boolean): Promise { - const db = this.instance.sys.database.postgres(); - - try { - await db`UPDATE public.users SET is_administrator = ${administrator} WHERE id = ${this.userId}`; - return true; - } catch (_) { - this.instance.sys.users.log.error(`Failed to set is_administrator for ${this.userId}`); - return false; - } - } - - /** - sets the user's original quality avatar to avatarFile - @returns `true` - copied the avatarFile successfully - @returns `false` - failed to copy the avatarFile - */ - async setAvatar(avatarFile: string): Promise { - try { - await fs.cp(avatarFile, path.join(this.getPath(), "assets/avatar/avatar.webp")); - return true; - } catch (_) { - this.instance.sys.users.log.error(`Failed to set avatar for ${this.userId} to ${avatarFile}`); - return false; - } - } - - /** - generates the required avatar sizes from the user's avatarFile, if override is not set to true, only missing avatar sizes will be generated - @returns `true` - generated required avatar files successfully - @returns `false` - failed to generate all required avatar files - */ - async generateAvatars(override?: boolean): Promise { - const AVATAR_SIZES: { width: number; height: number; name: string }[] = [ - { width: 16, height: 16, name: "xs" }, - { width: 32, height: 32, name: "s" }, - { width: 64, height: 64, name: "m" }, - { width: 128, height: 128, name: "l" }, - { width: 256, height: 256, name: "xl" }, - { width: 512, height: 512, name: "2xl" }, - ]; - - try { - for (const size of AVATAR_SIZES) { - if (override || !fsExistsSync(path.join(this.getPath(), `assets/avatar/${size.name}.webp`))) { - this.instance.sys.users.log.info(`Generating avatar for user '${this.userId}' @ ${size.name}`); - await sharp(path.join(this.getPath(), "assets/avatar/avatar.webp")) - .resize(size.width, size.height) - .toFile(path.join(this.getPath(), `assets/avatar/${size.name}.webp`)); - this.instance.sys.users.log.success(`Generated avatar for user '${this.userId}' @ ${size.name}`); - } - } - } catch (_) { - this.instance.sys.users.log.error("Failed to generate avatar sizes"); - } - - return true; - } - - /** - Check that all required directories and assets are valid for this user. - If they are missing or invalid, directories will be created and assets will be generated / copied - @returns `true` - if successful - */ - async verify(): Promise { - const username = await this.getUsername(); - const USER_DIRECTORIES = [ - "/", - "/fs", - "/fs/Desktop", - "/fs/Downloads", - "/fs/Documents", - "/fs/Photos", - "/fs/Music", - "/fs/Videos", - "/assets", - "/assets/avatar", - "/assets/wallpapers", - "/assets/wallpapers/resized", - "/mounts", - "/recycle_bin", - "/system", - "/system/logs", - "/system/temp", - ]; - - for (const dir of USER_DIRECTORIES) { - await this.instance.sys.filesystem.createDirectoryIfNotExists(path.join(this.instance.sys.filesystem.FS_ROOT, `users/${this.userId}`, dir)); - } - - if (!fsExistsSync(path.join(this.getPath(), "assets/avatar/avatar.webp"))) { - await this.setAvatar(path.join(this.instance.sys.filesystem.SRC_ROOT, "assets/placeholder/avatar.png")); - } - - await this.generateAvatars(); - - if (!(await this.instance.sys.authorization.hasPassword(this.userId))) { - this.instance.sys.users.log.warning(`user (${this.userId})${username} has no password set! Without a password, this account cannot be accessed.`); - } - - this.instance.sys.users.log.success(`Verified user (${this.userId})${username}`); - - return true; - } - - /** - Deletes a user from the filesystem and all database entries - */ - async delete() { - await fs.rm(path.join(this.instance.sys.filesystem.FS_ROOT, `users/${this.userId}`), { - recursive: true, - force: true, - }); - - const db = this.instance.sys.database.postgres(); - - await db`DELETE FROM public.users WHERE id = ${this.userId};`; - await db`DELETE FROM public.sessions WHERE user_id = ${this.userId};`; - - return true; - } -} - -export default class UsersSystem extends System { - constructor(instance: Instance) { - super("users", instance); - } - - override async startup(): Promise { - await super.startup(); - - const db = this.instance.sys.database.postgres(); - - /** - init the users database - - id - permanent unique user id number (number) - username - the user's changeable username (string) - forename - the user's chosen forename (string) - surname - the user's chosen surname (string) - gender - the user's chosen gender ("female" | "male" | "other") - bio - the user's chosen bio (string) - storage_quota - the user's storage quota in MB (number) - email - the user's chosen contact email (string) - is_administrator - is the user an administrator (boolean) - is_email_verified - is the user's chosen contact email verified to be theirs (boolean) - socials - the user's chosen social media links in the format '[name]:-:[url]' as such, the string ':-:' must not be in either [name] or [url] (string[]) - hashed_password - the user's password after it has been hashed by bun (string) - two_factor_secret - the user's secret string used to verify 2fa opt codes (string) - settings - a settings object - groups - a list of the group ids which this user is a member of - color_scheme - the user's color scheme - */ - await db`CREATE TABLE IF NOT EXISTS users ( - id SERIAL PRIMARY KEY, - username TEXT, - forename TEXT, - surname TEXT DEFAULT '', - gender TEXT DEFAULT 'other', - bio TEXT, - storage_quota BIGINT DEFAULT 8589934592, - email TEXT, - is_administrator BOOL DEFAULT FALSE, - is_email_verified BOOL DEFAULT FALSE, - socials TEXT[] DEFAULT '{}', - hashed_password TEXT, - two_factor_secret TEXT, - settings JSONB DEFAULT '{}'::JSONB, - groups TEXT[], - color_scheme JSONB - )`; - - if (!(await this.getAllUsers()).find((u) => u.isAdministrator())) { - this.log.warning("No administrator account exists, creating default administrator account with username 'admin' and password 'password'"); - - const administratorUserId = await this.createUser("admin"); - - // if the account is newly-created - if (administratorUserId !== undefined) { - const adminUser = await this.getUserById(administratorUserId); - - if (!adminUser) { - this.log.error("Admin user didn't exist and couldn't be created!"); - } else { - // Name: Admin Istrator - await adminUser.setFullName("Admin", "Istrator"); - await adminUser.setIsAdministrator(true); - - const defaultPassword = "password"; - - await this.instance.sys.authorization.setPassword(adminUser.userId, defaultPassword); - this.log.info(`The default admin user has a password of '${defaultPassword}'`); - } - } - } - - const users = await this.getAllUsers(); - - for (const user of users) { - await user.verify(); - } - - return true; - } - - /** - Create a new Workspaces User - @returns number - the userId of the created user - @returns undefined - the user already exists - */ - async createUser(username: string, password?: string): Promise { - const db = this.instance.sys.database.postgres(); - - if ((await db`SELECT username FROM public.users WHERE username = ${username}`).count !== 0) { - this.log.warning(`Failed to create user ${username} as they already exist`); - return undefined; - } - - const user = { - username, - forename: "John", - surname: "Doe", - }; - - const id = (await db`INSERT INTO public.users ${db(user)} RETURNING id`)?.[0]?.id; - - const ubi = await this.getUserById(id); - - if (!ubi) { - this.log.error("Failed during the user creation process."); - return undefined; - } - - if (password) await this.instance.sys.authorization.setPassword(id, password); - - await ubi.setAvatar(path.join(this.instance.sys.filesystem.SRC_ROOT, "assets/placeholder/avatar.png")); - - await ubi.verify(); - - return id; - } - - /** - Does a user with the userId exist - @returns true - they exist - @returns false - they do not exist - */ - async doesUserExist(userId: number): Promise { - const db = this.instance.sys.database.postgres(); - - return (await db`SELECT username FROM public.users WHERE id = ${userId}`).count === 1; - } - - /** - Gets an array of all users registered on this instance - @returns `WorkspacesUser[]` - an array of all users - */ - async getAllUsers(): Promise { - const db = this.instance.sys.database.postgres(); - - try { - // @ts-ignore this is valid - return (await db`SELECT id FROM public.users`).map((u: { id: number }) => new WorkspacesUser(this.instance, u.id)); - } catch (err) { - this.log.error("Failed to getAllUsers()", err); - - return []; - } - } - - /** - Gets a user by their userId - @returns `WorkspacesUser` - the user - @returns `undefined` - no such user exists - */ - async getUserById(userId: number): Promise { - if ((await this.doesUserExist(userId)) === undefined) return undefined; - - return new WorkspacesUser(this.instance, userId); - } - - /** - Gets a user by their username - @returns `WorkspacesUser` - the user - @returns `undefined` - no such user exists - */ - async getUserByUsername(username: string): Promise { - const db = this.instance.sys.database.postgres(); - - const userId = (await db`SELECT id FROM public.users WHERE username = ${username}`)?.[0]?.id; - - if (!(await this.doesUserExist(userId))) return undefined; - - return new WorkspacesUser(this.instance, userId); - } -} +import { promises as fs, existsSync as fsExistsSync } from "node:fs"; +import path from "node:path"; +import sharp from "sharp"; +import type { Instance } from "../index.ts"; +import System from "../system.ts"; + +export interface IUserDatabaseUser { + id: number; + username: string; + forename: string; + surname: string; +} + +// WARNING!: do not call new WorkspacesUser() it is only to be created by the UsersSubsystem +export class WorkspacesUser { + userId: number; + private instance: Instance; + + constructor(instance: Instance, userId: number) { + this.instance = instance; + this.userId = userId; + } + + getPath(): string { + return path.join(this.instance.sys.filesystem.FS_ROOT, `users/${this.userId}`); + } + + /** + Sets the user's username to username + @return `false` - failed to change the username + @return `true` - successfully changed the username + */ + async setUsername(username: string): Promise { + const db = this.instance.sys.database.postgres(); + + try { + if ((await db`SELECT username FROM public.users WHERE username = ${username}`).count !== 0) return false; + + await db`UPDATE public.users SET username = ${username} WHERE id = ${this.userId}`; + return true; + } catch (_) { + this.instance.sys.users.log.error(`Failed to set username for ${this.userId}`); + return false; + } + } + + /** + Get the user's username + @return `string` - the users username + @return `undefined` - could not get the user's username + */ + async getUsername(): Promise { + const db = this.instance.sys.database.postgres(); + + return (await db`SELECT username FROM public.users WHERE id = ${this.userId}`)?.[0]?.username || undefined; + } + + /** + Sets the user's forename to forename + @return `false` - failed to change the forename + @return `true` - successfully changed the forename + */ + async setForename(forename: string): Promise { + const db = this.instance.sys.database.postgres(); + + try { + await db`UPDATE public.users SET forename = ${forename} WHERE id = ${this.userId}`; + + return true; + } catch (_) { + this.instance.sys.users.log.error(`Failed to set forename for ${this.userId}`); + return false; + } + } + + /** + Get the user's forename + @return `string` - the users forename + @return `undefined` - could not get the user's forename + */ + async getForename(): Promise { + const db = this.instance.sys.database.postgres(); + + return (await db`SELECT forename FROM public.users WHERE id = ${this.userId}`)?.[0]?.forename || undefined; + } + + /** + Sets the user's surname to surname + @return `false` - failed to change the surname + @return `true` - successfully changed the surname + */ + async setSurname(surname: string): Promise { + const db = this.instance.sys.database.postgres(); + + try { + this.instance.log.system.info(`Set Surname to '${surname}' for ${this.userId}`); + + await db`UPDATE public.users SET surname = ${surname} WHERE id = ${this.userId}`; + + return true; + } catch (_) { + this.instance.sys.users.log.error(`Failed to set surname for ${this.userId}`); + return false; + } + } + + /** + Get the user's surname + @return `string` - the users surname + @return `undefined` - could not get the user's surname + */ + async getSurname(): Promise { + const db = this.instance.sys.database.postgres(); + + return (await db`SELECT surname FROM public.users WHERE id = ${this.userId}`)?.[0]?.surname || undefined; + } + + /** + Sets the user's forename and surname to the provided forename and surname + @return `false` - failed to change the surname + @return `true` - successfully changed the surname + */ + async setFullName(forename: string, surname: string): Promise { + const forenameRes = await this.setForename(forename); + const surnameRes = await this.setSurname(surname); + + return forenameRes && surnameRes; + } + + /** + Gets the user's forename and surname + */ + async getFullName(): Promise<{ forename?: string; surname?: string }> { + const forenameRes = await this.getForename(); + const surnameRes = await this.getSurname(); + + return { forename: forenameRes, surname: surnameRes }; + } + + /** + Sets the user's quota to the provided quota in bits + @returns `false` - failed to set the quota + @returns `true` - successfully set the quota + */ + async setQuota(quota: number): Promise { + const db = this.instance.sys.database.postgres(); + + try { + await db`UPDATE public.users SET storage_quota = ${quota} WHERE id = ${this.userId}`; + return true; + } catch (_) { + this.instance.sys.users.log.error(`Failed to set storage quota for ${this.userId}`); + return false; + } + } + + /** + Get the user's quota in bits + @returns `number` - the users quota + @returns `undefined` - could not get the user's quota + */ + async getQuota(): Promise { + const db = this.instance.sys.database.postgres(); + + return (await db`SELECT storage_quota FROM public.users WHERE id = ${this.userId}`)?.[0]?.storage_quota || undefined; + } + + /** + Sets the user's bio to bio + @returns `false` - failed to change the bio + @returns `true` - successfully changed the bio + */ + async setBio(bio: string): Promise { + const db = this.instance.sys.database.postgres(); + + try { + await db`UPDATE public.users SET bio = ${bio} WHERE id = ${this.userId}`; + return true; + } catch (_) { + this.instance.sys.users.log.error(`Failed to set bio for ${this.userId}`); + return false; + } + } + + /** + Get the user's bio + @returns `string` - the users bio + @returns `undefined` - could not get the user's bio + */ + async getBio(): Promise { + const db = this.instance.sys.database.postgres(); + + return (await db`SELECT bio FROM public.users WHERE id = ${this.userId}`)?.[0]?.bio || undefined; + } + + /** + Sets the user's email to email + @returns `false` - failed to change the email + @returns `true` - successfully changed the email + */ + async setEmail(email: string): Promise { + const db = this.instance.sys.database.postgres(); + try { + await db`UPDATE public.users SET email = ${email} WHERE id = ${this.userId}`; + return true; + } catch (_) { + this.instance.sys.users.log.error(`Failed to set email for ${this.userId}`); + return false; + } + } + + /** + Get the user's email + @returns `string` - the users email + @returns `undefined` - could not get the user's email + */ + async getEmail(): Promise { + const db = this.instance.sys.database.postgres(); + + return (await db`SELECT email FROM public.users WHERE id = ${this.userId}`)?.[0]?.email || undefined; + } + + /** + Sets the user's gender to gender + @returns `false` - failed to change the gender + @returns `true` - successfully changed the gender + */ + async setGender(gender: "female" | "male" | "other"): Promise { + const db = this.instance.sys.database.postgres(); + + try { + await db`UPDATE public.users SET gender = ${gender} WHERE id = ${this.userId}`; + return true; + } catch (_) { + this.instance.sys.users.log.error(`Failed to set gender for ${this.userId}`); + return false; + } + } + + /** + Get the user's gender + @returns `"female" | "male" | "other"` - the users gender + @returns `undefined` - could not get the user's gender + */ + async getGender(): Promise { + const db = this.instance.sys.database.postgres(); + + return (await db`SELECT gender FROM public.users WHERE id = ${this.userId}`)?.[0]?.gender || undefined; + } + + /** + Join a specified group for the user. + @returns `true` - if successfully joined the group + @returns `false` - if already a member or an error occurred. + */ + async joinGroup(groupId: string): Promise { + const db = this.instance.sys.database.postgres(); + + try { + const existingGroups = await this.getGroups(); + + if (existingGroups.includes(groupId)) { + return false; + } + + await db` + UPDATE public.users + SET groups = array_append(groups, ${groupId}) + WHERE id = ${this.userId} + `; + + return true; + } catch (error) { + console.error("Error joining group:", error); + return false; + } + } + + /** + Leave a specified group for the user. + @returns `true` - if successfully left the group + @returns `false` - if not a member or an error occurred. + */ + async leaveGroup(groupId: string): Promise { + const db = this.instance.sys.database.postgres(); + + try { + const existingGroups = await this.getGroups(); + + if (!existingGroups.includes(groupId)) { + return false; + } + + await db` + UPDATE public.users + SET groups = array_remove(groups, ${groupId}) + WHERE id = ${this.userId} + `; + + return true; + } catch (error) { + console.error("Error leaving group:", error); + return false; + } + } + + /** + Returns an array of groups the user belongs to. + @returns `string[]` - An array of group IDs the user is a member of, or an empty array if none. + */ + async getGroups(): Promise { + const db = this.instance.sys.database.postgres(); + + return (await db`SELECT groups FROM public.users WHERE id = ${this.userId}`)?.[0].groups || []; + } + + /** + Get if the user is an administrator + @returns `boolean` - if the user an administrator + */ + async isAdministrator(): Promise { + const db = this.instance.sys.database.postgres(); + + return (await db`SELECT is_administrator FROM public.users WHERE id = ${this.userId}`)?.[0]?.is_administrator || false; + } + + /** + Sets if user is an administrator + @returns `false` - failed to change the administrator status + @returns `true` - successfully changed the administrator status + */ + async setIsAdministrator(administrator: boolean): Promise { + const db = this.instance.sys.database.postgres(); + + try { + await db`UPDATE public.users SET is_administrator = ${administrator} WHERE id = ${this.userId}`; + return true; + } catch (_) { + this.instance.sys.users.log.error(`Failed to set is_administrator for ${this.userId}`); + return false; + } + } + + /** + sets the user's original quality avatar to avatarFile + @returns `true` - copied the avatarFile successfully + @returns `false` - failed to copy the avatarFile + */ + async setAvatar(avatarFile: string): Promise { + try { + await fs.cp(avatarFile, path.join(this.getPath(), "assets/avatar/avatar.webp")); + return true; + } catch (_) { + this.instance.sys.users.log.error(`Failed to set avatar for ${this.userId} to ${avatarFile}`); + return false; + } + } + + /** + generates the required avatar sizes from the user's avatarFile, if override is not set to true, only missing avatar sizes will be generated + @returns `true` - generated required avatar files successfully + @returns `false` - failed to generate all required avatar files + */ + async generateAvatars(override?: boolean): Promise { + const AVATAR_SIZES: { width: number; height: number; name: string }[] = [ + { width: 16, height: 16, name: "xs" }, + { width: 32, height: 32, name: "s" }, + { width: 64, height: 64, name: "m" }, + { width: 128, height: 128, name: "l" }, + { width: 256, height: 256, name: "xl" }, + { width: 512, height: 512, name: "2xl" }, + ]; + + try { + for (const size of AVATAR_SIZES) { + if (override || !fsExistsSync(path.join(this.getPath(), `assets/avatar/${size.name}.webp`))) { + this.instance.sys.users.log.info(`Generating avatar for user '${this.userId}' @ ${size.name}`); + await sharp(path.join(this.getPath(), "assets/avatar/avatar.webp")) + .resize(size.width, size.height) + .toFile(path.join(this.getPath(), `assets/avatar/${size.name}.webp`)); + this.instance.sys.users.log.success(`Generated avatar for user '${this.userId}' @ ${size.name}`); + } + } + } catch (_) { + this.instance.sys.users.log.error("Failed to generate avatar sizes"); + } + + return true; + } + + /** + Check that all required directories and assets are valid for this user. + If they are missing or invalid, directories will be created and assets will be generated / copied + @returns `true` - if successful + */ + async verify(): Promise { + const username = await this.getUsername(); + const USER_DIRECTORIES = [ + "/", + "/fs", + "/fs/Desktop", + "/fs/Downloads", + "/fs/Documents", + "/fs/Photos", + "/fs/Music", + "/fs/Videos", + "/assets", + "/assets/avatar", + "/assets/wallpapers", + "/assets/wallpapers/resized", + "/mounts", + "/recycle_bin", + "/system", + "/system/logs", + "/system/temp", + ]; + + for (const dir of USER_DIRECTORIES) { + await this.instance.sys.filesystem.createDirectoryIfNotExists(path.join(this.instance.sys.filesystem.FS_ROOT, `users/${this.userId}`, dir)); + } + + if (!fsExistsSync(path.join(this.getPath(), "assets/avatar/avatar.webp"))) { + await this.setAvatar(path.join(this.instance.sys.filesystem.SRC_ROOT, "assets/placeholder/avatar.png")); + } + + await this.generateAvatars(); + + if (!(await this.instance.sys.authorization.hasPassword(this.userId))) { + this.instance.sys.users.log.warning(`user (${this.userId})${username} has no password set! Without a password, this account cannot be accessed.`); + } + + this.instance.sys.users.log.success(`Verified user (${this.userId})${username}`); + + return true; + } + + /** + Deletes a user from the filesystem and all database entries + */ + async delete() { + await fs.rm(path.join(this.instance.sys.filesystem.FS_ROOT, `users/${this.userId}`), { + recursive: true, + force: true, + }); + + const db = this.instance.sys.database.postgres(); + + await db`DELETE FROM public.users WHERE id = ${this.userId};`; + await db`DELETE FROM public.sessions WHERE user_id = ${this.userId};`; + + return true; + } +} + +export default class UsersSystem extends System { + constructor(instance: Instance) { + super("users", instance); + } + + override async startup(): Promise { + await super.startup(); + + const db = this.instance.sys.database.postgres(); + + /** + init the users database + + id - permanent unique user id number (number) + username - the user's changeable username (string) + forename - the user's chosen forename (string) + surname - the user's chosen surname (string) + gender - the user's chosen gender ("female" | "male" | "other") + bio - the user's chosen bio (string) + storage_quota - the user's storage quota in MB (number) + email - the user's chosen contact email (string) + is_administrator - is the user an administrator (boolean) + is_email_verified - is the user's chosen contact email verified to be theirs (boolean) + socials - the user's chosen social media links in the format '[name]:-:[url]' as such, the string ':-:' must not be in either [name] or [url] (string[]) + hashed_password - the user's password after it has been hashed by bun (string) + two_factor_secret - the user's secret string used to verify 2fa opt codes (string) + settings - a settings object + groups - a list of the group ids which this user is a member of + color_scheme - the user's color scheme + */ + await db`CREATE TABLE IF NOT EXISTS users ( + id SERIAL PRIMARY KEY, + username TEXT, + forename TEXT, + surname TEXT DEFAULT '', + gender TEXT DEFAULT 'other', + bio TEXT, + storage_quota BIGINT DEFAULT 8589934592, + email TEXT, + is_administrator BOOL DEFAULT FALSE, + is_email_verified BOOL DEFAULT FALSE, + socials TEXT[] DEFAULT '{}', + hashed_password TEXT, + two_factor_secret TEXT, + settings JSONB DEFAULT '{}'::JSONB, + groups TEXT[], + color_scheme JSONB + )`; + + if (!(await this.getAllUsers()).find((u) => u.isAdministrator())) { + this.log.warning("No administrator account exists, creating default administrator account with username 'admin' and password 'password'"); + + const administratorUserId = await this.createUser("admin"); + + // if the account is newly-created + if (administratorUserId !== undefined) { + const adminUser = await this.getUserById(administratorUserId); + + if (!adminUser) { + this.log.error("Admin user didn't exist and couldn't be created!"); + } else { + // Name: Admin Istrator + await adminUser.setFullName("Admin", "Istrator"); + await adminUser.setIsAdministrator(true); + + const defaultPassword = "password"; + + await this.instance.sys.authorization.setPassword(adminUser.userId, defaultPassword); + this.log.info(`The default admin user has a password of '${defaultPassword}'`); + } + } + } + + const users = await this.getAllUsers(); + + for (const user of users) { + await user.verify(); + } + + return true; + } + + /** + Create a new Workspaces User + @returns number - the userId of the created user + @returns undefined - the user already exists + */ + async createUser(username: string, password?: string): Promise { + const db = this.instance.sys.database.postgres(); + + if ((await db`SELECT username FROM public.users WHERE username = ${username}`).count !== 0) { + this.log.warning(`Failed to create user ${username} as they already exist`); + return undefined; + } + + const user = { + username, + forename: "John", + surname: "Doe", + }; + + const id = (await db`INSERT INTO public.users ${db(user)} RETURNING id`)?.[0]?.id; + + const ubi = await this.getUserById(id); + + if (!ubi) { + this.log.error("Failed during the user creation process."); + return undefined; + } + + if (password) await this.instance.sys.authorization.setPassword(id, password); + + await ubi.setAvatar(path.join(this.instance.sys.filesystem.SRC_ROOT, "assets/placeholder/avatar.png")); + + await ubi.verify(); + + return id; + } + + /** + Does a user with the userId exist + @returns true - they exist + @returns false - they do not exist + */ + async doesUserExist(userId: number): Promise { + const db = this.instance.sys.database.postgres(); + + return (await db`SELECT username FROM public.users WHERE id = ${userId}`).count === 1; + } + + /** + Gets an array of all users registered on this instance + @returns `WorkspacesUser[]` - an array of all users + */ + async getAllUsers(): Promise { + const db = this.instance.sys.database.postgres(); + + try { + // @ts-ignore this is valid + return (await db`SELECT id FROM public.users`).map((u: { id: number }) => new WorkspacesUser(this.instance, u.id)); + } catch (err) { + this.log.error("Failed to getAllUsers()", err); + + return []; + } + } + + /** + Gets a user by their userId + @returns `WorkspacesUser` - the user + @returns `undefined` - no such user exists + */ + async getUserById(userId: number): Promise { + if ((await this.doesUserExist(userId)) === undefined) return undefined; + + return new WorkspacesUser(this.instance, userId); + } + + /** + Gets a user by their username + @returns `WorkspacesUser` - the user + @returns `undefined` - no such user exists + */ + async getUserByUsername(username: string): Promise { + const db = this.instance.sys.database.postgres(); + + const userId = (await db`SELECT id FROM public.users WHERE username = ${username}`)?.[0]?.id; + + if (!(await this.doesUserExist(userId))) return undefined; + + return new WorkspacesUser(this.instance, userId); + } +} diff --git a/instance/src/systems/webFrontend.ts b/instance/src/systems/webFrontend.ts index 6908ca1..c2aa07b 100644 --- a/instance/src/systems/webFrontend.ts +++ b/instance/src/systems/webFrontend.ts @@ -1,28 +1,28 @@ -import path from "node:path"; -import { createServer as createViteServer, type ViteDevServer } from "vite"; -import type { Instance } from "../index.ts"; -import System from "../system.ts"; - -export default class WebFrontendSystem extends System { - viteServer!: ViteDevServer; - - constructor(instance: Instance) { - super("web_frontend", instance); - } - - override async startup(): Promise { - if (this.instance.sys.configuration.isDevMode) { - this.viteServer = await createViteServer({ - configFile: path.join(this.instance.sys.filesystem.SRC_ROOT, "web/vite.config.ts"), - root: path.join(this.instance.sys.filesystem.SRC_ROOT, "web"), - clearScreen: false, - optimizeDeps: { - exclude: ["fsevents"], - }, - }); - await this.viteServer.listen(); - this.log.info("Listening for web requests:"); - } - return true; - } -} +import path from "node:path"; +import { createServer as createViteServer, type ViteDevServer } from "vite"; +import type { Instance } from "../index.ts"; +import System from "../system.ts"; + +export default class WebFrontendSystem extends System { + viteServer!: ViteDevServer; + + constructor(instance: Instance) { + super("web_frontend", instance); + } + + override async startup(): Promise { + if (this.instance.sys.configuration.isDevMode) { + this.viteServer = await createViteServer({ + configFile: path.join(this.instance.sys.filesystem.SRC_ROOT, "web/vite.config.ts"), + root: path.join(this.instance.sys.filesystem.SRC_ROOT, "web"), + clearScreen: false, + optimizeDeps: { + exclude: ["fsevents"], + }, + }); + await this.viteServer.listen(); + this.log.info("Listening for web requests:"); + } + return true; + } +} diff --git a/instance/src/web/.gitignore b/instance/src/web/.gitignore index a547bf3..4108b33 100644 --- a/instance/src/web/.gitignore +++ b/instance/src/web/.gitignore @@ -1,24 +1,24 @@ -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* -lerna-debug.log* - -node_modules -dist -dist-ssr -*.local - -# Editor directories and files -.vscode/* -!.vscode/extensions.json -.idea -.DS_Store -*.suo -*.ntvs* -*.njsproj -*.sln -*.sw? +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/instance/src/web/index.html b/instance/src/web/index.html index a7fd27d..8f7b114 100644 --- a/instance/src/web/index.html +++ b/instance/src/web/index.html @@ -1,21 +1,21 @@ - - - - - - - - - - - Workspace - - -
- - - + + + + + + + + + + + Workspace + + +
+ + + diff --git a/instance/src/web/package.json b/instance/src/web/package.json index 2829c92..c79eb4b 100644 --- a/instance/src/web/package.json +++ b/instance/src/web/package.json @@ -1,35 +1,35 @@ -{ - "name": "@onlineworkspace/workspace-instance-web", - "private": true, - "version": "0.0.0", - "type": "module", - "scripts": { - "dev": "vite --host", - "build": "vite build", - "preview": "vite preview" - }, - "dependencies": { - "@material-symbols/svg-700": "^0.42.3", - "@material/material-color-utilities": "^0.3.0", - "@ewsgit/uikit-solid": "workspace:*", - "@simplewebauthn/browser": "^13.3.0", - "@solid-primitives/media": "^2.3.5", - "@solid-primitives/refs": "^1.1.3", - "@solid-primitives/upload": "^0.1.4", - "@solidjs/router": "^0.16.1", - "@trpc/client": "^11.13.4", - "@trpc/server": "^11.13.4", - "@types/qrcode": "^1.5.6", - "clsx": "^2.1.1", - "qrcode": "^1.5.4", - "solid-devtools": "^0.34.5", - "solid-js": "^1.9.11", - "vite-plugin-compression2": "^2.5.3" - }, - "devDependencies": { - "typescript": "~5.9.3", - "vite": "^8.0.8", - "vite-plugin-solid": "^2.11.11", - "sass-embedded": "^1.98.0" - } +{ + "name": "@onlineworkspace/workspace-instance-web", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite --host", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "@material-symbols/svg-700": "^0.42.3", + "@material/material-color-utilities": "^0.3.0", + "@ewsgit/uikit-solid": "workspace:*", + "@simplewebauthn/browser": "^13.3.0", + "@solid-primitives/media": "^2.3.5", + "@solid-primitives/refs": "^1.1.3", + "@solid-primitives/upload": "^0.1.4", + "@solidjs/router": "^0.16.1", + "@trpc/client": "^11.13.4", + "@trpc/server": "^11.13.4", + "@types/qrcode": "^1.5.6", + "clsx": "^2.1.1", + "qrcode": "^1.5.4", + "solid-devtools": "^0.34.5", + "solid-js": "^1.9.11", + "vite-plugin-compression2": "^2.5.3" + }, + "devDependencies": { + "typescript": "~5.9.3", + "vite": "^8.0.8", + "vite-plugin-solid": "^2.11.11", + "sass-embedded": "^1.98.0" + } } \ No newline at end of file diff --git a/instance/src/web/public/app.webmanifest b/instance/src/web/public/app.webmanifest index ad88b29..a207124 100644 --- a/instance/src/web/public/app.webmanifest +++ b/instance/src/web/public/app.webmanifest @@ -1,13 +1,13 @@ -{ - "name": "Online Workspaces", - "short_name": "Workspaces", - "icons": [ - { - "src": "assets/onlineworkspace/online_workspace_logo.svg", - "type": "image/svg", - "sizes": "512x512", - "purpose": "maskable" - } - ], - "display": "standalone" -} +{ + "name": "Online Workspaces", + "short_name": "Workspaces", + "icons": [ + { + "src": "assets/onlineworkspace/online_workspace_logo.svg", + "type": "image/svg", + "sizes": "512x512", + "purpose": "maskable" + } + ], + "display": "standalone" +} diff --git a/instance/src/web/public/assets/onlineworkspace/online_workspace_logo.svg b/instance/src/web/public/assets/onlineworkspace/online_workspace_logo.svg index 86aa949..ffcc914 100644 --- a/instance/src/web/public/assets/onlineworkspace/online_workspace_logo.svg +++ b/instance/src/web/public/assets/onlineworkspace/online_workspace_logo.svg @@ -1,19 +1,19 @@ - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + diff --git a/instance/src/web/public/assets/onlineworkspace/online_workspace_wordmark.svg b/instance/src/web/public/assets/onlineworkspace/online_workspace_wordmark.svg index 015de59..87ccc0b 100644 --- a/instance/src/web/public/assets/onlineworkspace/online_workspace_wordmark.svg +++ b/instance/src/web/public/assets/onlineworkspace/online_workspace_wordmark.svg @@ -1,23 +1,23 @@ - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + diff --git a/instance/src/web/public/assets/placeholder/placeholder_image.svg b/instance/src/web/public/assets/placeholder/placeholder_image.svg index a9bffe5..41c75f0 100644 --- a/instance/src/web/public/assets/placeholder/placeholder_image.svg +++ b/instance/src/web/public/assets/placeholder/placeholder_image.svg @@ -1,495 +1,495 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/instance/src/web/public/fonts/roboto.css b/instance/src/web/public/fonts/roboto.css index cf12c83..922198a 100644 --- a/instance/src/web/public/fonts/roboto.css +++ b/instance/src/web/public/fonts/roboto.css @@ -1,80 +1,80 @@ -/* math */ -@font-face { - font-family: 'Roboto'; - font-style: italic; - font-weight: 100 900; - font-stretch: 100%; - font-display: swap; - src: url(/fonts/roboto_italic_math.woff2) format('woff2'); - unicode-range: U+0302-0303, U+0305, U+0307-0308, U+0310, U+0312, U+0315, U+031A, U+0326-0327, U+032C, U+032F-0330, U+0332-0333, U+0338, U+033A, U+0346, U+034D, U+0391-03A1, U+03A3-03A9, U+03B1-03C9, U+03D1, U+03D5-03D6, U+03F0-03F1, U+03F4-03F5, U+2016-2017, U+2034-2038, U+203C, U+2040, U+2043, U+2047, U+2050, U+2057, U+205F, U+2070-2071, U+2074-208E, U+2090-209C, U+20D0-20DC, U+20E1, U+20E5-20EF, U+2100-2112, U+2114-2115, U+2117-2121, U+2123-214F, U+2190, U+2192, U+2194-21AE, U+21B0-21E5, U+21F1-21F2, U+21F4-2211, U+2213-2214, U+2216-22FF, U+2308-230B, U+2310, U+2319, U+231C-2321, U+2336-237A, U+237C, U+2395, U+239B-23B7, U+23D0, U+23DC-23E1, U+2474-2475, U+25AF, U+25B3, U+25B7, U+25BD, U+25C1, U+25CA, U+25CC, U+25FB, U+266D-266F, U+27C0-27FF, U+2900-2AFF, U+2B0E-2B11, U+2B30-2B4C, U+2BFE, U+3030, U+FF5B, U+FF5D, U+1D400-1D7FF, U+1EE00-1EEFF; -} -/* symbols */ -@font-face { - font-family: 'Roboto'; - font-style: italic; - font-weight: 100 900; - font-stretch: 100%; - font-display: swap; - src: url(/fonts/roboto_italic_symbols.woff2) format('woff2'); - unicode-range: U+0001-000C, U+000E-001F, U+007F-009F, U+20DD-20E0, U+20E2-20E4, U+2150-218F, U+2190, U+2192, U+2194-2199, U+21AF, U+21E6-21F0, U+21F3, U+2218-2219, U+2299, U+22C4-22C6, U+2300-243F, U+2440-244A, U+2460-24FF, U+25A0-27BF, U+2800-28FF, U+2921-2922, U+2981, U+29BF, U+29EB, U+2B00-2BFF, U+4DC0-4DFF, U+FFF9-FFFB, U+10140-1018E, U+10190-1019C, U+101A0, U+101D0-101FD, U+102E0-102FB, U+10E60-10E7E, U+1D2C0-1D2D3, U+1D2E0-1D37F, U+1F000-1F0FF, U+1F100-1F1AD, U+1F1E6-1F1FF, U+1F30D-1F30F, U+1F315, U+1F31C, U+1F31E, U+1F320-1F32C, U+1F336, U+1F378, U+1F37D, U+1F382, U+1F393-1F39F, U+1F3A7-1F3A8, U+1F3AC-1F3AF, U+1F3C2, U+1F3C4-1F3C6, U+1F3CA-1F3CE, U+1F3D4-1F3E0, U+1F3ED, U+1F3F1-1F3F3, U+1F3F5-1F3F7, U+1F408, U+1F415, U+1F41F, U+1F426, U+1F43F, U+1F441-1F442, U+1F444, U+1F446-1F449, U+1F44C-1F44E, U+1F453, U+1F46A, U+1F47D, U+1F4A3, U+1F4B0, U+1F4B3, U+1F4B9, U+1F4BB, U+1F4BF, U+1F4C8-1F4CB, U+1F4D6, U+1F4DA, U+1F4DF, U+1F4E3-1F4E6, U+1F4EA-1F4ED, U+1F4F7, U+1F4F9-1F4FB, U+1F4FD-1F4FE, U+1F503, U+1F507-1F50B, U+1F50D, U+1F512-1F513, U+1F53E-1F54A, U+1F54F-1F5FA, U+1F610, U+1F650-1F67F, U+1F687, U+1F68D, U+1F691, U+1F694, U+1F698, U+1F6AD, U+1F6B2, U+1F6B9-1F6BA, U+1F6BC, U+1F6C6-1F6CF, U+1F6D3-1F6D7, U+1F6E0-1F6EA, U+1F6F0-1F6F3, U+1F6F7-1F6FC, U+1F700-1F7FF, U+1F800-1F80B, U+1F810-1F847, U+1F850-1F859, U+1F860-1F887, U+1F890-1F8AD, U+1F8B0-1F8BB, U+1F8C0-1F8C1, U+1F900-1F90B, U+1F93B, U+1F946, U+1F984, U+1F996, U+1F9E9, U+1FA00-1FA6F, U+1FA70-1FA7C, U+1FA80-1FA89, U+1FA8F-1FAC6, U+1FACE-1FADC, U+1FADF-1FAE9, U+1FAF0-1FAF8, U+1FB00-1FBFF; -} -/* latin-ext */ -@font-face { - font-family: 'Roboto'; - font-style: italic; - font-weight: 100 900; - font-stretch: 100%; - font-display: swap; - src: url(/fonts/roboto_italic_latin_ext.woff2) format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -/* latin */ -@font-face { - font-family: 'Roboto'; - font-style: italic; - font-weight: 100 900; - font-stretch: 100%; - font-display: swap; - src: url(/fonts/roboto_italic_latin.woff2) format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} -/* math */ -@font-face { - font-family: 'Roboto'; - font-style: normal; - font-weight: 100 900; - font-stretch: 100%; - font-display: swap; - src: url(/fonts/roboto_math.woff2) format('woff2'); - unicode-range: U+0302-0303, U+0305, U+0307-0308, U+0310, U+0312, U+0315, U+031A, U+0326-0327, U+032C, U+032F-0330, U+0332-0333, U+0338, U+033A, U+0346, U+034D, U+0391-03A1, U+03A3-03A9, U+03B1-03C9, U+03D1, U+03D5-03D6, U+03F0-03F1, U+03F4-03F5, U+2016-2017, U+2034-2038, U+203C, U+2040, U+2043, U+2047, U+2050, U+2057, U+205F, U+2070-2071, U+2074-208E, U+2090-209C, U+20D0-20DC, U+20E1, U+20E5-20EF, U+2100-2112, U+2114-2115, U+2117-2121, U+2123-214F, U+2190, U+2192, U+2194-21AE, U+21B0-21E5, U+21F1-21F2, U+21F4-2211, U+2213-2214, U+2216-22FF, U+2308-230B, U+2310, U+2319, U+231C-2321, U+2336-237A, U+237C, U+2395, U+239B-23B7, U+23D0, U+23DC-23E1, U+2474-2475, U+25AF, U+25B3, U+25B7, U+25BD, U+25C1, U+25CA, U+25CC, U+25FB, U+266D-266F, U+27C0-27FF, U+2900-2AFF, U+2B0E-2B11, U+2B30-2B4C, U+2BFE, U+3030, U+FF5B, U+FF5D, U+1D400-1D7FF, U+1EE00-1EEFF; -} -/* symbols */ -@font-face { - font-family: 'Roboto'; - font-style: normal; - font-weight: 100 900; - font-stretch: 100%; - font-display: swap; - src: url(/fonts/roboto_symbols.woff2) format('woff2'); - unicode-range: U+0001-000C, U+000E-001F, U+007F-009F, U+20DD-20E0, U+20E2-20E4, U+2150-218F, U+2190, U+2192, U+2194-2199, U+21AF, U+21E6-21F0, U+21F3, U+2218-2219, U+2299, U+22C4-22C6, U+2300-243F, U+2440-244A, U+2460-24FF, U+25A0-27BF, U+2800-28FF, U+2921-2922, U+2981, U+29BF, U+29EB, U+2B00-2BFF, U+4DC0-4DFF, U+FFF9-FFFB, U+10140-1018E, U+10190-1019C, U+101A0, U+101D0-101FD, U+102E0-102FB, U+10E60-10E7E, U+1D2C0-1D2D3, U+1D2E0-1D37F, U+1F000-1F0FF, U+1F100-1F1AD, U+1F1E6-1F1FF, U+1F30D-1F30F, U+1F315, U+1F31C, U+1F31E, U+1F320-1F32C, U+1F336, U+1F378, U+1F37D, U+1F382, U+1F393-1F39F, U+1F3A7-1F3A8, U+1F3AC-1F3AF, U+1F3C2, U+1F3C4-1F3C6, U+1F3CA-1F3CE, U+1F3D4-1F3E0, U+1F3ED, U+1F3F1-1F3F3, U+1F3F5-1F3F7, U+1F408, U+1F415, U+1F41F, U+1F426, U+1F43F, U+1F441-1F442, U+1F444, U+1F446-1F449, U+1F44C-1F44E, U+1F453, U+1F46A, U+1F47D, U+1F4A3, U+1F4B0, U+1F4B3, U+1F4B9, U+1F4BB, U+1F4BF, U+1F4C8-1F4CB, U+1F4D6, U+1F4DA, U+1F4DF, U+1F4E3-1F4E6, U+1F4EA-1F4ED, U+1F4F7, U+1F4F9-1F4FB, U+1F4FD-1F4FE, U+1F503, U+1F507-1F50B, U+1F50D, U+1F512-1F513, U+1F53E-1F54A, U+1F54F-1F5FA, U+1F610, U+1F650-1F67F, U+1F687, U+1F68D, U+1F691, U+1F694, U+1F698, U+1F6AD, U+1F6B2, U+1F6B9-1F6BA, U+1F6BC, U+1F6C6-1F6CF, U+1F6D3-1F6D7, U+1F6E0-1F6EA, U+1F6F0-1F6F3, U+1F6F7-1F6FC, U+1F700-1F7FF, U+1F800-1F80B, U+1F810-1F847, U+1F850-1F859, U+1F860-1F887, U+1F890-1F8AD, U+1F8B0-1F8BB, U+1F8C0-1F8C1, U+1F900-1F90B, U+1F93B, U+1F946, U+1F984, U+1F996, U+1F9E9, U+1FA00-1FA6F, U+1FA70-1FA7C, U+1FA80-1FA89, U+1FA8F-1FAC6, U+1FACE-1FADC, U+1FADF-1FAE9, U+1FAF0-1FAF8, U+1FB00-1FBFF; -} -/* latin-ext */ -@font-face { - font-family: 'Roboto'; - font-style: normal; - font-weight: 100 900; - font-stretch: 100%; - font-display: swap; - src: url(/fonts/roboto_latin_ext.woff2) format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -/* latin */ -@font-face { - font-family: 'Roboto'; - font-style: normal; - font-weight: 100 900; - font-stretch: 100%; - font-display: swap; - src: url(/fonts/roboto_latin.woff2) format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} +/* math */ +@font-face { + font-family: 'Roboto'; + font-style: italic; + font-weight: 100 900; + font-stretch: 100%; + font-display: swap; + src: url(/fonts/roboto_italic_math.woff2) format('woff2'); + unicode-range: U+0302-0303, U+0305, U+0307-0308, U+0310, U+0312, U+0315, U+031A, U+0326-0327, U+032C, U+032F-0330, U+0332-0333, U+0338, U+033A, U+0346, U+034D, U+0391-03A1, U+03A3-03A9, U+03B1-03C9, U+03D1, U+03D5-03D6, U+03F0-03F1, U+03F4-03F5, U+2016-2017, U+2034-2038, U+203C, U+2040, U+2043, U+2047, U+2050, U+2057, U+205F, U+2070-2071, U+2074-208E, U+2090-209C, U+20D0-20DC, U+20E1, U+20E5-20EF, U+2100-2112, U+2114-2115, U+2117-2121, U+2123-214F, U+2190, U+2192, U+2194-21AE, U+21B0-21E5, U+21F1-21F2, U+21F4-2211, U+2213-2214, U+2216-22FF, U+2308-230B, U+2310, U+2319, U+231C-2321, U+2336-237A, U+237C, U+2395, U+239B-23B7, U+23D0, U+23DC-23E1, U+2474-2475, U+25AF, U+25B3, U+25B7, U+25BD, U+25C1, U+25CA, U+25CC, U+25FB, U+266D-266F, U+27C0-27FF, U+2900-2AFF, U+2B0E-2B11, U+2B30-2B4C, U+2BFE, U+3030, U+FF5B, U+FF5D, U+1D400-1D7FF, U+1EE00-1EEFF; +} +/* symbols */ +@font-face { + font-family: 'Roboto'; + font-style: italic; + font-weight: 100 900; + font-stretch: 100%; + font-display: swap; + src: url(/fonts/roboto_italic_symbols.woff2) format('woff2'); + unicode-range: U+0001-000C, U+000E-001F, U+007F-009F, U+20DD-20E0, U+20E2-20E4, U+2150-218F, U+2190, U+2192, U+2194-2199, U+21AF, U+21E6-21F0, U+21F3, U+2218-2219, U+2299, U+22C4-22C6, U+2300-243F, U+2440-244A, U+2460-24FF, U+25A0-27BF, U+2800-28FF, U+2921-2922, U+2981, U+29BF, U+29EB, U+2B00-2BFF, U+4DC0-4DFF, U+FFF9-FFFB, U+10140-1018E, U+10190-1019C, U+101A0, U+101D0-101FD, U+102E0-102FB, U+10E60-10E7E, U+1D2C0-1D2D3, U+1D2E0-1D37F, U+1F000-1F0FF, U+1F100-1F1AD, U+1F1E6-1F1FF, U+1F30D-1F30F, U+1F315, U+1F31C, U+1F31E, U+1F320-1F32C, U+1F336, U+1F378, U+1F37D, U+1F382, U+1F393-1F39F, U+1F3A7-1F3A8, U+1F3AC-1F3AF, U+1F3C2, U+1F3C4-1F3C6, U+1F3CA-1F3CE, U+1F3D4-1F3E0, U+1F3ED, U+1F3F1-1F3F3, U+1F3F5-1F3F7, U+1F408, U+1F415, U+1F41F, U+1F426, U+1F43F, U+1F441-1F442, U+1F444, U+1F446-1F449, U+1F44C-1F44E, U+1F453, U+1F46A, U+1F47D, U+1F4A3, U+1F4B0, U+1F4B3, U+1F4B9, U+1F4BB, U+1F4BF, U+1F4C8-1F4CB, U+1F4D6, U+1F4DA, U+1F4DF, U+1F4E3-1F4E6, U+1F4EA-1F4ED, U+1F4F7, U+1F4F9-1F4FB, U+1F4FD-1F4FE, U+1F503, U+1F507-1F50B, U+1F50D, U+1F512-1F513, U+1F53E-1F54A, U+1F54F-1F5FA, U+1F610, U+1F650-1F67F, U+1F687, U+1F68D, U+1F691, U+1F694, U+1F698, U+1F6AD, U+1F6B2, U+1F6B9-1F6BA, U+1F6BC, U+1F6C6-1F6CF, U+1F6D3-1F6D7, U+1F6E0-1F6EA, U+1F6F0-1F6F3, U+1F6F7-1F6FC, U+1F700-1F7FF, U+1F800-1F80B, U+1F810-1F847, U+1F850-1F859, U+1F860-1F887, U+1F890-1F8AD, U+1F8B0-1F8BB, U+1F8C0-1F8C1, U+1F900-1F90B, U+1F93B, U+1F946, U+1F984, U+1F996, U+1F9E9, U+1FA00-1FA6F, U+1FA70-1FA7C, U+1FA80-1FA89, U+1FA8F-1FAC6, U+1FACE-1FADC, U+1FADF-1FAE9, U+1FAF0-1FAF8, U+1FB00-1FBFF; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto'; + font-style: italic; + font-weight: 100 900; + font-stretch: 100%; + font-display: swap; + src: url(/fonts/roboto_italic_latin_ext.woff2) format('woff2'); + unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto'; + font-style: italic; + font-weight: 100 900; + font-stretch: 100%; + font-display: swap; + src: url(/fonts/roboto_italic_latin.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* math */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100 900; + font-stretch: 100%; + font-display: swap; + src: url(/fonts/roboto_math.woff2) format('woff2'); + unicode-range: U+0302-0303, U+0305, U+0307-0308, U+0310, U+0312, U+0315, U+031A, U+0326-0327, U+032C, U+032F-0330, U+0332-0333, U+0338, U+033A, U+0346, U+034D, U+0391-03A1, U+03A3-03A9, U+03B1-03C9, U+03D1, U+03D5-03D6, U+03F0-03F1, U+03F4-03F5, U+2016-2017, U+2034-2038, U+203C, U+2040, U+2043, U+2047, U+2050, U+2057, U+205F, U+2070-2071, U+2074-208E, U+2090-209C, U+20D0-20DC, U+20E1, U+20E5-20EF, U+2100-2112, U+2114-2115, U+2117-2121, U+2123-214F, U+2190, U+2192, U+2194-21AE, U+21B0-21E5, U+21F1-21F2, U+21F4-2211, U+2213-2214, U+2216-22FF, U+2308-230B, U+2310, U+2319, U+231C-2321, U+2336-237A, U+237C, U+2395, U+239B-23B7, U+23D0, U+23DC-23E1, U+2474-2475, U+25AF, U+25B3, U+25B7, U+25BD, U+25C1, U+25CA, U+25CC, U+25FB, U+266D-266F, U+27C0-27FF, U+2900-2AFF, U+2B0E-2B11, U+2B30-2B4C, U+2BFE, U+3030, U+FF5B, U+FF5D, U+1D400-1D7FF, U+1EE00-1EEFF; +} +/* symbols */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100 900; + font-stretch: 100%; + font-display: swap; + src: url(/fonts/roboto_symbols.woff2) format('woff2'); + unicode-range: U+0001-000C, U+000E-001F, U+007F-009F, U+20DD-20E0, U+20E2-20E4, U+2150-218F, U+2190, U+2192, U+2194-2199, U+21AF, U+21E6-21F0, U+21F3, U+2218-2219, U+2299, U+22C4-22C6, U+2300-243F, U+2440-244A, U+2460-24FF, U+25A0-27BF, U+2800-28FF, U+2921-2922, U+2981, U+29BF, U+29EB, U+2B00-2BFF, U+4DC0-4DFF, U+FFF9-FFFB, U+10140-1018E, U+10190-1019C, U+101A0, U+101D0-101FD, U+102E0-102FB, U+10E60-10E7E, U+1D2C0-1D2D3, U+1D2E0-1D37F, U+1F000-1F0FF, U+1F100-1F1AD, U+1F1E6-1F1FF, U+1F30D-1F30F, U+1F315, U+1F31C, U+1F31E, U+1F320-1F32C, U+1F336, U+1F378, U+1F37D, U+1F382, U+1F393-1F39F, U+1F3A7-1F3A8, U+1F3AC-1F3AF, U+1F3C2, U+1F3C4-1F3C6, U+1F3CA-1F3CE, U+1F3D4-1F3E0, U+1F3ED, U+1F3F1-1F3F3, U+1F3F5-1F3F7, U+1F408, U+1F415, U+1F41F, U+1F426, U+1F43F, U+1F441-1F442, U+1F444, U+1F446-1F449, U+1F44C-1F44E, U+1F453, U+1F46A, U+1F47D, U+1F4A3, U+1F4B0, U+1F4B3, U+1F4B9, U+1F4BB, U+1F4BF, U+1F4C8-1F4CB, U+1F4D6, U+1F4DA, U+1F4DF, U+1F4E3-1F4E6, U+1F4EA-1F4ED, U+1F4F7, U+1F4F9-1F4FB, U+1F4FD-1F4FE, U+1F503, U+1F507-1F50B, U+1F50D, U+1F512-1F513, U+1F53E-1F54A, U+1F54F-1F5FA, U+1F610, U+1F650-1F67F, U+1F687, U+1F68D, U+1F691, U+1F694, U+1F698, U+1F6AD, U+1F6B2, U+1F6B9-1F6BA, U+1F6BC, U+1F6C6-1F6CF, U+1F6D3-1F6D7, U+1F6E0-1F6EA, U+1F6F0-1F6F3, U+1F6F7-1F6FC, U+1F700-1F7FF, U+1F800-1F80B, U+1F810-1F847, U+1F850-1F859, U+1F860-1F887, U+1F890-1F8AD, U+1F8B0-1F8BB, U+1F8C0-1F8C1, U+1F900-1F90B, U+1F93B, U+1F946, U+1F984, U+1F996, U+1F9E9, U+1FA00-1FA6F, U+1FA70-1FA7C, U+1FA80-1FA89, U+1FA8F-1FAC6, U+1FACE-1FADC, U+1FADF-1FAE9, U+1FAF0-1FAF8, U+1FB00-1FBFF; +} +/* latin-ext */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100 900; + font-stretch: 100%; + font-display: swap; + src: url(/fonts/roboto_latin_ext.woff2) format('woff2'); + unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto'; + font-style: normal; + font-weight: 100 900; + font-stretch: 100%; + font-display: swap; + src: url(/fonts/roboto_latin.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} diff --git a/instance/src/web/public/fonts/roboto_flex.css b/instance/src/web/public/fonts/roboto_flex.css index 68bf579..cca7272 100644 --- a/instance/src/web/public/fonts/roboto_flex.css +++ b/instance/src/web/public/fonts/roboto_flex.css @@ -1,20 +1,20 @@ -/* latin-ext */ -@font-face { - font-family: 'Roboto Flex'; - font-style: normal; - font-weight: 100 1000; - font-stretch: 100%; - font-display: swap; - src: url(/fonts/roboto_flex_latin_ext.woff2) format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -/* latin */ -@font-face { - font-family: 'Roboto Flex'; - font-style: normal; - font-weight: 100 1000; - font-stretch: 100%; - font-display: swap; - src: url(/fonts/roboto_flex_latin.woff2) format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} +/* latin-ext */ +@font-face { + font-family: 'Roboto Flex'; + font-style: normal; + font-weight: 100 1000; + font-stretch: 100%; + font-display: swap; + src: url(/fonts/roboto_flex_latin_ext.woff2) format('woff2'); + unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Roboto Flex'; + font-style: normal; + font-weight: 100 1000; + font-stretch: 100%; + font-display: swap; + src: url(/fonts/roboto_flex_latin.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} diff --git a/instance/src/web/src/App.module.scss b/instance/src/web/src/App.module.scss index 336768f..0a4ac65 100644 --- a/instance/src/web/src/App.module.scss +++ b/instance/src/web/src/App.module.scss @@ -1,14 +1,14 @@ -.root { - width: 100%; - height: 100%; - padding: 0; - margin: 0; - overflow-y: auto; -} - -.spinner { - position: fixed; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); -} +.root { + width: 100%; + height: 100%; + padding: 0; + margin: 0; + overflow-y: auto; +} + +.spinner { + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); +} diff --git a/instance/src/web/src/App.tsx b/instance/src/web/src/App.tsx index 1524769..d89a580 100644 --- a/instance/src/web/src/App.tsx +++ b/instance/src/web/src/App.tsx @@ -1,35 +1,35 @@ -import { UIKitRoot } from "@ewsgit/uikit-solid/src/index.tsx"; -// @ts-ignore -import ApplicationsRouter from "@onlineworkspace/workspaces-applications"; -import { Route, Router } from "@solidjs/router"; -import { type Component, lazy } from "solid-js"; -import styles from "./App.module.scss"; -import MissingApp from "./MissingApp.tsx"; -import AppIndex from "./pages/app/Index.tsx"; - -const App: Component = () => { - return ( - - - import("./pages/userSelect/Layout.tsx"))}> - import("./pages/userSelect/login/Login.tsx"))} /> - import("./pages/userSelect/signup/Signup.tsx"))} /> - import("./pages/userSelect/forgotPassword/ForgotPassword.tsx"))} /> - - import("./pages/app/AuthCheck.tsx"))}> - import("./pages/app/Layout.tsx"))}> - - - - - - import("./pages/notFound/Index.tsx"))} /> - - - import("./pages/notFound/Index.tsx"))} /> - - - ); -}; - -export default App; +import { UIKitRoot } from "@ewsgit/uikit-solid/src/index.tsx"; +// @ts-ignore +import ApplicationsRouter from "@onlineworkspace/workspaces-applications"; +import { Route, Router } from "@solidjs/router"; +import { type Component, lazy } from "solid-js"; +import styles from "./App.module.scss"; +import MissingApp from "./MissingApp.tsx"; +import AppIndex from "./pages/app/Index.tsx"; + +const App: Component = () => { + return ( + + + import("./pages/userSelect/Layout.tsx"))}> + import("./pages/userSelect/login/Login.tsx"))} /> + import("./pages/userSelect/signup/Signup.tsx"))} /> + import("./pages/userSelect/forgotPassword/ForgotPassword.tsx"))} /> + + import("./pages/app/AuthCheck.tsx"))}> + import("./pages/app/Layout.tsx"))}> + + + + + + import("./pages/notFound/Index.tsx"))} /> + + + import("./pages/notFound/Index.tsx"))} /> + + + ); +}; + +export default App; diff --git a/instance/src/web/src/MissingApp.module.scss b/instance/src/web/src/MissingApp.module.scss index 1c25bfc..dbbae1b 100644 --- a/instance/src/web/src/MissingApp.module.scss +++ b/instance/src/web/src/MissingApp.module.scss @@ -1,9 +1,9 @@ -.root { - display: flex; - width: 100%; - height: 100%; - justify-content: center; - align-items: center; - flex-direction: column; - gap: 0.5rem; -} +.root { + display: flex; + width: 100%; + height: 100%; + justify-content: center; + align-items: center; + flex-direction: column; + gap: 0.5rem; +} diff --git a/instance/src/web/src/MissingApp.tsx b/instance/src/web/src/MissingApp.tsx index dbe3fc0..16b837c 100644 --- a/instance/src/web/src/MissingApp.tsx +++ b/instance/src/web/src/MissingApp.tsx @@ -1,30 +1,30 @@ -import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import { useNavigate, useParams } from "@solidjs/router"; -import type { Component } from "solid-js"; -import styles from "./MissingApp.module.scss"; - -const MissingApp: Component = () => { - const params = useParams(); - const navigate = useNavigate(); - - return ( -
- - Missing Application - - - The application '{params.applicationId}' cannot be found. - - { - navigate("/app/uk.ewsgit.dashboard"); - }} - > - Back to Dashboard - -
- ); -}; - -export default MissingApp; +import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import { useNavigate, useParams } from "@solidjs/router"; +import type { Component } from "solid-js"; +import styles from "./MissingApp.module.scss"; + +const MissingApp: Component = () => { + const params = useParams(); + const navigate = useNavigate(); + + return ( +
+ + Missing Application + + + The application '{params.applicationId}' cannot be found. + + { + navigate("/app/uk.ewsgit.dashboard"); + }} + > + Back to Dashboard + +
+ ); +}; + +export default MissingApp; diff --git a/instance/src/web/src/index.scss b/instance/src/web/src/index.scss index 93e2647..7f13aa5 100644 --- a/instance/src/web/src/index.scss +++ b/instance/src/web/src/index.scss @@ -1,14 +1,14 @@ -body, -html, -#root, -:root { - width: 100%; - height: 100%; - padding: 0; - margin: 0; - overflow-y: auto; -} - -* { - box-sizing: border-box; -} +body, +html, +#root, +:root { + width: 100%; + height: 100%; + padding: 0; + margin: 0; + overflow-y: auto; +} + +* { + box-sizing: border-box; +} diff --git a/instance/src/web/src/index.tsx b/instance/src/web/src/index.tsx index c1a9bc6..27352d3 100644 --- a/instance/src/web/src/index.tsx +++ b/instance/src/web/src/index.tsx @@ -1,9 +1,9 @@ -/* @refresh reload */ -import { render } from "solid-js/web"; -import "./index.scss"; -// import "solid-devtools"; -import App from "./App.tsx"; - -const root = document.getElementById("root"); - -render(() => , root!); +/* @refresh reload */ +import { render } from "solid-js/web"; +import "./index.scss"; +// import "solid-devtools"; +import App from "./App.tsx"; + +const root = document.getElementById("root"); + +render(() => , root!); diff --git a/instance/src/web/src/lib/backend.ts b/instance/src/web/src/lib/backend.ts index 1af8ad4..e8100d7 100644 --- a/instance/src/web/src/lib/backend.ts +++ b/instance/src/web/src/lib/backend.ts @@ -1,7 +1,7 @@ -export default function backend(path: string): string { - if (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1") { - return `https://localhost${path}`; - } - - return `${window.location.origin}${path}`; -} +export default function backend(path: string): string { + if (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1") { + return `https://localhost${path}`; + } + + return `${window.location.origin}${path}`; +} diff --git a/instance/src/web/src/lib/trpc.ts b/instance/src/web/src/lib/trpc.ts index 93cc4c3..5647a30 100644 --- a/instance/src/web/src/lib/trpc.ts +++ b/instance/src/web/src/lib/trpc.ts @@ -1,28 +1,28 @@ -import { createTRPCClient, httpBatchLink } from "@trpc/client"; -import type { WorkspacesTRPCRouter } from "../../../systems/trpcRouter"; -import backend from "./backend"; - -const trpc = createTRPCClient({ - links: [ - // splitLink({ - // condition: (op: { type: string }) => op.type === "subscription", - // true: wsLink({ - // client: createWSClient({ - // url: "ws://localhost:3564", - // connectionParams: async () => { - // return {}; - // }, - // }), - // }), - // false: - httpBatchLink({ - url: backend("/api/trpc"), - fetch(input, init) { - return fetch(input, { credentials: "include", ...init }); - }, - }), - // }), - ], -}); - -export default trpc; +import { createTRPCClient, httpBatchLink } from "@trpc/client"; +import type { WorkspacesTRPCRouter } from "../../../systems/trpcRouter"; +import backend from "./backend"; + +const trpc = createTRPCClient({ + links: [ + // splitLink({ + // condition: (op: { type: string }) => op.type === "subscription", + // true: wsLink({ + // client: createWSClient({ + // url: "ws://localhost:3564", + // connectionParams: async () => { + // return {}; + // }, + // }), + // }), + // false: + httpBatchLink({ + url: backend("/api/trpc"), + fetch(input, init) { + return fetch(input, { credentials: "include", ...init }); + }, + }), + // }), + ], +}); + +export default trpc; diff --git a/instance/src/web/src/pages/app/AuthCheck.module.scss b/instance/src/web/src/pages/app/AuthCheck.module.scss index 2d5c42d..3f98dc6 100644 --- a/instance/src/web/src/pages/app/AuthCheck.module.scss +++ b/instance/src/web/src/pages/app/AuthCheck.module.scss @@ -1,22 +1,22 @@ -.root { - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - display: flex; - flex-direction: column; - gap: 1rem; - align-items: center; - justify-content: center; -} - -.button { - margin-left: auto; -} - -.spinner { - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); -} +.root { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + display: flex; + flex-direction: column; + gap: 1rem; + align-items: center; + justify-content: center; +} + +.button { + margin-left: auto; +} + +.spinner { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); +} diff --git a/instance/src/web/src/pages/app/AuthCheck.tsx b/instance/src/web/src/pages/app/AuthCheck.tsx index cc72985..6aef291 100644 --- a/instance/src/web/src/pages/app/AuthCheck.tsx +++ b/instance/src/web/src/pages/app/AuthCheck.tsx @@ -1,45 +1,45 @@ -import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.tsx"; -import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.tsx"; -import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.ts"; -import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.tsx"; -import UKCircularProgressIndicator from "@ewsgit/uikit-solid/src/components/circularProgressIndicator/UKCircularProgressIndicator.tsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.tsx"; -import { useNavigate } from "@solidjs/router"; -import { type Component, createResource, type ParentProps } from "solid-js"; -import trpc from "../../lib/trpc.ts"; -import styles from "./AuthCheck.module.scss"; - -const AuthCheck: Component = (props) => { - const navigate = useNavigate(); - const [checkResult] = createResource(() => trpc.authorization.isAuthenticated.query()); - - return ( - <> - {checkResult() === undefined ? ( - - ) : !checkResult()?.authenticated ? ( - - - Unauthorized - - - - Please login before trying to access this page. - - { - navigate(`/?redirect=${window.location.pathname}`); - }} - > - Login - - - ) : ( - props.children - )} - - ); -}; - -export default AuthCheck; +import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.tsx"; +import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.tsx"; +import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.ts"; +import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.tsx"; +import UKCircularProgressIndicator from "@ewsgit/uikit-solid/src/components/circularProgressIndicator/UKCircularProgressIndicator.tsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.tsx"; +import { useNavigate } from "@solidjs/router"; +import { type Component, createResource, type ParentProps } from "solid-js"; +import trpc from "../../lib/trpc.ts"; +import styles from "./AuthCheck.module.scss"; + +const AuthCheck: Component = (props) => { + const navigate = useNavigate(); + const [checkResult] = createResource(() => trpc.authorization.isAuthenticated.query()); + + return ( + <> + {checkResult() === undefined ? ( + + ) : !checkResult()?.authenticated ? ( + + + Unauthorized + + + + Please login before trying to access this page. + + { + navigate(`/?redirect=${window.location.pathname}`); + }} + > + Login + + + ) : ( + props.children + )} + + ); +}; + +export default AuthCheck; diff --git a/instance/src/web/src/pages/app/Index.tsx b/instance/src/web/src/pages/app/Index.tsx index d93c1c1..e383f97 100644 --- a/instance/src/web/src/pages/app/Index.tsx +++ b/instance/src/web/src/pages/app/Index.tsx @@ -1,13 +1,13 @@ -import { useNavigate } from "@solidjs/router"; -import type { Component } from "solid-js"; - -const AppIndex: Component = () => { - const navigate = useNavigate(); - - // this should be a trpc request to allow the user to change it - navigate("/app/uk.ewsgit.dashboard"); - - return null; -}; - -export default AppIndex; +import { useNavigate } from "@solidjs/router"; +import type { Component } from "solid-js"; + +const AppIndex: Component = () => { + const navigate = useNavigate(); + + // this should be a trpc request to allow the user to change it + navigate("/app/uk.ewsgit.dashboard"); + + return null; +}; + +export default AppIndex; diff --git a/instance/src/web/src/pages/app/Layout.module.scss b/instance/src/web/src/pages/app/Layout.module.scss index 147ed43..62a5ec5 100644 --- a/instance/src/web/src/pages/app/Layout.module.scss +++ b/instance/src/web/src/pages/app/Layout.module.scss @@ -1,10 +1,10 @@ -.page { - display: flex; - flex-direction: column; - width: 100%; - height: 100%; - - /* remove later */ - align-items: center; - justify-content: center; -} +.page { + display: flex; + flex-direction: column; + width: 100%; + height: 100%; + + /* remove later */ + align-items: center; + justify-content: center; +} diff --git a/instance/src/web/src/pages/app/Layout.tsx b/instance/src/web/src/pages/app/Layout.tsx index cf99787..83949d0 100644 --- a/instance/src/web/src/pages/app/Layout.tsx +++ b/instance/src/web/src/pages/app/Layout.tsx @@ -1,66 +1,66 @@ -import UKCircularProgressIndicator from "@ewsgit/uikit-solid/src/components/circularProgressIndicator/UKCircularProgressIndicator.jsx"; -import { baselineTheme } from "@ewsgit/uikit-solid/src/core/design/themes/baseline.js"; -import { applyTheme } from "@ewsgit/uikit-solid/src/core/design/tokens.js"; -import { Ref } from "@solid-primitives/refs"; -import type { RouteSectionProps } from "@solidjs/router"; -import { type Component, createEffect, createSignal, lazy, Suspense } from "solid-js"; -import trpc from "../../lib/trpc.ts"; -import styles from "./Layout.module.scss"; - -const AppNavigation = lazy(() => import("./Navigation.tsx")); - -const AppLayout: Component> = (props) => { - const [ref, setRef] = createSignal(undefined); - const isLightMode = window.matchMedia("(prefers-color-scheme: light)").matches; - - createEffect(async () => { - const refElement = ref(); - if (!refElement) { - return; - } - - const uikitRoot = refElement?.closest('[data-uikit-root="true"]') as HTMLDivElement | undefined; - - if (!uikitRoot) { - console.warn("Could not find uikit root element. AppNavigation may not be rendered correctly."); - return; - } - - const userTheme = await trpc.theme.get.query(); - - if (userTheme === false) return; - - const parsedUserTheme = { - ...baselineTheme, - sys: { - ...baselineTheme.sys, - color: { - ...baselineTheme.sys.color, - ...userTheme, - }, - }, - }; - - applyTheme(parsedUserTheme, uikitRoot, isLightMode ? "light" : "dark"); - }); - - return ( - <> - {window.localStorage.getItem("onlineworkspace_workspace_no_app_navigation_rail") !== "true" ? ( - - - }>{props.children} - - - ) : ( - -
- }>{props.children} -
-
- )} - - ); -}; - -export default AppLayout; +import UKCircularProgressIndicator from "@ewsgit/uikit-solid/src/components/circularProgressIndicator/UKCircularProgressIndicator.jsx"; +import { baselineTheme } from "@ewsgit/uikit-solid/src/core/design/themes/baseline.js"; +import { applyTheme } from "@ewsgit/uikit-solid/src/core/design/tokens.js"; +import { Ref } from "@solid-primitives/refs"; +import type { RouteSectionProps } from "@solidjs/router"; +import { type Component, createEffect, createSignal, lazy, Suspense } from "solid-js"; +import trpc from "../../lib/trpc.ts"; +import styles from "./Layout.module.scss"; + +const AppNavigation = lazy(() => import("./Navigation.tsx")); + +const AppLayout: Component> = (props) => { + const [ref, setRef] = createSignal(undefined); + const isLightMode = window.matchMedia("(prefers-color-scheme: light)").matches; + + createEffect(async () => { + const refElement = ref(); + if (!refElement) { + return; + } + + const uikitRoot = refElement?.closest('[data-uikit-root="true"]') as HTMLDivElement | undefined; + + if (!uikitRoot) { + console.warn("Could not find uikit root element. AppNavigation may not be rendered correctly."); + return; + } + + const userTheme = await trpc.theme.get.query(); + + if (userTheme === false) return; + + const parsedUserTheme = { + ...baselineTheme, + sys: { + ...baselineTheme.sys, + color: { + ...baselineTheme.sys.color, + ...userTheme, + }, + }, + }; + + applyTheme(parsedUserTheme, uikitRoot, isLightMode ? "light" : "dark"); + }); + + return ( + <> + {window.localStorage.getItem("onlineworkspace_workspace_no_app_navigation_rail") !== "true" ? ( + + + }>{props.children} + + + ) : ( + +
+ }>{props.children} +
+
+ )} + + ); +}; + +export default AppLayout; diff --git a/instance/src/web/src/pages/app/Navigation.module.scss b/instance/src/web/src/pages/app/Navigation.module.scss index b11acca..489b331 100644 --- a/instance/src/web/src/pages/app/Navigation.module.scss +++ b/instance/src/web/src/pages/app/Navigation.module.scss @@ -1,24 +1,24 @@ -.versionLabel { - margin-bottom: 0.5rem; - user-select: none; -} - -.rail { - border-right: 1px solid rgb(var(--uk-sys-color-outline-variant)); - - *[data-navigation-rail-mobile-mode="true"] > & { - border-top: 1px solid rgb(var(--uk-sys-color-outline-variant)); - border-right: none; - } -} - -.page { - display: flex; - flex-direction: column; - width: 100%; - height: 100%; - - /* remove later */ - align-items: center; - justify-content: center; -} +.versionLabel { + margin-bottom: 0.5rem; + user-select: none; +} + +.rail { + border-right: 1px solid rgb(var(--uk-sys-color-outline-variant)); + + *[data-navigation-rail-mobile-mode="true"] > & { + border-top: 1px solid rgb(var(--uk-sys-color-outline-variant)); + border-right: none; + } +} + +.page { + display: flex; + flex-direction: column; + width: 100%; + height: 100%; + + /* remove later */ + align-items: center; + justify-content: center; +} diff --git a/instance/src/web/src/pages/app/Navigation.tsx b/instance/src/web/src/pages/app/Navigation.tsx index 5c7dbca..d7f9ab0 100644 --- a/instance/src/web/src/pages/app/Navigation.tsx +++ b/instance/src/web/src/pages/app/Navigation.tsx @@ -1,108 +1,108 @@ -import UKNavigationRail from "@ewsgit/uikit-solid/src/components/navigationRail/UKNavigationRail.jsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import useIsMobile from "@ewsgit/uikit-solid/src/core/useIsMobile.js"; -import { useLocation, useNavigate } from "@solidjs/router"; -import { type Component, createMemo, createResource, createSignal, type ParentProps, Show } from "solid-js"; -import trpc from "../../lib/trpc"; -import NavigationRailApplications from "./components/NavigationRail/components/navigationRailApplications/NavigationRailApplications"; -import NavigationRailAvatar from "./components/NavigationRail/components/navigationRailAvatar/NavigationRailAvatar"; -import NavigationRailClock from "./components/NavigationRail/components/navigationRailClock/NavigationRailClock"; -import NavigationRailNotifications from "./components/NavigationRail/components/navigationRailNotifications/NavigationRailNotifications"; -import styles from "./Navigation.module.scss"; - -const AppNavigation: Component = (props) => { - const location = useLocation(); - const navigate = useNavigate(); - const isMobile = useIsMobile(); - - const [quickShortcuts] = createResource(() => trpc.app.navigation.getQuickShortcuts.query(), { initialValue: [] }); - const [expanded, setExpanded] = createSignal(false); - const [toggledDrawer, setToggledDrawer] = createSignal<"applications" | "notifications" | false>(false); - - const memoedNavigationItems = createMemo(() => { - return quickShortcuts() - .map((sc) => { - return { - icon: sc.icon || { - type: "icon", - value: "indeterminate_question_box", - }, - label: sc.label, - active: location.pathname.startsWith(sc.location.value), - onClick() { - if (sc.location.type === "local") { - navigate(sc.location.value); - } else if (sc.location.type === "remote") { - window.location.href = sc.location.value; - } - }, - onMiddleClick() { - if (sc.location.type === "local") { - window.open(sc.location.value, "_blank"); - } else if (sc.location.type === "remote") { - window.open(sc.location.value, "_blank"); - } - }, - }; - }) - .slice(0, isMobile() ? 3 : undefined) - }) - - return ( - setExpanded(expandedState)} - anchorPoints={{ - topMost: ( - <> - - - - - ), - top: ( - <> - - - ), - bottom: ( - <> - { - if (toggledDrawer() === "applications") { - setToggledDrawer(false); - } else { - setToggledDrawer(str); - } - }} - expanded={expanded()} - /> - - - Dev Build - - - { - if (toggledDrawer() === "notifications") { - setToggledDrawer(false); - } else { - setToggledDrawer(drawerState); - } - }} - expanded={expanded()} - /> - - ), - }} - > -
{props.children}
-
- ); -}; - -export default AppNavigation; +import UKNavigationRail from "@ewsgit/uikit-solid/src/components/navigationRail/UKNavigationRail.jsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import useIsMobile from "@ewsgit/uikit-solid/src/core/useIsMobile.js"; +import { useLocation, useNavigate } from "@solidjs/router"; +import { type Component, createMemo, createResource, createSignal, type ParentProps, Show } from "solid-js"; +import trpc from "../../lib/trpc"; +import NavigationRailApplications from "./components/NavigationRail/components/navigationRailApplications/NavigationRailApplications"; +import NavigationRailAvatar from "./components/NavigationRail/components/navigationRailAvatar/NavigationRailAvatar"; +import NavigationRailClock from "./components/NavigationRail/components/navigationRailClock/NavigationRailClock"; +import NavigationRailNotifications from "./components/NavigationRail/components/navigationRailNotifications/NavigationRailNotifications"; +import styles from "./Navigation.module.scss"; + +const AppNavigation: Component = (props) => { + const location = useLocation(); + const navigate = useNavigate(); + const isMobile = useIsMobile(); + + const [quickShortcuts] = createResource(() => trpc.app.navigation.getQuickShortcuts.query(), { initialValue: [] }); + const [expanded, setExpanded] = createSignal(false); + const [toggledDrawer, setToggledDrawer] = createSignal<"applications" | "notifications" | false>(false); + + const memoedNavigationItems = createMemo(() => { + return quickShortcuts() + .map((sc) => { + return { + icon: sc.icon || { + type: "icon", + value: "indeterminate_question_box", + }, + label: sc.label, + active: location.pathname.startsWith(sc.location.value), + onClick() { + if (sc.location.type === "local") { + navigate(sc.location.value); + } else if (sc.location.type === "remote") { + window.location.href = sc.location.value; + } + }, + onMiddleClick() { + if (sc.location.type === "local") { + window.open(sc.location.value, "_blank"); + } else if (sc.location.type === "remote") { + window.open(sc.location.value, "_blank"); + } + }, + }; + }) + .slice(0, isMobile() ? 3 : undefined) + }) + + return ( + setExpanded(expandedState)} + anchorPoints={{ + topMost: ( + <> + + + + + ), + top: ( + <> + + + ), + bottom: ( + <> + { + if (toggledDrawer() === "applications") { + setToggledDrawer(false); + } else { + setToggledDrawer(str); + } + }} + expanded={expanded()} + /> + + + Dev Build + + + { + if (toggledDrawer() === "notifications") { + setToggledDrawer(false); + } else { + setToggledDrawer(drawerState); + } + }} + expanded={expanded()} + /> + + ), + }} + > +
{props.children}
+
+ ); +}; + +export default AppNavigation; diff --git a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailApplications/NavigationRailApplications.module.scss b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailApplications/NavigationRailApplications.module.scss index 54cc8ba..54b9b7f 100644 --- a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailApplications/NavigationRailApplications.module.scss +++ b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailApplications/NavigationRailApplications.module.scss @@ -1,101 +1,101 @@ -.root { - position: relative; - display: flex; - padding-bottom: 1rem; - justify-content: center; - align-items: center; - width: 100%; - margin-top: auto; - - &[data-expanded="true"] { - > .drawer { - left: 22.5rem; - } - } - - &[data-expanded="false"] { - > .drawer { - left: 6rem; - } - } - - *[data-navigation-rail-mobile-mode="true"] > div > & { - justify-content: unset; - width: unset; - padding-bottom: unset; - margin-top: unset; - - > .drawer { - position: fixed; - width: calc(100vw - 2rem); - left: 1rem; - bottom: 5.5rem; - border-bottom-left-radius: var(--uk-sys-shape-corner-medium); - border-bottom-right-radius: var(--uk-sys-shape-corner-medium); - - animation: fadeInBottom var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); - - @keyframes fadeInBottom { - from { - opacity: 0; - transform: translateY(-1rem); - } - to { - opacity: 1; - transform: translateY(0); - } - } - } - } -} - -.drawer { - position: absolute; - display: flex; - flex-direction: column; - gap: 0.5rem; - padding: 1rem; - bottom: 1rem; - z-index: 10; - background-color: rgb(var(--uk-sys-color-surface-container)); - border: 1px solid rgb(var(--uk-sys-color-outline-variant)); - border-radius: calc(var(--uk-sys-shape-corner-medium) + 1rem); - border-bottom-left-radius: var(--uk-sys-shape-corner-medium); - transition: left var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); - width: 24rem; - - animation: fadeInLeft var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); - - @keyframes fadeInLeft { - from { - opacity: 0; - transform: translateX(-1rem); - } - to { - opacity: 1; - transform: translateX(0); - } - } -} - -.appsGrid { - display: grid; - gap: 0.5rem; - grid-template-columns: 1fr 1fr 1fr; - grid-auto-rows: 1fr; - - .application { - display: flex; - flex-direction: column; - gap: 0.5rem; - justify-content: center; - align-items: center; - text-wrap: wrap; - overflow: hidden; - - .applicationImageIcon { - width: 24px; - height: 24px; - } - } -} +.root { + position: relative; + display: flex; + padding-bottom: 1rem; + justify-content: center; + align-items: center; + width: 100%; + margin-top: auto; + + &[data-expanded="true"] { + > .drawer { + left: 22.5rem; + } + } + + &[data-expanded="false"] { + > .drawer { + left: 6rem; + } + } + + *[data-navigation-rail-mobile-mode="true"] > div > & { + justify-content: unset; + width: unset; + padding-bottom: unset; + margin-top: unset; + + > .drawer { + position: fixed; + width: calc(100vw - 2rem); + left: 1rem; + bottom: 5.5rem; + border-bottom-left-radius: var(--uk-sys-shape-corner-medium); + border-bottom-right-radius: var(--uk-sys-shape-corner-medium); + + animation: fadeInBottom var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); + + @keyframes fadeInBottom { + from { + opacity: 0; + transform: translateY(-1rem); + } + to { + opacity: 1; + transform: translateY(0); + } + } + } + } +} + +.drawer { + position: absolute; + display: flex; + flex-direction: column; + gap: 0.5rem; + padding: 1rem; + bottom: 1rem; + z-index: 10; + background-color: rgb(var(--uk-sys-color-surface-container)); + border: 1px solid rgb(var(--uk-sys-color-outline-variant)); + border-radius: calc(var(--uk-sys-shape-corner-medium) + 1rem); + border-bottom-left-radius: var(--uk-sys-shape-corner-medium); + transition: left var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); + width: 24rem; + + animation: fadeInLeft var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); + + @keyframes fadeInLeft { + from { + opacity: 0; + transform: translateX(-1rem); + } + to { + opacity: 1; + transform: translateX(0); + } + } +} + +.appsGrid { + display: grid; + gap: 0.5rem; + grid-template-columns: 1fr 1fr 1fr; + grid-auto-rows: 1fr; + + .application { + display: flex; + flex-direction: column; + gap: 0.5rem; + justify-content: center; + align-items: center; + text-wrap: wrap; + overflow: hidden; + + .applicationImageIcon { + width: 24px; + height: 24px; + } + } +} diff --git a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailApplications/NavigationRailApplications.tsx b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailApplications/NavigationRailApplications.tsx index 4575c7f..730a428 100644 --- a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailApplications/NavigationRailApplications.tsx +++ b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailApplications/NavigationRailApplications.tsx @@ -1,75 +1,75 @@ -import APPS_ICON from "@material-symbols/svg-700/outlined/apps.svg"; -import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.js"; -import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; -import UKIconButton from "@ewsgit/uikit-solid/src/components/iconButton/UKIconButton.jsx"; -import UKList from "@ewsgit/uikit-solid/src/components/list/UKList.jsx"; -import UKListItem from "@ewsgit/uikit-solid/src/components/list/UKListItem.jsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import { useNavigate } from "@solidjs/router"; -import { type Component, createResource, For, Show } from "solid-js"; -import trpc from "../../../../../../lib/trpc"; -import styles from "./NavigationRailApplications.module.scss"; -import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; -import UKIcon from "@ewsgit/uikit-solid/src/components/icon/UKIcon.jsx"; - -const NavigationRailApplications: Component<{ - expanded: boolean; - toggle: (text: "applications") => void; - isToggled: boolean; -}> = (props) => { - const navigate = useNavigate(); - const [applications] = createResource(() => trpc.app.navigation.getApplications.query()); - - return ( -
- { - props.toggle("applications"); - }} - /> - {props.isToggled && ( -
- - Applications - - -
- - {(app) => { - return ( - { - if (app.location.type === "local") { - navigate(app.location.value); - props.toggle("applications"); - } else if (app.location.type === "remote") { - window.location.href = app.location.value; - } - }} - > - - {app.icon.value} - - - - - - {app.label} - - - ); - }} - -
-
- )} -
- ); -}; - -export default NavigationRailApplications; +import APPS_ICON from "@material-symbols/svg-700/outlined/apps.svg"; +import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.js"; +import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; +import UKIconButton from "@ewsgit/uikit-solid/src/components/iconButton/UKIconButton.jsx"; +import UKList from "@ewsgit/uikit-solid/src/components/list/UKList.jsx"; +import UKListItem from "@ewsgit/uikit-solid/src/components/list/UKListItem.jsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import { useNavigate } from "@solidjs/router"; +import { type Component, createResource, For, Show } from "solid-js"; +import trpc from "../../../../../../lib/trpc"; +import styles from "./NavigationRailApplications.module.scss"; +import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; +import UKIcon from "@ewsgit/uikit-solid/src/components/icon/UKIcon.jsx"; + +const NavigationRailApplications: Component<{ + expanded: boolean; + toggle: (text: "applications") => void; + isToggled: boolean; +}> = (props) => { + const navigate = useNavigate(); + const [applications] = createResource(() => trpc.app.navigation.getApplications.query()); + + return ( +
+ { + props.toggle("applications"); + }} + /> + {props.isToggled && ( +
+ + Applications + + +
+ + {(app) => { + return ( + { + if (app.location.type === "local") { + navigate(app.location.value); + props.toggle("applications"); + } else if (app.location.type === "remote") { + window.location.href = app.location.value; + } + }} + > + + {app.icon.value} + + + + + + {app.label} + + + ); + }} + +
+
+ )} +
+ ); +}; + +export default NavigationRailApplications; diff --git a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailAvatar/NavigationRailAvatar.module.scss b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailAvatar/NavigationRailAvatar.module.scss index 06d8fb5..d0f6356 100644 --- a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailAvatar/NavigationRailAvatar.module.scss +++ b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailAvatar/NavigationRailAvatar.module.scss @@ -1,119 +1,119 @@ -.root { - margin-top: 2.75rem; - display: flex; - flex-direction: row; - align-items: center; - gap: 1rem; - background: #0000; - padding: 1rem; - border-radius: 10rem; - position: relative; - - transition: - background-color var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate), - color var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); - - .avatarContainer { - outline-style: solid; - outline-offset: 2px; - outline-width: 0; - outline-color: transparent; - margin-bottom: 0; - - transition: - outline-color var(--uk-sys-motion-duration-100) var(--uk-sys-motion-easing-standard-decelerate), - outline-width var(--uk-sys-motion-duration-50) linear, - margin-bottom var(--uk-sys-motion-duration-500) var(--uk-sys-motion-easing-emphasized-decelerate); - - &:hover { - outline-width: var(--uk-sys-state-focus-indicator-thickness); - outline-offset: var(--uk-sys-state-focus-indicator-outer-offset); - outline-color: rgb(var(--uk-sys-color-secondary)); - } - } - - .nameContainer { - width: 100%; - overflow: hidden; - display: flex; - flex-direction: column; - white-space: nowrap; - } - - .displayName { - line-height: 1rem !important; - } - - &[data-expanded="true"] { - color: rgb(var(--uk-sys-color-secondary)); - background-color: rgb(var(--uk-sys-color-secondary-container)); - - > .logout { - visibility: visible; - pointer-events: all; - opacity: 1; - transition: opacity var(--uk-sys-motion-duration-1000) var(--uk-sys-motion-easing-emphasized-decelerate); - } - } - - .logout { - display: flex; - pointer-events: none; - position: absolute; - bottom: 0.75rem; - right: 0.75rem; - opacity: 0; - visibility: hidden; - } - - &[data-expanded="false"]:hover { - flex-direction: column; - color: rgb(var(--uk-sys-color-secondary)); - background-color: rgb(var(--uk-sys-color-secondary-container)); - - .avatarContainer { - margin-bottom: 3rem; - outline-width: var(--uk-sys-state-focus-indicator-thickness); - outline-offset: var(--uk-sys-state-focus-indicator-outer-offset); - outline-color: rgb(var(--uk-sys-color-secondary)); - } - - .logout { - visibility: visible; - pointer-events: all; - opacity: 1; - transition: - opacity var(--uk-sys-motion-duration-1000) var(--uk-sys-motion-easing-emphasized-decelerate), - border-radius var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); - } - - .nameContainer { - visibility: hidden; - display: none; - } - } - - *[data-navigation-rail-mobile-mode="true"] > div > & { - margin-top: auto; - margin-bottom: auto; - margin-right: 1rem; - padding: unset; - aspect-ratio: 1 / 1; - background: transparent; - - &:hover { - .avatarContainer { - margin-bottom: auto; - } - } - - .logout { - pointer-events: none; - position: absolute; - bottom: 0.75rem; - right: 0.75rem; - opacity: 0; - visibility: hidden; - } - } -} +.root { + margin-top: 2.75rem; + display: flex; + flex-direction: row; + align-items: center; + gap: 1rem; + background: #0000; + padding: 1rem; + border-radius: 10rem; + position: relative; + + transition: + background-color var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate), + color var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); + + .avatarContainer { + outline-style: solid; + outline-offset: 2px; + outline-width: 0; + outline-color: transparent; + margin-bottom: 0; + + transition: + outline-color var(--uk-sys-motion-duration-100) var(--uk-sys-motion-easing-standard-decelerate), + outline-width var(--uk-sys-motion-duration-50) linear, + margin-bottom var(--uk-sys-motion-duration-500) var(--uk-sys-motion-easing-emphasized-decelerate); + + &:hover { + outline-width: var(--uk-sys-state-focus-indicator-thickness); + outline-offset: var(--uk-sys-state-focus-indicator-outer-offset); + outline-color: rgb(var(--uk-sys-color-secondary)); + } + } + + .nameContainer { + width: 100%; + overflow: hidden; + display: flex; + flex-direction: column; + white-space: nowrap; + } + + .displayName { + line-height: 1rem !important; + } + + &[data-expanded="true"] { + color: rgb(var(--uk-sys-color-secondary)); + background-color: rgb(var(--uk-sys-color-secondary-container)); + + > .logout { + visibility: visible; + pointer-events: all; + opacity: 1; + transition: opacity var(--uk-sys-motion-duration-1000) var(--uk-sys-motion-easing-emphasized-decelerate); + } + } + + .logout { + display: flex; + pointer-events: none; + position: absolute; + bottom: 0.75rem; + right: 0.75rem; + opacity: 0; + visibility: hidden; + } + + &[data-expanded="false"]:hover { + flex-direction: column; + color: rgb(var(--uk-sys-color-secondary)); + background-color: rgb(var(--uk-sys-color-secondary-container)); + + .avatarContainer { + margin-bottom: 3rem; + outline-width: var(--uk-sys-state-focus-indicator-thickness); + outline-offset: var(--uk-sys-state-focus-indicator-outer-offset); + outline-color: rgb(var(--uk-sys-color-secondary)); + } + + .logout { + visibility: visible; + pointer-events: all; + opacity: 1; + transition: + opacity var(--uk-sys-motion-duration-1000) var(--uk-sys-motion-easing-emphasized-decelerate), + border-radius var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); + } + + .nameContainer { + visibility: hidden; + display: none; + } + } + + *[data-navigation-rail-mobile-mode="true"] > div > & { + margin-top: auto; + margin-bottom: auto; + margin-right: 1rem; + padding: unset; + aspect-ratio: 1 / 1; + background: transparent; + + &:hover { + .avatarContainer { + margin-bottom: auto; + } + } + + .logout { + pointer-events: none; + position: absolute; + bottom: 0.75rem; + right: 0.75rem; + opacity: 0; + visibility: hidden; + } + } +} diff --git a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailAvatar/NavigationRailAvatar.tsx b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailAvatar/NavigationRailAvatar.tsx index baf58bc..9381490 100644 --- a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailAvatar/NavigationRailAvatar.tsx +++ b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailAvatar/NavigationRailAvatar.tsx @@ -1,56 +1,56 @@ -import LOGOUT_ICON from "@material-symbols/svg-700/outlined/logout.svg"; -import UKAvatar from "@ewsgit/uikit-solid/src/components/avatar/UKAvatar.jsx"; -import UKIconButton from "@ewsgit/uikit-solid/src/components/iconButton/UKIconButton.tsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import useIsMobile from "@ewsgit/uikit-solid/src/core/useIsMobile.ts"; -import { useNavigate } from "@solidjs/router"; -import { type Component, createResource, Show } from "solid-js"; -import backend from "../../../../../../lib/backend"; -import trpc from "../../../../../../lib/trpc"; -import styles from "./NavigationRailAvatar.module.scss"; - -const NavigationRailAvatar: Component<{ expanded: boolean }> = (props) => { - const navigate = useNavigate(); - const isMobile = useIsMobile(); - const [user] = createResource(() => trpc.app.navigation.user.name.query()); - - return ( -
- { - navigate("/app/uk.ewsgit.settings/"); - }} - containerClass={styles.avatarContainer} - avatar={backend("/api/user/me/avatar/s")} - size="s" - username="me" - /> - -
- - {`${user()?.forename} ${user()?.surname}`} - - - {`@${user()?.username}`} - -
- { - await trpc.authorization.logout.mutate(); - - navigate("/"); - }} - /> -
-
- ); -}; - -export default NavigationRailAvatar; +import LOGOUT_ICON from "@material-symbols/svg-700/outlined/logout.svg"; +import UKAvatar from "@ewsgit/uikit-solid/src/components/avatar/UKAvatar.jsx"; +import UKIconButton from "@ewsgit/uikit-solid/src/components/iconButton/UKIconButton.tsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import useIsMobile from "@ewsgit/uikit-solid/src/core/useIsMobile.ts"; +import { useNavigate } from "@solidjs/router"; +import { type Component, createResource, Show } from "solid-js"; +import backend from "../../../../../../lib/backend"; +import trpc from "../../../../../../lib/trpc"; +import styles from "./NavigationRailAvatar.module.scss"; + +const NavigationRailAvatar: Component<{ expanded: boolean }> = (props) => { + const navigate = useNavigate(); + const isMobile = useIsMobile(); + const [user] = createResource(() => trpc.app.navigation.user.name.query()); + + return ( +
+ { + navigate("/app/uk.ewsgit.settings/"); + }} + containerClass={styles.avatarContainer} + avatar={backend("/api/user/me/avatar/s")} + size="s" + username="me" + /> + +
+ + {`${user()?.forename} ${user()?.surname}`} + + + {`@${user()?.username}`} + +
+ { + await trpc.authorization.logout.mutate(); + + navigate("/"); + }} + /> +
+
+ ); +}; + +export default NavigationRailAvatar; diff --git a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailClock/NavigationRailClock.module.scss b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailClock/NavigationRailClock.module.scss index daba961..3c6be38 100644 --- a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailClock/NavigationRailClock.module.scss +++ b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailClock/NavigationRailClock.module.scss @@ -1,40 +1,40 @@ -.root { - margin-top: 1rem; - margin-bottom: -1rem; - display: flex; - flex-direction: row; - justify-content: center; - align-items: center; - gap: 0; - border-radius: 10rem; - - transition: gap var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate), width var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); - - &[data-expanded="true"] { - width: 20.5rem; - gap: 1rem; - } - - &[data-expanded="false"] { - width: 4rem; - - .expanded { - opacity: 0; - width: 0; - transition: width var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); - } - } -} - -.content { - overflow: hidden; - height: var(--uk-sys-typescale-body-medium-line-height); -} - -.collapsed { - -} - -.expanded { - transition: width var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate), opacity var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); -} +.root { + margin-top: 1rem; + margin-bottom: -1rem; + display: flex; + flex-direction: row; + justify-content: center; + align-items: center; + gap: 0; + border-radius: 10rem; + + transition: gap var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate), width var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); + + &[data-expanded="true"] { + width: 20.5rem; + gap: 1rem; + } + + &[data-expanded="false"] { + width: 4rem; + + .expanded { + opacity: 0; + width: 0; + transition: width var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); + } + } +} + +.content { + overflow: hidden; + height: var(--uk-sys-typescale-body-medium-line-height); +} + +.collapsed { + +} + +.expanded { + transition: width var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate), opacity var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); +} diff --git a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailClock/NavigationRailClock.tsx b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailClock/NavigationRailClock.tsx index 234a353..f241aef 100644 --- a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailClock/NavigationRailClock.tsx +++ b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailClock/NavigationRailClock.tsx @@ -1,50 +1,50 @@ -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.tsx"; -import clsx from "clsx"; -import { type Component, createSignal, onCleanup } from "solid-js"; -import styles from "./NavigationRailClock.module.scss"; - -function padWith0(num: number) { - return num.toString().padStart(2, "0"); -} - -const NavigationRailClock: Component<{ expanded: boolean }> = (props) => { - const [currentDate, setCurrentDate] = createSignal(new Date()); - - const timer = setInterval(() => setCurrentDate(new Date()), 10_000); - onCleanup(() => clearInterval(timer)); - - /* Add "st/nd/rd/th" suffix to a string */ - function addOrdinalSuffixToDay(day: number) { - const j = day % 10; - const k = day % 100; - - if (j === 1 && k !== 11) return "st"; - if (j === 2 && k !== 12) return "nd"; - if (j === 3 && k !== 13) return "rd"; - - return "th"; - } - - const time = () => `${padWith0(currentDate().getHours())}:${padWith0(currentDate().getMinutes())}`; - const date = () => { - const d = currentDate(); - const weekday = d.toLocaleDateString(undefined, { weekday: "long" }); - const day = d.getDate(); - const month = d.toLocaleDateString(undefined, { month: "long" }); - const year = d.getFullYear(); - return `${weekday} ${day}${addOrdinalSuffixToDay(day)} ${month} ${year}`; - }; - - return ( -
- - {time()} - - - {date()} - -
- ); -}; - -export default NavigationRailClock; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.tsx"; +import clsx from "clsx"; +import { type Component, createSignal, onCleanup } from "solid-js"; +import styles from "./NavigationRailClock.module.scss"; + +function padWith0(num: number) { + return num.toString().padStart(2, "0"); +} + +const NavigationRailClock: Component<{ expanded: boolean }> = (props) => { + const [currentDate, setCurrentDate] = createSignal(new Date()); + + const timer = setInterval(() => setCurrentDate(new Date()), 10_000); + onCleanup(() => clearInterval(timer)); + + /* Add "st/nd/rd/th" suffix to a string */ + function addOrdinalSuffixToDay(day: number) { + const j = day % 10; + const k = day % 100; + + if (j === 1 && k !== 11) return "st"; + if (j === 2 && k !== 12) return "nd"; + if (j === 3 && k !== 13) return "rd"; + + return "th"; + } + + const time = () => `${padWith0(currentDate().getHours())}:${padWith0(currentDate().getMinutes())}`; + const date = () => { + const d = currentDate(); + const weekday = d.toLocaleDateString(undefined, { weekday: "long" }); + const day = d.getDate(); + const month = d.toLocaleDateString(undefined, { month: "long" }); + const year = d.getFullYear(); + return `${weekday} ${day}${addOrdinalSuffixToDay(day)} ${month} ${year}`; + }; + + return ( +
+ + {time()} + + + {date()} + +
+ ); +}; + +export default NavigationRailClock; diff --git a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/NavigationRailNotifications.module.scss b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/NavigationRailNotifications.module.scss index 3ab94ab..5bd4513 100644 --- a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/NavigationRailNotifications.module.scss +++ b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/NavigationRailNotifications.module.scss @@ -1,117 +1,117 @@ -.root { - position: relative; - display: flex; - padding-bottom: 1rem; - justify-content: center; - align-items: center; - width: 100%; - - &[data-expanded="true"] { - > .notifications, - > .flyoutNotifications { - left: 22.5rem; - } - } - - &[data-expanded="false"] { - > .notifications, - > .flyoutNotifications { - left: 6rem; - } - } - - *[data-navigation-rail-mobile-mode="true"] > div > & { - justify-content: unset; - width: unset; - padding-bottom: unset; - - > .notifications, - > .flyoutNotifications { - position: fixed; - left: 1rem; - bottom: 5.5rem; - height: unset; - width: calc(100vw - 2rem); - - animation: fadeInBottom var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); - transition: bottom var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); - - @keyframes fadeInBottom { - from { - opacity: 0; - transform: translateY(1rem); - } - to { - opacity: 1; - transform: translateY(0); - } - } - } - } -} - -.notifications { - position: absolute; - display: flex; - flex-direction: column; - gap: 0.5rem; - bottom: 1rem; - padding: 1rem; - z-index: 10; - height: calc(100vh - 2rem); - width: calc(20rem + 2rem); - - background-color: rgb(var(--uk-sys-color-surface-container)); - border: 1px solid rgb(var(--uk-sys-color-outline-variant)); - border-radius: calc(var(--uk-sys-shape-corner-medium) + 1rem); - - transition: left var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); - - animation: fadeInLeft var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); - - @keyframes fadeInLeft { - from { - opacity: 0; - transform: translateX(-1rem); - } - to { - opacity: 1; - transform: translateX(0); - } - } -} - -.flyoutNotifications { - position: absolute; - display: flex; - flex-direction: column; - gap: 0.5rem; - bottom: 1rem; - z-index: 10; - - transition: left var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); - - > * { - animation: fadeIn var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); - - @keyframes fadeIn { - from { - opacity: 0; - transform: translateX(-1rem); - } - to { - opacity: 1; - transform: translateX(0); - } - } - } -} - -.noNotificationsMessage { - display: flex; - flex-direction: column; - gap: 0.5rem; - margin: auto; - align-items: center; - justify-content: center; -} +.root { + position: relative; + display: flex; + padding-bottom: 1rem; + justify-content: center; + align-items: center; + width: 100%; + + &[data-expanded="true"] { + > .notifications, + > .flyoutNotifications { + left: 22.5rem; + } + } + + &[data-expanded="false"] { + > .notifications, + > .flyoutNotifications { + left: 6rem; + } + } + + *[data-navigation-rail-mobile-mode="true"] > div > & { + justify-content: unset; + width: unset; + padding-bottom: unset; + + > .notifications, + > .flyoutNotifications { + position: fixed; + left: 1rem; + bottom: 5.5rem; + height: unset; + width: calc(100vw - 2rem); + + animation: fadeInBottom var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); + transition: bottom var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); + + @keyframes fadeInBottom { + from { + opacity: 0; + transform: translateY(1rem); + } + to { + opacity: 1; + transform: translateY(0); + } + } + } + } +} + +.notifications { + position: absolute; + display: flex; + flex-direction: column; + gap: 0.5rem; + bottom: 1rem; + padding: 1rem; + z-index: 10; + height: calc(100vh - 2rem); + width: calc(20rem + 2rem); + + background-color: rgb(var(--uk-sys-color-surface-container)); + border: 1px solid rgb(var(--uk-sys-color-outline-variant)); + border-radius: calc(var(--uk-sys-shape-corner-medium) + 1rem); + + transition: left var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); + + animation: fadeInLeft var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); + + @keyframes fadeInLeft { + from { + opacity: 0; + transform: translateX(-1rem); + } + to { + opacity: 1; + transform: translateX(0); + } + } +} + +.flyoutNotifications { + position: absolute; + display: flex; + flex-direction: column; + gap: 0.5rem; + bottom: 1rem; + z-index: 10; + + transition: left var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); + + > * { + animation: fadeIn var(--uk-sys-motion-duration-250) var(--uk-sys-motion-easing-emphasized-decelerate); + + @keyframes fadeIn { + from { + opacity: 0; + transform: translateX(-1rem); + } + to { + opacity: 1; + transform: translateX(0); + } + } + } +} + +.noNotificationsMessage { + display: flex; + flex-direction: column; + gap: 0.5rem; + margin: auto; + align-items: center; + justify-content: center; +} diff --git a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/NavigationRailNotifications.tsx b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/NavigationRailNotifications.tsx index 450f5c8..4c44c03 100644 --- a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/NavigationRailNotifications.tsx +++ b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/NavigationRailNotifications.tsx @@ -1,143 +1,143 @@ -import NOTIFICATIONS_ICON from "@material-symbols/svg-700/outlined/notifications.svg"; -import NOTIFICATIONS_UNREAD_ICON from "@material-symbols/svg-700/outlined/notifications_unread.svg"; -import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.js"; -import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; -import UKIconButton from "@ewsgit/uikit-solid/src/components/iconButton/UKIconButton.jsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import { useNavigate } from "@solidjs/router"; -import { type Component, createSignal, For } from "solid-js"; -import type { WorkspacesNotification } from "../../../../../../../../systems/notifications"; -import trpc from "../../../../../../lib/trpc"; -import styles from "./NavigationRailNotifications.module.scss"; -import Notification from "./notification/Notification"; - -// const FLYOUT_NOTIFICATION_TIMEOUT = 10_000; - -const NavigationRailNotifications: Component<{ - expanded: boolean; - toggle: (text: "notifications") => void; - isToggled: boolean; -}> = (props) => { - const navigate = useNavigate(); - const [notifications, setNotifications] = createSignal([]); - const [flyoutNotifications, setFlyoutNotifications] = createSignal([]); - // let subscription: Unsubscribable; - // - // onMount(() => { - // subscription = trpc.app.notifications.listener.subscribe(undefined, { - // onData(data) { - // // @ts-ignore - // setFlyoutNotifications((not) => { - // return [...not, data]; - // }); - // - // // @ts-ignore - // setNotifications((not) => { - // return [...not, data]; - // }); - // - // // if not urgent, remove after FLYOUT_NOTIFICATION_TIMEOUT - // if (data.priority !== 2) { - // setTimeout(() => { - // setFlyoutNotifications((not) => not.filter((n) => n.uuid !== data.uuid)); - // }, FLYOUT_NOTIFICATION_TIMEOUT); - // } - // }, - // }); - // }); - // - // onCleanup(() => { - // subscription.unsubscribe(); - // }); - - return ( -
- { - props.toggle("notifications"); - }} - /> -
- - {(notification) => ( - { - if (type === "close") { - setFlyoutNotifications((notifications) => notifications.filter((n) => n.uuid !== notification.uuid)); - setNotifications((notifications) => notifications.filter((n) => n.uuid !== notification.uuid)); - - return; - } - - const responseAction = await trpc.app.notifications.respond.mutate({ - uuid: notification.uuid, - responseType: type, - value: value, - }); - - if (responseAction.action?.type === "navigate") { - navigate(responseAction.action.value); - } - - if (responseAction.action?.type === "reload") { - window.location.reload(); - } - - setFlyoutNotifications((notifications) => notifications.filter((n) => n.uuid !== notification.uuid)); - setNotifications((notifications) => notifications.filter((n) => n.uuid !== notification.uuid)); - }} - notification={notification} - /> - )} - -
- {props.isToggled && ( -
- {notifications().length > 0 ? ( - - {(notification) => ( - { - const responseAction = await trpc.app.notifications.respond.mutate({ - uuid: notification.uuid, - responseType: type as "button", - value: value, - }); - - if (responseAction.action?.type === "navigate") { - navigate(responseAction.action.value); - } - - if (responseAction.action?.type === "reload") { - window.location.reload(); - } - - setNotifications((notifications) => notifications.filter((n) => n.uuid !== notification.uuid)); - setFlyoutNotifications((notifications) => notifications.filter((n) => n.uuid !== notification.uuid)); - }} - notification={notification} - /> - )} - - ) : ( -
- - Nothing here - - - - You have no notifications, when you have a notification it will show up here. - -
- )} -
- )} -
- ); -}; - -export default NavigationRailNotifications; +import NOTIFICATIONS_ICON from "@material-symbols/svg-700/outlined/notifications.svg"; +import NOTIFICATIONS_UNREAD_ICON from "@material-symbols/svg-700/outlined/notifications_unread.svg"; +import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.js"; +import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; +import UKIconButton from "@ewsgit/uikit-solid/src/components/iconButton/UKIconButton.jsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import { useNavigate } from "@solidjs/router"; +import { type Component, createSignal, For } from "solid-js"; +import type { WorkspacesNotification } from "../../../../../../../../systems/notifications"; +import trpc from "../../../../../../lib/trpc"; +import styles from "./NavigationRailNotifications.module.scss"; +import Notification from "./notification/Notification"; + +// const FLYOUT_NOTIFICATION_TIMEOUT = 10_000; + +const NavigationRailNotifications: Component<{ + expanded: boolean; + toggle: (text: "notifications") => void; + isToggled: boolean; +}> = (props) => { + const navigate = useNavigate(); + const [notifications, setNotifications] = createSignal([]); + const [flyoutNotifications, setFlyoutNotifications] = createSignal([]); + // let subscription: Unsubscribable; + // + // onMount(() => { + // subscription = trpc.app.notifications.listener.subscribe(undefined, { + // onData(data) { + // // @ts-ignore + // setFlyoutNotifications((not) => { + // return [...not, data]; + // }); + // + // // @ts-ignore + // setNotifications((not) => { + // return [...not, data]; + // }); + // + // // if not urgent, remove after FLYOUT_NOTIFICATION_TIMEOUT + // if (data.priority !== 2) { + // setTimeout(() => { + // setFlyoutNotifications((not) => not.filter((n) => n.uuid !== data.uuid)); + // }, FLYOUT_NOTIFICATION_TIMEOUT); + // } + // }, + // }); + // }); + // + // onCleanup(() => { + // subscription.unsubscribe(); + // }); + + return ( +
+ { + props.toggle("notifications"); + }} + /> +
+ + {(notification) => ( + { + if (type === "close") { + setFlyoutNotifications((notifications) => notifications.filter((n) => n.uuid !== notification.uuid)); + setNotifications((notifications) => notifications.filter((n) => n.uuid !== notification.uuid)); + + return; + } + + const responseAction = await trpc.app.notifications.respond.mutate({ + uuid: notification.uuid, + responseType: type, + value: value, + }); + + if (responseAction.action?.type === "navigate") { + navigate(responseAction.action.value); + } + + if (responseAction.action?.type === "reload") { + window.location.reload(); + } + + setFlyoutNotifications((notifications) => notifications.filter((n) => n.uuid !== notification.uuid)); + setNotifications((notifications) => notifications.filter((n) => n.uuid !== notification.uuid)); + }} + notification={notification} + /> + )} + +
+ {props.isToggled && ( +
+ {notifications().length > 0 ? ( + + {(notification) => ( + { + const responseAction = await trpc.app.notifications.respond.mutate({ + uuid: notification.uuid, + responseType: type as "button", + value: value, + }); + + if (responseAction.action?.type === "navigate") { + navigate(responseAction.action.value); + } + + if (responseAction.action?.type === "reload") { + window.location.reload(); + } + + setNotifications((notifications) => notifications.filter((n) => n.uuid !== notification.uuid)); + setFlyoutNotifications((notifications) => notifications.filter((n) => n.uuid !== notification.uuid)); + }} + notification={notification} + /> + )} + + ) : ( +
+ + Nothing here + + + + You have no notifications, when you have a notification it will show up here. + +
+ )} +
+ )} +
+ ); +}; + +export default NavigationRailNotifications; diff --git a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/notification/Notification.module.scss b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/notification/Notification.module.scss index 8c90de4..2259341 100644 --- a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/notification/Notification.module.scss +++ b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/notification/Notification.module.scss @@ -1,38 +1,38 @@ -.root { - display: flex; - flex-direction: column; - width: 20rem; - overflow: hidden; -} - -.progressBar { - width: calc(100% + 2rem); - height: 0.25rem; - background: rgb(var(--uk-sys-color-primary)); - margin-top: -1rem; - margin-left: -1rem; - margin-right: -1rem; - margin-bottom: 0.75rem; -} - -.header { - display: flex; - flex-direction: row; - gap: 0.5rem; - padding-bottom: 0.5rem; - color: rgb(var(--uk-sys-color-on-surface)); -} - -.body { - padding-top: 0.5rem; - color: rgb(var(--uk-sys-color-on-surface-variant)); -} - -.footer { - display: flex; - flex-direction: row; - justify-content: end; - align-items: center; - padding-top: 0.5rem; - gap: 0.5rem; -} +.root { + display: flex; + flex-direction: column; + width: 20rem; + overflow: hidden; +} + +.progressBar { + width: calc(100% + 2rem); + height: 0.25rem; + background: rgb(var(--uk-sys-color-primary)); + margin-top: -1rem; + margin-left: -1rem; + margin-right: -1rem; + margin-bottom: 0.75rem; +} + +.header { + display: flex; + flex-direction: row; + gap: 0.5rem; + padding-bottom: 0.5rem; + color: rgb(var(--uk-sys-color-on-surface)); +} + +.body { + padding-top: 0.5rem; + color: rgb(var(--uk-sys-color-on-surface-variant)); +} + +.footer { + display: flex; + flex-direction: row; + justify-content: end; + align-items: center; + padding-top: 0.5rem; + gap: 0.5rem; +} diff --git a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/notification/Notification.tsx b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/notification/Notification.tsx index 9840cc6..210d75c 100644 --- a/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/notification/Notification.tsx +++ b/instance/src/web/src/pages/app/components/NavigationRail/components/navigationRailNotifications/notification/Notification.tsx @@ -1,53 +1,53 @@ -import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; -import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; -import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.js"; -import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; -import UKIcon from "@ewsgit/uikit-solid/src/components/icon/UKIcon.jsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import { type Component, For } from "solid-js"; -import type { WorkspacesNotification } from "../../../../../../../../../systems/notifications"; -import styles from "./Notification.module.scss"; - -const Notification: Component<{ - notification: WorkspacesNotification; - respond: (type: "button" | "close", value: string) => void; -}> = (props) => { - return ( - { - if (!props.notification.options?.buttons || props.notification.options.buttons.length === 0) { - props.respond("close", ""); - } - }} - > -
-
- {props.notification.content.icon && {props.notification.content.icon}} - - {props.notification.content.title} - -
- - - {props.notification.content.body} - -
- - {(btn) => ( - { - props.respond("button", btn.id); - }} - > - {btn.label} - - )} - -
-
- ); -}; - -export default Notification; +import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; +import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; +import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.js"; +import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; +import UKIcon from "@ewsgit/uikit-solid/src/components/icon/UKIcon.jsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import { type Component, For } from "solid-js"; +import type { WorkspacesNotification } from "../../../../../../../../../systems/notifications"; +import styles from "./Notification.module.scss"; + +const Notification: Component<{ + notification: WorkspacesNotification; + respond: (type: "button" | "close", value: string) => void; +}> = (props) => { + return ( + { + if (!props.notification.options?.buttons || props.notification.options.buttons.length === 0) { + props.respond("close", ""); + } + }} + > +
+
+ {props.notification.content.icon && {props.notification.content.icon}} + + {props.notification.content.title} + +
+ + + {props.notification.content.body} + +
+ + {(btn) => ( + { + props.respond("button", btn.id); + }} + > + {btn.label} + + )} + +
+
+ ); +}; + +export default Notification; diff --git a/instance/src/web/src/pages/notFound/Index.tsx b/instance/src/web/src/pages/notFound/Index.tsx index 9fa4301..78fce15 100644 --- a/instance/src/web/src/pages/notFound/Index.tsx +++ b/instance/src/web/src/pages/notFound/Index.tsx @@ -1,15 +1,15 @@ -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import type { RouteSectionProps } from "@solidjs/router"; -import type { Component } from "solid-js"; - -const NotFoundPage: Component> = () => { - return ( -
- - 404 - Not Found - -
- ); -}; - -export default NotFoundPage; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import type { RouteSectionProps } from "@solidjs/router"; +import type { Component } from "solid-js"; + +const NotFoundPage: Component> = () => { + return ( +
+ + 404 - Not Found + +
+ ); +}; + +export default NotFoundPage; diff --git a/instance/src/web/src/pages/userSelect/Layout.module.scss b/instance/src/web/src/pages/userSelect/Layout.module.scss index 89c43e9..dc6a100 100644 --- a/instance/src/web/src/pages/userSelect/Layout.module.scss +++ b/instance/src/web/src/pages/userSelect/Layout.module.scss @@ -1,34 +1,34 @@ -.root { - display: flex; - align-items: center; - justify-content: center; - width: 100%; - min-height: 100%; - flex-direction: column; - position: relative; - gap: 2rem; -} - -.copyrightContainer { - position: absolute; - display: flex; - align-items: center; - justify-content: center; - flex-direction: column; - bottom: 1rem; -} - -.background { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - object-fit: cover; -} - -.banner { - z-index: 2; - max-height: 10rem; - max-width: calc(100% - 1rem); -} +.root { + display: flex; + align-items: center; + justify-content: center; + width: 100%; + min-height: 100%; + flex-direction: column; + position: relative; + gap: 2rem; +} + +.copyrightContainer { + position: absolute; + display: flex; + align-items: center; + justify-content: center; + flex-direction: column; + bottom: 1rem; +} + +.background { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + object-fit: cover; +} + +.banner { + z-index: 2; + max-height: 10rem; + max-width: calc(100% - 1rem); +} diff --git a/instance/src/web/src/pages/userSelect/Layout.tsx b/instance/src/web/src/pages/userSelect/Layout.tsx index 51687e7..ffbbdbf 100644 --- a/instance/src/web/src/pages/userSelect/Layout.tsx +++ b/instance/src/web/src/pages/userSelect/Layout.tsx @@ -1,27 +1,27 @@ -import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; -import UKCircularProgressIndicator from "@ewsgit/uikit-solid/src/components/circularProgressIndicator/UKCircularProgressIndicator.jsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import type { RouteSectionProps } from "@solidjs/router"; -import { type Component, Suspense } from "solid-js"; -import backend from "../../lib/backend"; -import styles from "./Layout.module.scss"; - -const UserSelectLayout: Component> = (props) => { - return ( -
- - - }>{props.children} - - - Online Workspace Alpha - - - Copyright 2025-2026 Ewsgit - - -
- ); -}; - -export default UserSelectLayout; +import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; +import UKCircularProgressIndicator from "@ewsgit/uikit-solid/src/components/circularProgressIndicator/UKCircularProgressIndicator.jsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import type { RouteSectionProps } from "@solidjs/router"; +import { type Component, Suspense } from "solid-js"; +import backend from "../../lib/backend"; +import styles from "./Layout.module.scss"; + +const UserSelectLayout: Component> = (props) => { + return ( +
+ + + }>{props.children} + + + Online Workspace Alpha + + + Copyright 2025-2026 Ewsgit + + +
+ ); +}; + +export default UserSelectLayout; diff --git a/instance/src/web/src/pages/userSelect/forgotPassword/ForgotPassword.module.scss b/instance/src/web/src/pages/userSelect/forgotPassword/ForgotPassword.module.scss index 009cb92..6673072 100644 --- a/instance/src/web/src/pages/userSelect/forgotPassword/ForgotPassword.module.scss +++ b/instance/src/web/src/pages/userSelect/forgotPassword/ForgotPassword.module.scss @@ -1,14 +1,14 @@ -.root { - z-index: 1; - display: flex; - flex-direction: column; - gap: 1rem; -} - -.actions { - display: flex; - flex-direction: row; - align-items: center; - justify-content: space-between; - gap: 1rem; -} +.root { + z-index: 1; + display: flex; + flex-direction: column; + gap: 1rem; +} + +.actions { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + gap: 1rem; +} diff --git a/instance/src/web/src/pages/userSelect/forgotPassword/ForgotPassword.tsx b/instance/src/web/src/pages/userSelect/forgotPassword/ForgotPassword.tsx index 3620129..aa0d357 100644 --- a/instance/src/web/src/pages/userSelect/forgotPassword/ForgotPassword.tsx +++ b/instance/src/web/src/pages/userSelect/forgotPassword/ForgotPassword.tsx @@ -1,38 +1,38 @@ -import CHEVRON_LEFT_ICON from "@material-symbols/svg-700/outlined/chevron_left.svg"; -import UKButton, { AffirmativeButtonState } from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; -import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; -import { useNavigate, useSearchParams } from "@solidjs/router"; -import type { Component } from "solid-js"; -import styles from "./ForgotPassword.module.scss"; - -const ForgotPassword: Component = () => { - const navigate = useNavigate(); - const [searchParams] = useSearchParams(); - - return ( -
- TODO: Forgot password page -
- { - navigate(`/?username=${searchParams.username?.toString() || ""}`); - }} - color="tonal" - leadingIcon={CHEVRON_LEFT_ICON} - > - Go back - - { - return { state: AffirmativeButtonState.Error }; - }} - > - Continue - -
-
- ); -}; - -export default ForgotPassword; +import CHEVRON_LEFT_ICON from "@material-symbols/svg-700/outlined/chevron_left.svg"; +import UKButton, { AffirmativeButtonState } from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; +import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; +import { useNavigate, useSearchParams } from "@solidjs/router"; +import type { Component } from "solid-js"; +import styles from "./ForgotPassword.module.scss"; + +const ForgotPassword: Component = () => { + const navigate = useNavigate(); + const [searchParams] = useSearchParams(); + + return ( +
+ TODO: Forgot password page +
+ { + navigate(`/?username=${searchParams.username?.toString() || ""}`); + }} + color="tonal" + leadingIcon={CHEVRON_LEFT_ICON} + > + Go back + + { + return { state: AffirmativeButtonState.Error }; + }} + > + Continue + +
+
+ ); +}; + +export default ForgotPassword; diff --git a/instance/src/web/src/pages/userSelect/login/Login.module.scss b/instance/src/web/src/pages/userSelect/login/Login.module.scss index 5d7a2d8..d8c1b03 100644 --- a/instance/src/web/src/pages/userSelect/login/Login.module.scss +++ b/instance/src/web/src/pages/userSelect/login/Login.module.scss @@ -1,34 +1,34 @@ -.modal { - gap: 1rem; - display: flex; - flex-direction: column; - width: max-content; - min-width: min(20rem, calc(100% - 2rem)); - - > .signupSegment { - display: flex; - flex-direction: column; - align-items: center; - gap: 0.5rem; - } - - > form { - gap: 1rem; - display: flex; - flex-direction: column; - width: 100%; - - > .loginButtons { - display: flex; - flex-direction: row; - align-items: center; - justify-content: end; - gap: 0.5rem; - } - } -} - -.alternateLoginMethod { - margin-left: auto; - margin-right: auto; -} +.modal { + gap: 1rem; + display: flex; + flex-direction: column; + width: max-content; + min-width: min(20rem, calc(100% - 2rem)); + + > .signupSegment { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.5rem; + } + + > form { + gap: 1rem; + display: flex; + flex-direction: column; + width: 100%; + + > .loginButtons { + display: flex; + flex-direction: row; + align-items: center; + justify-content: end; + gap: 0.5rem; + } + } +} + +.alternateLoginMethod { + margin-left: auto; + margin-right: auto; +} diff --git a/instance/src/web/src/pages/userSelect/login/Login.tsx b/instance/src/web/src/pages/userSelect/login/Login.tsx index 9bb26ee..43e460d 100644 --- a/instance/src/web/src/pages/userSelect/login/Login.tsx +++ b/instance/src/web/src/pages/userSelect/login/Login.tsx @@ -1,168 +1,168 @@ -import KEY_ICON from "@material-symbols/svg-700/outlined/key.svg"; -import UKButton, { AffirmativeButtonState } from "@ewsgit/uikit-solid/src/components/button/UKButton.tsx"; -import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.tsx"; -import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.ts"; -import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.tsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.tsx"; -import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.tsx"; -import { startAuthentication } from "@simplewebauthn/browser"; -import { useNavigate, usePreloadRoute, useSearchParams } from "@solidjs/router"; -import { type Component, createEffect, createResource, createSignal, onMount } from "solid-js"; -import trpc from "../../../lib/trpc"; -import styles from "./Login.module.scss"; - -const UserSelectPage: Component = () => { - const navigate = useNavigate(); - const preloadRoute = usePreloadRoute(); - const [searchParams] = useSearchParams(); - - const [username, setUsername] = createSignal(searchParams.username?.toString() || ""); - const [password, setPassword] = createSignal(""); - const [showTwoFactor, setShowTwoFactor] = createSignal(false); - const [canSignup] = createResource(() => trpc.authorization.canSignup.query()); - - createEffect(async () => { - if ((await trpc.authorization.isAuthenticated.query()).authenticated) { - navigate("/app"); - } - }); - - createEffect(async () => { - const authenticationOptions = await trpc.authorization.passkeyRequestSignin.query({ username: username() }); - - if (authenticationOptions === undefined) return; - - const authenticationResponse = await startAuthentication({ - optionsJSON: authenticationOptions, - useBrowserAutofill: true, - }); - - const response = await trpc.authorization.passkeyCompleteSignin.mutate({ username: username(), passkeyResponse: authenticationResponse }); - - if (response.type === "success") { - const redirect = new URLSearchParams(window.location.search).get("redirect"); - if (redirect) { - navigate(redirect); - } - - navigate("/app"); - } - }); - - return ( - - - Sign In - - - {showTwoFactor() ? ( - <> - - Please enter the 2FA code from your authenticator app. - - { - if (val.length === 6) { - const resp = await trpc.authorization.passwordSignin.mutate({ - username: username(), - password: password(), - twoFactorCode: val, - }); - - if (resp.type === "success") { - const redirect = new URLSearchParams(window.location.search).get("redirect"); - if (redirect) { - navigate(redirect); - return; - } - - navigate("/app"); - } - } - }} - label={"Two Factor Code"} - /> - - ) : ( - <> -
- - -
- navigate(`/forgot-password?username=${username()}`)} disabled={username() === ""} color={"standard"}> - Forgot password? - - { - const resp = await trpc.authorization.passwordSignin.mutate({ - username: username(), - password: password(), - }); - - if (resp.type === "twofactor") { - setShowTwoFactor(true); - return { state: AffirmativeButtonState.Unset }; - } - - if (resp.type === "success") { - const redirect = new URLSearchParams(window.location.search).get("redirect"); - if (redirect) { - preloadRoute(redirect); - return { state: AffirmativeButtonState.Success, cb: () => navigate(redirect) }; - } - - preloadRoute("/app"); - return { - state: AffirmativeButtonState.Success, - cb: () => navigate("/app"), - }; - } - - // TODO: change to a toast when support is included in UIKit - console.error("Failed to login"); - return { state: AffirmativeButtonState.Error }; - }} - onSuccess={() => { }} - color={"filled"} - > - Login - -
- - {canSignup() ? ( - <> - -
- - Don't have an account? - - navigate("/signup")} color={"tonal"}> - Signup - -
- - ) : null} - - )} -
- ); -}; - -export default UserSelectPage; +import KEY_ICON from "@material-symbols/svg-700/outlined/key.svg"; +import UKButton, { AffirmativeButtonState } from "@ewsgit/uikit-solid/src/components/button/UKButton.tsx"; +import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.tsx"; +import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.ts"; +import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.tsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.tsx"; +import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.tsx"; +import { startAuthentication } from "@simplewebauthn/browser"; +import { useNavigate, usePreloadRoute, useSearchParams } from "@solidjs/router"; +import { type Component, createEffect, createResource, createSignal, onMount } from "solid-js"; +import trpc from "../../../lib/trpc"; +import styles from "./Login.module.scss"; + +const UserSelectPage: Component = () => { + const navigate = useNavigate(); + const preloadRoute = usePreloadRoute(); + const [searchParams] = useSearchParams(); + + const [username, setUsername] = createSignal(searchParams.username?.toString() || ""); + const [password, setPassword] = createSignal(""); + const [showTwoFactor, setShowTwoFactor] = createSignal(false); + const [canSignup] = createResource(() => trpc.authorization.canSignup.query()); + + createEffect(async () => { + if ((await trpc.authorization.isAuthenticated.query()).authenticated) { + navigate("/app"); + } + }); + + createEffect(async () => { + const authenticationOptions = await trpc.authorization.passkeyRequestSignin.query({ username: username() }); + + if (authenticationOptions === undefined) return; + + const authenticationResponse = await startAuthentication({ + optionsJSON: authenticationOptions, + useBrowserAutofill: true, + }); + + const response = await trpc.authorization.passkeyCompleteSignin.mutate({ username: username(), passkeyResponse: authenticationResponse }); + + if (response.type === "success") { + const redirect = new URLSearchParams(window.location.search).get("redirect"); + if (redirect) { + navigate(redirect); + } + + navigate("/app"); + } + }); + + return ( + + + Sign In + + + {showTwoFactor() ? ( + <> + + Please enter the 2FA code from your authenticator app. + + { + if (val.length === 6) { + const resp = await trpc.authorization.passwordSignin.mutate({ + username: username(), + password: password(), + twoFactorCode: val, + }); + + if (resp.type === "success") { + const redirect = new URLSearchParams(window.location.search).get("redirect"); + if (redirect) { + navigate(redirect); + return; + } + + navigate("/app"); + } + } + }} + label={"Two Factor Code"} + /> + + ) : ( + <> +
+ + +
+ navigate(`/forgot-password?username=${username()}`)} disabled={username() === ""} color={"standard"}> + Forgot password? + + { + const resp = await trpc.authorization.passwordSignin.mutate({ + username: username(), + password: password(), + }); + + if (resp.type === "twofactor") { + setShowTwoFactor(true); + return { state: AffirmativeButtonState.Unset }; + } + + if (resp.type === "success") { + const redirect = new URLSearchParams(window.location.search).get("redirect"); + if (redirect) { + preloadRoute(redirect); + return { state: AffirmativeButtonState.Success, cb: () => navigate(redirect) }; + } + + preloadRoute("/app"); + return { + state: AffirmativeButtonState.Success, + cb: () => navigate("/app"), + }; + } + + // TODO: change to a toast when support is included in UIKit + console.error("Failed to login"); + return { state: AffirmativeButtonState.Error }; + }} + onSuccess={() => { }} + color={"filled"} + > + Login + +
+ + {canSignup() ? ( + <> + +
+ + Don't have an account? + + navigate("/signup")} color={"tonal"}> + Signup + +
+ + ) : null} + + )} +
+ ); +}; + +export default UserSelectPage; diff --git a/instance/src/web/src/pages/userSelect/signup/Signup.module.scss b/instance/src/web/src/pages/userSelect/signup/Signup.module.scss index bf9f91f..d9272bc 100644 --- a/instance/src/web/src/pages/userSelect/signup/Signup.module.scss +++ b/instance/src/web/src/pages/userSelect/signup/Signup.module.scss @@ -1,41 +1,41 @@ -.modal { - gap: 1rem; - display: flex; - flex-direction: column; - width: max-content; - min-width: min(20rem, calc(100% - 2rem)); - - > .stageButtons { - display: flex; - flex-direction: row; - align-items: center; - justify-content: space-between; - gap: 0.5rem; - width: 100%; - } -} - -.guidePromptStage { - &.modal { - > .continueSegment { - display: flex; - flex-direction: row; - align-items: center; - justify-content: space-between; - gap: 0.5rem; - } - } -} - -.guideStage { - &.modal { - > .continueSegment { - display: flex; - flex-direction: row; - align-items: center; - justify-content: center; - width: 100%; - gap: 0.5rem; - } - } -} +.modal { + gap: 1rem; + display: flex; + flex-direction: column; + width: max-content; + min-width: min(20rem, calc(100% - 2rem)); + + > .stageButtons { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + width: 100%; + } +} + +.guidePromptStage { + &.modal { + > .continueSegment { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + } + } +} + +.guideStage { + &.modal { + > .continueSegment { + display: flex; + flex-direction: row; + align-items: center; + justify-content: center; + width: 100%; + gap: 0.5rem; + } + } +} diff --git a/instance/src/web/src/pages/userSelect/signup/Signup.tsx b/instance/src/web/src/pages/userSelect/signup/Signup.tsx index 2cf4356..a0d0f5f 100644 --- a/instance/src/web/src/pages/userSelect/signup/Signup.tsx +++ b/instance/src/web/src/pages/userSelect/signup/Signup.tsx @@ -1,215 +1,215 @@ -import UKAvatar from "@ewsgit/uikit-solid/src/components/avatar/UKAvatar.tsx"; -import UKButton, { - AffirmativeButtonState, -} from "@ewsgit/uikit-solid/src/components/button/UKButton.tsx"; -import UKCircularProgressIndicator from "@ewsgit/uikit-solid/src/components/circularProgressIndicator/UKCircularProgressIndicator.tsx"; -import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.tsx"; -import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.ts"; -import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.tsx"; -import UKSearchableDropdownMenu from "@ewsgit/uikit-solid/src/components/searchableDropdownMenu/UKSearchableDropdownMenu.tsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.tsx"; -import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.tsx"; -import { useNavigate, usePreloadRoute } from "@solidjs/router"; -import clsx from "clsx"; -import { - type Component, - createResource, - createSignal, - Match, - Switch, -} from "solid-js"; -import trpc from "../../../lib/trpc"; -import styles from "./Signup.module.scss"; -import Email from "./stages/Email/Email"; -import Password from "./stages/Password/Password"; -import Profile from "./stages/Profile/Profile"; -import TermsOfUse from "./stages/TermsOfUse/TermsOfUse"; -import TwoFactorAuthentication from "./stages/TwoFactorAuthentication/TwoFactorAuthentication"; -import Username from "./stages/Username/Username"; -import VerifyEmail from "./stages/VerifyEmail/VerifyEmail"; - -export enum UserSelectStage { - Username = 0, // set username - Email = 1, // set email - VerifyEmail = 2, // verify they own the email - Password = 3, // set password - Profile = 4, // set profile information - TermsOfUse = 5, // accept the terms of use for this instance - TwoFactorAuthentication = 6, // attempt to setup 2FA - GuidePrompt = 7, // prompt the user for if they want to see the introductory guide - Guide = 8, // guide the new user through the basics -} - -const UserSelectPage: Component = () => { - const navigate = useNavigate(); - const preload = usePreloadRoute(); - const [stage, setStage] = createSignal( - UserSelectStage.Username, - ); - - const [username, setUsername] = createSignal(""); - const [password, setPassword] = createSignal(""); - const [confirmedPassword, setConfirmedPassword] = createSignal(""); - const [emailAddress, setEmailAddress] = createSignal< - `${string}@${string}.${string}` | "" - >(""); - const [emailCode, setEmailCode] = createSignal(""); - const [displayName, setDisplayName] = createSignal(""); - const [gender, setGender] = createSignal<"female" | "male" | "other">( - "other", - ); - const [bio, setBio] = createSignal(""); - - const [requirements] = createResource(() => - trpc.authorization.signupRequirements.query(), - ); - - const [isUsernameValid, setIsUsernameValid] = createSignal(false); - const [twoFactorTestCode, setTwoFactorTestCode] = createSignal(""); - const [isEmailCodeValid, setIsEmailCodeValid] = createSignal(false); - - return ( - }> - - - - - - - - - - - - - - - - - { - // create the user - const resp = await trpc.authorization.signup.mutate({ - username: username(), - bio: bio(), - displayName: displayName(), - emailAddress: emailAddress(), - emailCode: emailCode(), - gender: gender(), - password: password(), - }); - - if (resp.type === "success") { - preload("/app/uk.ewsgit.dashboard"); - return { - state: AffirmativeButtonState.Success, - cb() { - setStage(UserSelectStage.TwoFactorAuthentication); - }, - }; - } else { - // TODO: add an error toast here instead of a console message (When implemented in UIKit of course) - console.error(resp); - alert("A critical error occurred!"); - - return { - state: AffirmativeButtonState.Error, - }; - } - }} - /> - - - - - - - - Guide - - - - {"Would you like to have a guide of your new workspace?"} - - -
- navigate("/app")} color={"tonal"}> - Skip guide - - { - setStage(UserSelectStage.Guide); - }} - color={"filled"} - > - Continue - -
-
-
- - - - {"Unimplemented"} - - - - {"The guide is not yet implemented"} - - -
- navigate("/app")} color={"filled"}> - Skip guide and continue - -
-
-
-
- ); -}; - -export default UserSelectPage; +import UKAvatar from "@ewsgit/uikit-solid/src/components/avatar/UKAvatar.tsx"; +import UKButton, { + AffirmativeButtonState, +} from "@ewsgit/uikit-solid/src/components/button/UKButton.tsx"; +import UKCircularProgressIndicator from "@ewsgit/uikit-solid/src/components/circularProgressIndicator/UKCircularProgressIndicator.tsx"; +import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.tsx"; +import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.ts"; +import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.tsx"; +import UKSearchableDropdownMenu from "@ewsgit/uikit-solid/src/components/searchableDropdownMenu/UKSearchableDropdownMenu.tsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.tsx"; +import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.tsx"; +import { useNavigate, usePreloadRoute } from "@solidjs/router"; +import clsx from "clsx"; +import { + type Component, + createResource, + createSignal, + Match, + Switch, +} from "solid-js"; +import trpc from "../../../lib/trpc"; +import styles from "./Signup.module.scss"; +import Email from "./stages/Email/Email"; +import Password from "./stages/Password/Password"; +import Profile from "./stages/Profile/Profile"; +import TermsOfUse from "./stages/TermsOfUse/TermsOfUse"; +import TwoFactorAuthentication from "./stages/TwoFactorAuthentication/TwoFactorAuthentication"; +import Username from "./stages/Username/Username"; +import VerifyEmail from "./stages/VerifyEmail/VerifyEmail"; + +export enum UserSelectStage { + Username = 0, // set username + Email = 1, // set email + VerifyEmail = 2, // verify they own the email + Password = 3, // set password + Profile = 4, // set profile information + TermsOfUse = 5, // accept the terms of use for this instance + TwoFactorAuthentication = 6, // attempt to setup 2FA + GuidePrompt = 7, // prompt the user for if they want to see the introductory guide + Guide = 8, // guide the new user through the basics +} + +const UserSelectPage: Component = () => { + const navigate = useNavigate(); + const preload = usePreloadRoute(); + const [stage, setStage] = createSignal( + UserSelectStage.Username, + ); + + const [username, setUsername] = createSignal(""); + const [password, setPassword] = createSignal(""); + const [confirmedPassword, setConfirmedPassword] = createSignal(""); + const [emailAddress, setEmailAddress] = createSignal< + `${string}@${string}.${string}` | "" + >(""); + const [emailCode, setEmailCode] = createSignal(""); + const [displayName, setDisplayName] = createSignal(""); + const [gender, setGender] = createSignal<"female" | "male" | "other">( + "other", + ); + const [bio, setBio] = createSignal(""); + + const [requirements] = createResource(() => + trpc.authorization.signupRequirements.query(), + ); + + const [isUsernameValid, setIsUsernameValid] = createSignal(false); + const [twoFactorTestCode, setTwoFactorTestCode] = createSignal(""); + const [isEmailCodeValid, setIsEmailCodeValid] = createSignal(false); + + return ( + }> + + + + + + + + + + + + + + + + + { + // create the user + const resp = await trpc.authorization.signup.mutate({ + username: username(), + bio: bio(), + displayName: displayName(), + emailAddress: emailAddress(), + emailCode: emailCode(), + gender: gender(), + password: password(), + }); + + if (resp.type === "success") { + preload("/app/uk.ewsgit.dashboard"); + return { + state: AffirmativeButtonState.Success, + cb() { + setStage(UserSelectStage.TwoFactorAuthentication); + }, + }; + } else { + // TODO: add an error toast here instead of a console message (When implemented in UIKit of course) + console.error(resp); + alert("A critical error occurred!"); + + return { + state: AffirmativeButtonState.Error, + }; + } + }} + /> + + + + + + + + Guide + + + + {"Would you like to have a guide of your new workspace?"} + + +
+ navigate("/app")} color={"tonal"}> + Skip guide + + { + setStage(UserSelectStage.Guide); + }} + color={"filled"} + > + Continue + +
+
+
+ + + + {"Unimplemented"} + + + + {"The guide is not yet implemented"} + + +
+ navigate("/app")} color={"filled"}> + Skip guide and continue + +
+
+
+
+ ); +}; + +export default UserSelectPage; diff --git a/instance/src/web/src/pages/userSelect/signup/stages/Email/Email.tsx b/instance/src/web/src/pages/userSelect/signup/stages/Email/Email.tsx index defafcb..8d53534 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/Email/Email.tsx +++ b/instance/src/web/src/pages/userSelect/signup/stages/Email/Email.tsx @@ -1,59 +1,59 @@ -import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; -import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; -import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.jsx"; -import type { Accessor, Component } from "solid-js"; -import z from "zod"; -import trpc from "../../../../../lib/trpc"; -import { UserSelectStage } from "../../Signup"; -import modalStyles from "../../Signup.module.scss"; - -const Email: Component<{ - setStage(stage: UserSelectStage): void; - emailAddress: Accessor; - setEmailAddress(emailAddress: string): void; - setEmailCode(emailCode: string): void; -}> = (props) => { - return ( - - - Set Email - - - -
- { - props.setStage(UserSelectStage.Username); - }} - color={"tonal"} - > - Back - - { - await trpc.authorization.checkEmailAddressOwnership.mutate({ - emailAddress: props.emailAddress(), - }); - - props.setStage(UserSelectStage.VerifyEmail); - }} - color={"filled"} - > - Continue - -
-
- ); -}; - -export default Email; +import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; +import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; +import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.jsx"; +import type { Accessor, Component } from "solid-js"; +import z from "zod"; +import trpc from "../../../../../lib/trpc"; +import { UserSelectStage } from "../../Signup"; +import modalStyles from "../../Signup.module.scss"; + +const Email: Component<{ + setStage(stage: UserSelectStage): void; + emailAddress: Accessor; + setEmailAddress(emailAddress: string): void; + setEmailCode(emailCode: string): void; +}> = (props) => { + return ( + + + Set Email + + + +
+ { + props.setStage(UserSelectStage.Username); + }} + color={"tonal"} + > + Back + + { + await trpc.authorization.checkEmailAddressOwnership.mutate({ + emailAddress: props.emailAddress(), + }); + + props.setStage(UserSelectStage.VerifyEmail); + }} + color={"filled"} + > + Continue + +
+
+ ); +}; + +export default Email; diff --git a/instance/src/web/src/pages/userSelect/signup/stages/Guide/Guide.tsx b/instance/src/web/src/pages/userSelect/signup/stages/Guide/Guide.tsx index b28d989..390e184 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/Guide/Guide.tsx +++ b/instance/src/web/src/pages/userSelect/signup/stages/Guide/Guide.tsx @@ -1,7 +1,7 @@ -import type { Component } from "solid-js"; - -const Guide: Component = () => { - return <>Guide; -}; - -export default Guide; +import type { Component } from "solid-js"; + +const Guide: Component = () => { + return <>Guide; +}; + +export default Guide; diff --git a/instance/src/web/src/pages/userSelect/signup/stages/GuidePrompt/GuidePrompt.tsx b/instance/src/web/src/pages/userSelect/signup/stages/GuidePrompt/GuidePrompt.tsx index 5bf391e..adb3651 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/GuidePrompt/GuidePrompt.tsx +++ b/instance/src/web/src/pages/userSelect/signup/stages/GuidePrompt/GuidePrompt.tsx @@ -1,7 +1,7 @@ -import type { Component } from "solid-js"; - -const GuidePrompt: Component = () => { - return <>GuidePrompt; -}; - -export default GuidePrompt; +import type { Component } from "solid-js"; + +const GuidePrompt: Component = () => { + return <>GuidePrompt; +}; + +export default GuidePrompt; diff --git a/instance/src/web/src/pages/userSelect/signup/stages/Password/Password.module.scss b/instance/src/web/src/pages/userSelect/signup/stages/Password/Password.module.scss index 20caa3e..fc0398e 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/Password/Password.module.scss +++ b/instance/src/web/src/pages/userSelect/signup/stages/Password/Password.module.scss @@ -1,11 +1,11 @@ -.root { -} - -.requirements { - display: grid; - grid-template-columns: auto 1fr; - align-items: center; - justify-content: start; - gap: 0.5rem; - margin-top: -0.5rem; -} +.root { +} + +.requirements { + display: grid; + grid-template-columns: auto 1fr; + align-items: center; + justify-content: start; + gap: 0.5rem; + margin-top: -0.5rem; +} diff --git a/instance/src/web/src/pages/userSelect/signup/stages/Password/Password.tsx b/instance/src/web/src/pages/userSelect/signup/stages/Password/Password.tsx index bc83a46..6f63999 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/Password/Password.tsx +++ b/instance/src/web/src/pages/userSelect/signup/stages/Password/Password.tsx @@ -1,123 +1,123 @@ -import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; -import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; -import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.js"; -import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.jsx"; -import type { Accessor, Component, Resource } from "solid-js"; -import { UserSelectStage } from "../../Signup"; -import modalStyles from "../../Signup.module.scss"; -import Requirement from "./components/Requirement/Requirement"; -import styles from "./Password.module.scss"; - -const Password: Component<{ - password: Accessor; - setPassword(password: string): void; - confirmedPassword: Accessor; - setConfirmedPassword(password: string): void; - setStage(stage: UserSelectStage): void; - requirements: Resource<{ - email: boolean; - passwordMinimumLength?: number; - passwordContains?: { - minimumLowercase?: number; - minimumNumbers?: number; - minimumSymbols?: number; - minimumUppercase?: number; - }; - }>; -}> = (props) => { - return ( - - - Create a strong password - - - - Password Requirements - -
- (props.requirements()?.passwordMinimumLength || 0)} - label={`Is at least ${props.requirements()?.passwordMinimumLength} characters long`} - /> - = (props.requirements()?.passwordContains?.minimumLowercase || 0)} - label={`Contains at least ${props.requirements()?.passwordContains?.minimumLowercase} lowercase letter`} - /> - = (props.requirements()?.passwordContains?.minimumUppercase || 0)} - label={`Contains at least ${props.requirements()?.passwordContains?.minimumUppercase} uppercase letter`} - /> - = (props.requirements()?.passwordContains?.minimumNumbers || 0)} - label={`Contains at least ${props.requirements()?.passwordContains?.minimumNumbers} number`} - /> - = (props.requirements()?.passwordContains?.minimumSymbols || 0)} - label={`Contains at least ${props.requirements()?.passwordContains?.minimumSymbols} special character`} - /> -
- - - -
- { - if (props.requirements()?.email) { - props.setStage(UserSelectStage.VerifyEmail); - } else { - props.setStage(UserSelectStage.Username); - } - }} - color={"tonal"} - > - Back - - (props.requirements()?.passwordMinimumLength || 0) && - (props.password()?.match(/[a-z]/g)?.length || 0) >= (props.requirements()?.passwordContains?.minimumLowercase || 0) && - (props.password()?.match(/[A-Z]/g)?.length || 0) >= (props.requirements()?.passwordContains?.minimumUppercase || 0) && - (props.password()?.match(/[0-9]/g)?.length || 0) >= (props.requirements()?.passwordContains?.minimumNumbers || 0) - ) - } - onClick={() => { - props.setStage(UserSelectStage.Profile); - }} - color={"filled"} - > - Continue - -
-
- ); -}; - -export default Password; +import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; +import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; +import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.js"; +import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.jsx"; +import type { Accessor, Component, Resource } from "solid-js"; +import { UserSelectStage } from "../../Signup"; +import modalStyles from "../../Signup.module.scss"; +import Requirement from "./components/Requirement/Requirement"; +import styles from "./Password.module.scss"; + +const Password: Component<{ + password: Accessor; + setPassword(password: string): void; + confirmedPassword: Accessor; + setConfirmedPassword(password: string): void; + setStage(stage: UserSelectStage): void; + requirements: Resource<{ + email: boolean; + passwordMinimumLength?: number; + passwordContains?: { + minimumLowercase?: number; + minimumNumbers?: number; + minimumSymbols?: number; + minimumUppercase?: number; + }; + }>; +}> = (props) => { + return ( + + + Create a strong password + + + + Password Requirements + +
+ (props.requirements()?.passwordMinimumLength || 0)} + label={`Is at least ${props.requirements()?.passwordMinimumLength} characters long`} + /> + = (props.requirements()?.passwordContains?.minimumLowercase || 0)} + label={`Contains at least ${props.requirements()?.passwordContains?.minimumLowercase} lowercase letter`} + /> + = (props.requirements()?.passwordContains?.minimumUppercase || 0)} + label={`Contains at least ${props.requirements()?.passwordContains?.minimumUppercase} uppercase letter`} + /> + = (props.requirements()?.passwordContains?.minimumNumbers || 0)} + label={`Contains at least ${props.requirements()?.passwordContains?.minimumNumbers} number`} + /> + = (props.requirements()?.passwordContains?.minimumSymbols || 0)} + label={`Contains at least ${props.requirements()?.passwordContains?.minimumSymbols} special character`} + /> +
+ + + +
+ { + if (props.requirements()?.email) { + props.setStage(UserSelectStage.VerifyEmail); + } else { + props.setStage(UserSelectStage.Username); + } + }} + color={"tonal"} + > + Back + + (props.requirements()?.passwordMinimumLength || 0) && + (props.password()?.match(/[a-z]/g)?.length || 0) >= (props.requirements()?.passwordContains?.minimumLowercase || 0) && + (props.password()?.match(/[A-Z]/g)?.length || 0) >= (props.requirements()?.passwordContains?.minimumUppercase || 0) && + (props.password()?.match(/[0-9]/g)?.length || 0) >= (props.requirements()?.passwordContains?.minimumNumbers || 0) + ) + } + onClick={() => { + props.setStage(UserSelectStage.Profile); + }} + color={"filled"} + > + Continue + +
+
+ ); +}; + +export default Password; diff --git a/instance/src/web/src/pages/userSelect/signup/stages/Password/components/Requirement/Requirement.tsx b/instance/src/web/src/pages/userSelect/signup/stages/Password/components/Requirement/Requirement.tsx index f3629e0..0540622 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/Password/components/Requirement/Requirement.tsx +++ b/instance/src/web/src/pages/userSelect/signup/stages/Password/components/Requirement/Requirement.tsx @@ -1,22 +1,22 @@ -import CHECK_ICON from "@material-symbols/svg-700/outlined/check.svg"; -import CLOSE_ICON from "@material-symbols/svg-700/outlined/close.svg"; -import UKIcon from "@ewsgit/uikit-solid/src/components/icon/UKIcon.jsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import type { Component } from "solid-js"; - -const Requirement: Component<{ shouldDisplay: boolean; checkValue: boolean; label: string }> = (props) => { - return ( - <> - {props.shouldDisplay && ( - <> - {props.checkValue ? CHECK_ICON : CLOSE_ICON} - - {props.label} - - - )} - - ); -}; - -export default Requirement; +import CHECK_ICON from "@material-symbols/svg-700/outlined/check.svg"; +import CLOSE_ICON from "@material-symbols/svg-700/outlined/close.svg"; +import UKIcon from "@ewsgit/uikit-solid/src/components/icon/UKIcon.jsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import type { Component } from "solid-js"; + +const Requirement: Component<{ shouldDisplay: boolean; checkValue: boolean; label: string }> = (props) => { + return ( + <> + {props.shouldDisplay && ( + <> + {props.checkValue ? CHECK_ICON : CLOSE_ICON} + + {props.label} + + + )} + + ); +}; + +export default Requirement; diff --git a/instance/src/web/src/pages/userSelect/signup/stages/Profile/Profile.module.scss b/instance/src/web/src/pages/userSelect/signup/stages/Profile/Profile.module.scss index 6a989c1..dc42226 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/Profile/Profile.module.scss +++ b/instance/src/web/src/pages/userSelect/signup/stages/Profile/Profile.module.scss @@ -1,35 +1,35 @@ -.avatar { - margin-left: auto; - margin-right: auto; -} - -.displayName { - font-variation-settings: - "wght" 900, - "wdth" 151, - "opsz" 8, - "GRAD" 60, - "XTRA" 475, - "XOPQ" 175, - "YOPQ" 100, - "YTLC" 570, - "YTAS" 850 !important; - text-align: center; - word-wrap: normal; -} - -.username { - margin-top: -0.75rem; - color: rgb(var(--uk-sys-color-secondary)); -} - -.pronouns { - margin-top: -0.75rem; - color: rgb(var(--uk-sys-color-secondary), 0.75); -} - -.buttonContainer { - display: flex; - align-items: center; - justify-content: endcop; -} +.avatar { + margin-left: auto; + margin-right: auto; +} + +.displayName { + font-variation-settings: + "wght" 900, + "wdth" 151, + "opsz" 8, + "GRAD" 60, + "XTRA" 475, + "XOPQ" 175, + "YOPQ" 100, + "YTLC" 570, + "YTAS" 850 !important; + text-align: center; + word-wrap: normal; +} + +.username { + margin-top: -0.75rem; + color: rgb(var(--uk-sys-color-secondary)); +} + +.pronouns { + margin-top: -0.75rem; + color: rgb(var(--uk-sys-color-secondary), 0.75); +} + +.buttonContainer { + display: flex; + align-items: center; + justify-content: endcop; +} diff --git a/instance/src/web/src/pages/userSelect/signup/stages/Profile/Profile.tsx b/instance/src/web/src/pages/userSelect/signup/stages/Profile/Profile.tsx index 6fe6e88..ea1331d 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/Profile/Profile.tsx +++ b/instance/src/web/src/pages/userSelect/signup/stages/Profile/Profile.tsx @@ -1,91 +1,91 @@ -import UKAvatar from "@ewsgit/uikit-solid/src/components/avatar/UKAvatar.jsx"; -import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; -import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; -import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.js"; -import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; -import UKSearchableDropdownMenu from "@ewsgit/uikit-solid/src/components/searchableDropdownMenu/UKSearchableDropdownMenu.jsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.jsx"; -import clsx from "clsx"; -import type { Accessor, Component } from "solid-js"; -import { UserSelectStage } from "../../Signup"; -import modalStyles from "../../Signup.module.scss"; -import styles from "./Profile.module.scss"; - -const Profile: Component<{ - username: Accessor; - displayName: Accessor; - gender: Accessor; - setGender(gender: string): void; - bio: Accessor; - setBio(bio: string): void; - setDisplayName(displayName: string): void; - setStage(stage: UserSelectStage): void; -}> = (props) => { - return ( - - - Setup Profile - - - - - {props.displayName() || props.username()} - - - {`@${props.username()}`} - - - {props.gender() === "female" ? "she/her" : props.gender() === "male" ? "he/him" : "they/them"} - - - props.setGender(val.toLowerCase())} - items={[ - { - id: "female", - type: "button", - label: "Female", - }, - { - id: "male", - type: "button", - label: "Male", - }, - { - id: "other", - type: "button", - label: "Other", - }, - ]} - /> - -
- { - if (props.displayName() === "") { - props.setDisplayName(props.username()); - } - - props.setStage(UserSelectStage.TermsOfUse); - }} - color={"filled"} - > - Continue - -
-
- ); -}; - -export default Profile; +import UKAvatar from "@ewsgit/uikit-solid/src/components/avatar/UKAvatar.jsx"; +import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; +import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; +import { DividerDirection } from "@ewsgit/uikit-solid/src/components/divider/lib/direction.js"; +import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; +import UKSearchableDropdownMenu from "@ewsgit/uikit-solid/src/components/searchableDropdownMenu/UKSearchableDropdownMenu.jsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.jsx"; +import clsx from "clsx"; +import type { Accessor, Component } from "solid-js"; +import { UserSelectStage } from "../../Signup"; +import modalStyles from "../../Signup.module.scss"; +import styles from "./Profile.module.scss"; + +const Profile: Component<{ + username: Accessor; + displayName: Accessor; + gender: Accessor; + setGender(gender: string): void; + bio: Accessor; + setBio(bio: string): void; + setDisplayName(displayName: string): void; + setStage(stage: UserSelectStage): void; +}> = (props) => { + return ( + + + Setup Profile + + + + + {props.displayName() || props.username()} + + + {`@${props.username()}`} + + + {props.gender() === "female" ? "she/her" : props.gender() === "male" ? "he/him" : "they/them"} + + + props.setGender(val.toLowerCase())} + items={[ + { + id: "female", + type: "button", + label: "Female", + }, + { + id: "male", + type: "button", + label: "Male", + }, + { + id: "other", + type: "button", + label: "Other", + }, + ]} + /> + +
+ { + if (props.displayName() === "") { + props.setDisplayName(props.username()); + } + + props.setStage(UserSelectStage.TermsOfUse); + }} + color={"filled"} + > + Continue + +
+
+ ); +}; + +export default Profile; diff --git a/instance/src/web/src/pages/userSelect/signup/stages/TermsOfUse/TermsOfUse.module.scss b/instance/src/web/src/pages/userSelect/signup/stages/TermsOfUse/TermsOfUse.module.scss index 4e6bdd8..938ead4 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/TermsOfUse/TermsOfUse.module.scss +++ b/instance/src/web/src/pages/userSelect/signup/stages/TermsOfUse/TermsOfUse.module.scss @@ -1,11 +1,11 @@ -.modal { - min-width: min(32rem, calc(100% - 2rem)); -} - -.continueSegment { - display: flex; - flex-direction: row; - align-items: center; - justify-content: space-between; - gap: 0.5rem; -} +.modal { + min-width: min(32rem, calc(100% - 2rem)); +} + +.continueSegment { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + gap: 0.5rem; +} diff --git a/instance/src/web/src/pages/userSelect/signup/stages/TermsOfUse/TermsOfUse.tsx b/instance/src/web/src/pages/userSelect/signup/stages/TermsOfUse/TermsOfUse.tsx index 5144e42..1212ec8 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/TermsOfUse/TermsOfUse.tsx +++ b/instance/src/web/src/pages/userSelect/signup/stages/TermsOfUse/TermsOfUse.tsx @@ -1,46 +1,46 @@ -import UKButton, { type AffirmativeButtonState } from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; -import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; -import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import { useNavigate } from "@solidjs/router"; -import clsx from "clsx"; -import { type Component, createResource } from "solid-js"; -import trpc from "../../../../../lib/trpc"; -import type { UserSelectStage } from "../../Signup"; -import modalStyles from "../../Signup.module.scss"; -import styles from "./TermsOfUse.module.scss"; - -const TermsOfUse: Component<{ - setStage(stage: UserSelectStage): void; - signup(): Promise<{ state: AffirmativeButtonState; cb?: () => void }>; -}> = (props) => { - const navigate = useNavigate(); - - const [termsOfUse] = createResource(() => trpc.termsOfUse.query()); - - return ( - - - Terms Of Use - - - - {termsOfUse()} - - - - You must agree to the terms above to continue - -
- navigate("/")} color={"tonal"}> - Deny - - - Agree and Continue - -
-
- ); -}; - -export default TermsOfUse; +import UKButton, { type AffirmativeButtonState } from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; +import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; +import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import { useNavigate } from "@solidjs/router"; +import clsx from "clsx"; +import { type Component, createResource } from "solid-js"; +import trpc from "../../../../../lib/trpc"; +import type { UserSelectStage } from "../../Signup"; +import modalStyles from "../../Signup.module.scss"; +import styles from "./TermsOfUse.module.scss"; + +const TermsOfUse: Component<{ + setStage(stage: UserSelectStage): void; + signup(): Promise<{ state: AffirmativeButtonState; cb?: () => void }>; +}> = (props) => { + const navigate = useNavigate(); + + const [termsOfUse] = createResource(() => trpc.termsOfUse.query()); + + return ( + + + Terms Of Use + + + + {termsOfUse()} + + + + You must agree to the terms above to continue + +
+ navigate("/")} color={"tonal"}> + Deny + + + Agree and Continue + +
+
+ ); +}; + +export default TermsOfUse; diff --git a/instance/src/web/src/pages/userSelect/signup/stages/TwoFactorAuthentication/TwoFactorAuthentication.module.scss b/instance/src/web/src/pages/userSelect/signup/stages/TwoFactorAuthentication/TwoFactorAuthentication.module.scss index 5d80fb0..c482b88 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/TwoFactorAuthentication/TwoFactorAuthentication.module.scss +++ b/instance/src/web/src/pages/userSelect/signup/stages/TwoFactorAuthentication/TwoFactorAuthentication.module.scss @@ -1,20 +1,20 @@ -.twoFactorStage { - > .skipButton { - margin-left: auto; - margin-right: auto; - } -} - -.qr { - width: 100%; - display: flex; - flex-direction: column; - gap: 0.5rem; - align-items: center; - justify-content: center; -} - -.singleButtonGroup { - display: flex; - justify-content: end; -} +.twoFactorStage { + > .skipButton { + margin-left: auto; + margin-right: auto; + } +} + +.qr { + width: 100%; + display: flex; + flex-direction: column; + gap: 0.5rem; + align-items: center; + justify-content: center; +} + +.singleButtonGroup { + display: flex; + justify-content: end; +} diff --git a/instance/src/web/src/pages/userSelect/signup/stages/TwoFactorAuthentication/TwoFactorAuthentication.tsx b/instance/src/web/src/pages/userSelect/signup/stages/TwoFactorAuthentication/TwoFactorAuthentication.tsx index cdf7bf0..55904b9 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/TwoFactorAuthentication/TwoFactorAuthentication.tsx +++ b/instance/src/web/src/pages/userSelect/signup/stages/TwoFactorAuthentication/TwoFactorAuthentication.tsx @@ -1,107 +1,107 @@ -import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; -import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; -import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.jsx"; -import clsx from "clsx"; -import QRCode from "qrcode"; -import { type Accessor, type Component, createEffect, createResource, createSignal, type Resource } from "solid-js"; -import trpc from "../../../../../lib/trpc"; -import { UserSelectStage } from "../../Signup"; -import modalStyles from "../../Signup.module.scss"; -import styles from "./TwoFactorAuthentication.module.scss"; - -const TwoFactorAuthentication: Component<{ - twoFactorTestCode: Accessor; - setTwoFactorTestCode(testCode: string): void; - setStage(stage: UserSelectStage): void; - requirements: Resource<{ twoFactorAuthentication?: boolean }>; -}> = (props) => { - const [isTwoFactorCodeValid, setIsTwoFactorCodeValid] = createSignal(false); - const [twoFactorSecret] = createResource(() => trpc.authorization.enableTwoFactor.mutate()); - let canvasElement!: HTMLCanvasElement; - - createEffect(() => { - const twoFactorSecretValue = twoFactorSecret(); - - if (!twoFactorSecretValue) return; - - QRCode.toCanvas(canvasElement, twoFactorSecretValue?.twoFactorSecretURI || "https://http.cat/404", (error) => { - if (error) console.error(error); - }); - }); - - return ( - <> - {isTwoFactorCodeValid() ? ( - - - Two Factor Setup Complete! - - - - You have successfully setup two-factor authentication on your account! - - -
- { - props.setStage(UserSelectStage.GuidePrompt); - }} - color={"filled"} - > - Continue - -
-
- ) : ( - - - Setup Two Factor Authentication - - -
- - - {`secret: ${twoFactorSecret()?.twoFactorSecret || "..."}`} - -
- { - props.setTwoFactorTestCode(value); - - if (value.length === 6) { - setIsTwoFactorCodeValid( - await trpc.authorization.confirmTwoFactor.mutate({ - twoFactorCode: value, - }), - ); - } - }} - supportingText={"*required"} - maximumCharacterCount={6} - /> - {!props.requirements()?.twoFactorAuthentication && ( - <> - - { - props.setStage(UserSelectStage.GuidePrompt); - }} - color={"standard"} - > - Skip Two Factor Setup - - - )} -
- )} - - ); -}; - -export default TwoFactorAuthentication; +import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; +import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; +import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.jsx"; +import clsx from "clsx"; +import QRCode from "qrcode"; +import { type Accessor, type Component, createEffect, createResource, createSignal, type Resource } from "solid-js"; +import trpc from "../../../../../lib/trpc"; +import { UserSelectStage } from "../../Signup"; +import modalStyles from "../../Signup.module.scss"; +import styles from "./TwoFactorAuthentication.module.scss"; + +const TwoFactorAuthentication: Component<{ + twoFactorTestCode: Accessor; + setTwoFactorTestCode(testCode: string): void; + setStage(stage: UserSelectStage): void; + requirements: Resource<{ twoFactorAuthentication?: boolean }>; +}> = (props) => { + const [isTwoFactorCodeValid, setIsTwoFactorCodeValid] = createSignal(false); + const [twoFactorSecret] = createResource(() => trpc.authorization.enableTwoFactor.mutate()); + let canvasElement!: HTMLCanvasElement; + + createEffect(() => { + const twoFactorSecretValue = twoFactorSecret(); + + if (!twoFactorSecretValue) return; + + QRCode.toCanvas(canvasElement, twoFactorSecretValue?.twoFactorSecretURI || "https://http.cat/404", (error) => { + if (error) console.error(error); + }); + }); + + return ( + <> + {isTwoFactorCodeValid() ? ( + + + Two Factor Setup Complete! + + + + You have successfully setup two-factor authentication on your account! + + +
+ { + props.setStage(UserSelectStage.GuidePrompt); + }} + color={"filled"} + > + Continue + +
+
+ ) : ( + + + Setup Two Factor Authentication + + +
+ + + {`secret: ${twoFactorSecret()?.twoFactorSecret || "..."}`} + +
+ { + props.setTwoFactorTestCode(value); + + if (value.length === 6) { + setIsTwoFactorCodeValid( + await trpc.authorization.confirmTwoFactor.mutate({ + twoFactorCode: value, + }), + ); + } + }} + supportingText={"*required"} + maximumCharacterCount={6} + /> + {!props.requirements()?.twoFactorAuthentication && ( + <> + + { + props.setStage(UserSelectStage.GuidePrompt); + }} + color={"standard"} + > + Skip Two Factor Setup + + + )} +
+ )} + + ); +}; + +export default TwoFactorAuthentication; diff --git a/instance/src/web/src/pages/userSelect/signup/stages/Username/Username.module.scss b/instance/src/web/src/pages/userSelect/signup/stages/Username/Username.module.scss index a3ca383..8b630b7 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/Username/Username.module.scss +++ b/instance/src/web/src/pages/userSelect/signup/stages/Username/Username.module.scss @@ -1,15 +1,15 @@ -.loginSegment { - display: flex; - flex-direction: column; - align-items: center; - gap: 0.5rem; -} - -.stageButtons { - display: flex; - flex-direction: row; - align-items: center; - justify-content: end; - gap: 0.5rem; - width: 100%; -} +.loginSegment { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.5rem; +} + +.stageButtons { + display: flex; + flex-direction: row; + align-items: center; + justify-content: end; + gap: 0.5rem; + width: 100%; +} diff --git a/instance/src/web/src/pages/userSelect/signup/stages/Username/Username.tsx b/instance/src/web/src/pages/userSelect/signup/stages/Username/Username.tsx index 372e041..d01bd7a 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/Username/Username.tsx +++ b/instance/src/web/src/pages/userSelect/signup/stages/Username/Username.tsx @@ -1,82 +1,82 @@ -import PERSON_ICON from "@material-symbols/svg-700/outlined/person.svg"; -import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; -import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; -import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.jsx"; -import { useNavigate } from "@solidjs/router"; -import clsx from "clsx"; -import type { Accessor, Component, Resource } from "solid-js"; -import trpc from "../../../../../lib/trpc"; -import { UserSelectStage } from "../../Signup"; -import modalStyles from "../../Signup.module.scss"; -import styles from "./Username.module.scss"; - -const Username: Component<{ - setStage(stage: UserSelectStage): void; - username: Accessor; - setUsername(username: string): void; - requirements: Resource<{ - email: boolean; - }>; - isUsernameValid: Accessor; - setIsUsernameValid(isValid: boolean): void; -}> = (props) => { - const navigate = useNavigate(); - - return ( - <> - - - Signup - - - { - props.setUsername(val); - - if (await trpc.authorization.isUsernameValid.query(val)) { - props.setIsUsernameValid(true); - } else { - props.setIsUsernameValid(false); - } - }} - onSubmit={() => { - if (props.username() !== "") props.setStage(UserSelectStage.Email); - }} - /> -
- { - if (props.requirements()?.email) { - props.setStage(UserSelectStage.Email); - } else { - props.setStage(UserSelectStage.Password); - } - }} - color={"filled"} - > - Continue - -
- -
- - Already have an account? - - navigate("/")} color={"tonal"}> - Login - -
-
- - ); -}; - -export default Username; +import PERSON_ICON from "@material-symbols/svg-700/outlined/person.svg"; +import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; +import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; +import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.jsx"; +import { useNavigate } from "@solidjs/router"; +import clsx from "clsx"; +import type { Accessor, Component, Resource } from "solid-js"; +import trpc from "../../../../../lib/trpc"; +import { UserSelectStage } from "../../Signup"; +import modalStyles from "../../Signup.module.scss"; +import styles from "./Username.module.scss"; + +const Username: Component<{ + setStage(stage: UserSelectStage): void; + username: Accessor; + setUsername(username: string): void; + requirements: Resource<{ + email: boolean; + }>; + isUsernameValid: Accessor; + setIsUsernameValid(isValid: boolean): void; +}> = (props) => { + const navigate = useNavigate(); + + return ( + <> + + + Signup + + + { + props.setUsername(val); + + if (await trpc.authorization.isUsernameValid.query(val)) { + props.setIsUsernameValid(true); + } else { + props.setIsUsernameValid(false); + } + }} + onSubmit={() => { + if (props.username() !== "") props.setStage(UserSelectStage.Email); + }} + /> +
+ { + if (props.requirements()?.email) { + props.setStage(UserSelectStage.Email); + } else { + props.setStage(UserSelectStage.Password); + } + }} + color={"filled"} + > + Continue + +
+ +
+ + Already have an account? + + navigate("/")} color={"tonal"}> + Login + +
+
+ + ); +}; + +export default Username; diff --git a/instance/src/web/src/pages/userSelect/signup/stages/VerifyEmail/VerifyEmail.tsx b/instance/src/web/src/pages/userSelect/signup/stages/VerifyEmail/VerifyEmail.tsx index 02a73f2..862a2af 100644 --- a/instance/src/web/src/pages/userSelect/signup/stages/VerifyEmail/VerifyEmail.tsx +++ b/instance/src/web/src/pages/userSelect/signup/stages/VerifyEmail/VerifyEmail.tsx @@ -1,71 +1,71 @@ -import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; -import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; -import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; -import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; -import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.jsx"; -import { type Accessor, type Component, createSignal } from "solid-js"; -import trpc from "../../../../../lib/trpc"; -import { UserSelectStage } from "../../Signup"; -import modalStyles from "../../Signup.module.scss"; -import styles from "./VerifyEmail.module.scss"; - -const VerifyEmail: Component<{ - emailAddress: Accessor; - emailCode: Accessor; - setEmailCode(emailCode: string): void; - setStage(stage: UserSelectStage): void; - isEmailCodeValid: Accessor; - setIsEmailCodeValid(isValid: boolean): void; -}> = (props) => { - return ( - <> - - - Verify Email - - - - Please enter the code which was sent to the email you provided to continue. - - { - props.setEmailCode(value); - - props.setIsEmailCodeValid( - await trpc.authorization.validateEmailCode.query({ - emailAddress: props.emailAddress(), - emailCode: props.emailCode(), - }), - ); - }} - maximumCharacterCount={8} - supportingText={"*required"} - /> -
- { - props.setStage(UserSelectStage.Email); - }} - color={"tonal"} - > - Back - - { - props.setStage(UserSelectStage.Password); - }} - color={"filled"} - > - Continue - -
-
- - ); -}; - -export default VerifyEmail; +import UKButton from "@ewsgit/uikit-solid/src/components/button/UKButton.jsx"; +import UKCard from "@ewsgit/uikit-solid/src/components/card/UKCard.jsx"; +import UKDivider from "@ewsgit/uikit-solid/src/components/divider/UKDivider.jsx"; +import UKText from "@ewsgit/uikit-solid/src/components/text/UKText.jsx"; +import UKTextField from "@ewsgit/uikit-solid/src/components/textField/UKTextField.jsx"; +import { type Accessor, type Component, createSignal } from "solid-js"; +import trpc from "../../../../../lib/trpc"; +import { UserSelectStage } from "../../Signup"; +import modalStyles from "../../Signup.module.scss"; +import styles from "./VerifyEmail.module.scss"; + +const VerifyEmail: Component<{ + emailAddress: Accessor; + emailCode: Accessor; + setEmailCode(emailCode: string): void; + setStage(stage: UserSelectStage): void; + isEmailCodeValid: Accessor; + setIsEmailCodeValid(isValid: boolean): void; +}> = (props) => { + return ( + <> + + + Verify Email + + + + Please enter the code which was sent to the email you provided to continue. + + { + props.setEmailCode(value); + + props.setIsEmailCodeValid( + await trpc.authorization.validateEmailCode.query({ + emailAddress: props.emailAddress(), + emailCode: props.emailCode(), + }), + ); + }} + maximumCharacterCount={8} + supportingText={"*required"} + /> +
+ { + props.setStage(UserSelectStage.Email); + }} + color={"tonal"} + > + Back + + { + props.setStage(UserSelectStage.Password); + }} + color={"filled"} + > + Continue + +
+
+ + ); +}; + +export default VerifyEmail; diff --git a/instance/src/web/src/vite-env.d.ts b/instance/src/web/src/vite-env.d.ts index 11f02fe..7d0ff9e 100644 --- a/instance/src/web/src/vite-env.d.ts +++ b/instance/src/web/src/vite-env.d.ts @@ -1 +1 @@ -/// +/// diff --git a/instance/src/web/tsconfig.app.json b/instance/src/web/tsconfig.app.json index a640bff..86eb47e 100644 --- a/instance/src/web/tsconfig.app.json +++ b/instance/src/web/tsconfig.app.json @@ -1,28 +1,28 @@ -{ - "compilerOptions": { - "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", - "target": "ES2022", - "useDefineForClassFields": true, - "module": "ESNext", - "lib": ["ES2022", "DOM", "DOM.Iterable"], - "skipLibCheck": true, - - /* Bundler mode */ - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "verbatimModuleSyntax": true, - "moduleDetection": "force", - "noEmit": true, - "jsx": "preserve", - "jsxImportSource": "solid-js", - - /* Linting */ - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "erasableSyntaxOnly": false, - "noFallthroughCasesInSwitch": true, - "noUncheckedSideEffectImports": true - }, - "include": ["src"] -} +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", + "target": "ES2022", + "useDefineForClassFields": true, + "module": "ESNext", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", + + /* Linting */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": false, + "noFallthroughCasesInSwitch": true, + "noUncheckedSideEffectImports": true + }, + "include": ["src"] +} diff --git a/instance/src/web/tsconfig.json b/instance/src/web/tsconfig.json index 1ffef60..38e8e3b 100644 --- a/instance/src/web/tsconfig.json +++ b/instance/src/web/tsconfig.json @@ -1,7 +1,7 @@ -{ - "files": [], - "references": [ - { "path": "./tsconfig.app.json" }, - { "path": "./tsconfig.node.json" } - ] -} +{ + "files": [], + "references": [ + { "path": "./tsconfig.app.json" }, + { "path": "./tsconfig.node.json" } + ] +} diff --git a/instance/src/web/tsconfig.node.json b/instance/src/web/tsconfig.node.json index f85a399..f82894f 100644 --- a/instance/src/web/tsconfig.node.json +++ b/instance/src/web/tsconfig.node.json @@ -1,25 +1,25 @@ -{ - "compilerOptions": { - "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", - "target": "ES2023", - "lib": ["ES2023"], - "module": "ESNext", - "skipLibCheck": true, - - /* Bundler mode */ - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "verbatimModuleSyntax": true, - "moduleDetection": "force", - "noEmit": true, - - /* Linting */ - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "erasableSyntaxOnly": true, - "noFallthroughCasesInSwitch": true, - "noUncheckedSideEffectImports": true - }, - "include": ["vite.config.ts"] -} +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "target": "ES2023", + "lib": ["ES2023"], + "module": "ESNext", + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + + /* Linting */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedSideEffectImports": true + }, + "include": ["vite.config.ts"] +} diff --git a/instance/src/web/vite.config.ts b/instance/src/web/vite.config.ts index 50f3264..92220c5 100644 --- a/instance/src/web/vite.config.ts +++ b/instance/src/web/vite.config.ts @@ -1,32 +1,32 @@ -// import devtools from "solid-devtools/vite"; -import { defineConfig } from "vite"; -import { compression } from "vite-plugin-compression2"; -import solid from "vite-plugin-solid"; - -export default defineConfig({ - plugins: [ - // @ts-ignore - // devtools({ - // /* features options - all disabled by default */ - // autoname: true, // e.g. enable autoname - // }), - solid(), - compression(), - ], - server: { - host: true, - allowedHosts: [process.env.ALLOW_HOST || "localhost"], - hmr: { - clientPort: 443, - protocol: "wss", - host: process.env.ALLOW_HOST || "localhost", - }, - }, - resolve: { - alias: { - "@solidjs/router": "/node_modules/@solidjs/router", - "@ewsgit/uikit-solid": "/node_modules/@ewsgit/uikit-solid", - "@onlineworkspace/workspaces-applications": "/../../../fs/system/vite/Applications.tsx", - }, - }, -}); +// import devtools from "solid-devtools/vite"; +import { defineConfig } from "vite"; +import { compression } from "vite-plugin-compression2"; +import solid from "vite-plugin-solid"; + +export default defineConfig({ + plugins: [ + // @ts-ignore + // devtools({ + // /* features options - all disabled by default */ + // autoname: true, // e.g. enable autoname + // }), + solid(), + compression(), + ], + server: { + host: true, + allowedHosts: [process.env.ALLOW_HOST || "localhost"], + hmr: { + clientPort: 443, + protocol: "wss", + host: process.env.ALLOW_HOST || "localhost", + }, + }, + resolve: { + alias: { + "@solidjs/router": "/node_modules/@solidjs/router", + "@ewsgit/uikit-solid": "/node_modules/@ewsgit/uikit-solid", + "@onlineworkspace/workspaces-applications": "/../../../fs/system/vite/Applications.tsx", + }, + }, +}); diff --git a/uikit-solid b/uikit-solid index 9496b1c..23f4386 160000 --- a/uikit-solid +++ b/uikit-solid @@ -1 +1 @@ -Subproject commit 9496b1c69fdbf2bfe086c9ab6067fa242b1c3b1c +Subproject commit 23f4386375e2c998be5da6986471092de870c7fa -- knotmirror 0.0.1