some useless bs work on the indexed db and json fetching functions, shell done, can successfully call commands via the main Shell singleton
This commit is contained in:
@@ -29,5 +29,8 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.28.1": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
export interface TermosConfig {
|
||||
serverAddress: string;
|
||||
dbName: string;
|
||||
idbName: string;
|
||||
}
|
||||
|
||||
export const defaultConfig: TermosConfig = {
|
||||
serverAddress: "",
|
||||
dbName: "termos",
|
||||
idbName: "cache",
|
||||
};
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ export interface CommandDescriptor {
|
||||
fn: CommandFn;
|
||||
name: string;
|
||||
flags?: readonly FlagDescriptor[];
|
||||
requresRoot?: boolean;
|
||||
requiresRoot?: boolean;
|
||||
description?: string;
|
||||
keybinds?: readonly string[];
|
||||
}
|
||||
|
||||
@@ -73,7 +73,11 @@ export interface InvalidArgumentsError extends ShellError {
|
||||
actual: string; // e.g., the user's input
|
||||
}
|
||||
|
||||
// Codes 3 - 63 reserved for currently running processes, and their specific error handling.
|
||||
// Codes 3 - 62 reserved for currently running processes, and their specific error handling.
|
||||
|
||||
export interface ParseError extends ShellError {
|
||||
errorType: "ParseError";
|
||||
}
|
||||
|
||||
/** Command used incorrectly (bad flag, wrong arg count) - maps to EX_USAGE (Exit 64) */
|
||||
export interface UsageError extends ShellError {
|
||||
|
||||
+72
-17
@@ -1,18 +1,21 @@
|
||||
import { FileSystem } from "@core/filesystem/filesystem";
|
||||
import type { Result } from "@core/result";
|
||||
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
||||
import type { ShellError } from "@core/util/errors";
|
||||
import { COMMAND_REGISTRY } from "@core/command_registry";
|
||||
import { createErrorResult, createSuccessResult, type Result, type ResultError } from "@core/result";
|
||||
import { getCurrentSession } from "@core/session_manager";
|
||||
import { withExitCode, withHistory, type ShellState } from "@core/shell_state";
|
||||
import type { CommandNotFoundError, ParseError, PermissionDeniedError, ShellError } from "@core/util/errors";
|
||||
import { createImmutableBuffer } from "@core/util/immutable_buffer";
|
||||
import { parseCommand } from "@core/util/parser";
|
||||
|
||||
export class Shell {
|
||||
static #instance: Shell;
|
||||
static #promise: Promise<Shell> | null = null;
|
||||
private readonly state: Readonly<ShellState>;
|
||||
private _state: Readonly<ShellState>;
|
||||
|
||||
private constructor(state: ShellState) {
|
||||
this.state = Object.freeze(state);
|
||||
this._state = Object.freeze(state);
|
||||
}
|
||||
|
||||
static async init(): Promise<Shell> {
|
||||
static async init(initialState: ShellState): Promise<Shell> {
|
||||
if (Shell.#instance) {
|
||||
console.warn("Shell already initialized");
|
||||
return this.#instance;
|
||||
@@ -20,15 +23,9 @@ export class Shell {
|
||||
|
||||
if (Shell.#promise) return Shell.#promise;
|
||||
|
||||
const fs = FileSystem.init()
|
||||
const users =
|
||||
const sessionStack =
|
||||
|
||||
const state: ShellState = createInitialShellState(); //Create initial shell state,
|
||||
|
||||
Shell.#promise = (async () => {
|
||||
try {
|
||||
Shell.#instance = new Shell();
|
||||
Shell.#instance = new Shell(initialState);
|
||||
return Shell.#instance;
|
||||
} finally {
|
||||
Shell.#promise = null;
|
||||
@@ -38,15 +35,73 @@ export class Shell {
|
||||
return Shell.#promise;
|
||||
}
|
||||
|
||||
public async Execute(input: string): Promise<Result<ShellError>> {}
|
||||
public async Execute(input: string): Promise<Result<ShellError>> {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = parseCommand(input);
|
||||
} catch {
|
||||
return createErrorResult(
|
||||
"ParseError",
|
||||
`Parsing error - ${input}`,
|
||||
{},
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
"",
|
||||
) satisfies ResultError<ParseError>;
|
||||
}
|
||||
|
||||
if (parsed.command === "") {
|
||||
return createSuccessResult(
|
||||
"",
|
||||
0,
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
);
|
||||
}
|
||||
|
||||
this._state = withHistory(this._state, input);
|
||||
const command = COMMAND_REGISTRY.get(parsed.command);
|
||||
|
||||
if (!command)
|
||||
return createErrorResult(
|
||||
"CommandNotFound",
|
||||
`Command ${parsed.command} not found`,
|
||||
{ command: parsed.command },
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
parsed.command,
|
||||
) satisfies ResultError<CommandNotFoundError>;
|
||||
|
||||
if (command.requiresRoot && getCurrentSession(this._state).user.uid != 0) {
|
||||
return createErrorResult(
|
||||
"PermissionDenied",
|
||||
`Permission Denied`,
|
||||
{ resource: `Execution of the ${command.name} command` },
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
createImmutableBuffer(new Uint8Array()),
|
||||
parsed.command,
|
||||
) satisfies ResultError<PermissionDeniedError>;
|
||||
}
|
||||
|
||||
const out = command.fn(this._state, parsed.flags, parsed.args);
|
||||
this._state = out.state;
|
||||
|
||||
if (out.result.type === "error") {
|
||||
this._state = withExitCode(this._state, out.result.error.exitCode);
|
||||
} else {
|
||||
this._state = withExitCode(this._state, out.result.exitCode);
|
||||
}
|
||||
|
||||
return out.result;
|
||||
}
|
||||
|
||||
public get State(): Readonly<ShellState> {
|
||||
return this.state;
|
||||
return this._state;
|
||||
}
|
||||
|
||||
public static get Instance(): Shell | undefined {
|
||||
if (!Shell.#instance) {
|
||||
console.error("Shell has not been initialised yet. Call `await Singleton.init()` first.");
|
||||
console.error("Shell has not been initialised yet. Call `await Shell.init()` first.");
|
||||
return;
|
||||
}
|
||||
return Shell.#instance;
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { MD5 } from "./hash";
|
||||
|
||||
//INDEXED DB IS SO FUCKING DOGSHIT ITS INSANE
|
||||
|
||||
//TODO: load IDB db name from config;
|
||||
|
||||
export async function initializeIDB() {
|
||||
const request = indexedDB.open("cache");
|
||||
request.onerror = e => {
|
||||
throw new Error(`Failed to open the IDB during the init - ${request.error}`);
|
||||
};
|
||||
|
||||
request.onsuccess = e => {
|
||||
const DB = request.result;
|
||||
const STORE = DB.createObjectStore("fs", { autoIncrement: true });
|
||||
|
||||
STORE.createIndex("json", "json");
|
||||
STORE.createIndex("checksum", "checksum");
|
||||
};
|
||||
}
|
||||
|
||||
export async function writeFileSystemCache(cache: string, checksum: string) {
|
||||
if (cache.length === 0 || checksum.length === 0) {
|
||||
throw new Error(`Cache value or the checksum value cannot be empty!`);
|
||||
}
|
||||
|
||||
if (!isChecksumMatching(cache, checksum))
|
||||
throw new Error("The cache value checksum does not match the provided checksum");
|
||||
|
||||
const request = indexedDB.open("cache");
|
||||
request.onerror = e => {
|
||||
throw new Error(`Failed to open the IDB during the init - ${request.error}`);
|
||||
};
|
||||
|
||||
request.onsuccess = e => {
|
||||
const DB = request.result;
|
||||
const T = DB.transaction(["cache"], "readwrite");
|
||||
const STOREFS = T.objectStore("fs");
|
||||
const STORECK = T.objectStore("fs");
|
||||
|
||||
const RFS = STOREFS.add(cache);
|
||||
//const CFS =
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchFileSystemCache(): Promise<{ cache: string; checksum: string }> {
|
||||
const request = indexedDB.open("cache");
|
||||
|
||||
request.onerror = e => {
|
||||
throw new Error(`Failed to open the IDB - ${request.error}`);
|
||||
};
|
||||
|
||||
request.onsuccess = e => {
|
||||
const DB = request.result;
|
||||
const T = DB.transaction(["cache"], "readonly");
|
||||
const STORE = T.objectStore("fs");
|
||||
|
||||
const R = STORE.get("1");
|
||||
|
||||
R.onerror = e => {
|
||||
throw new Error(`Some IDB error - ${R.error}`);
|
||||
};
|
||||
|
||||
R.onsuccess = e => {
|
||||
console.log(R.result.json, R.result.checksum);
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
function isChecksumMatching(json: string, checksum: string): boolean {
|
||||
const resourceChksm = MD5.hash(json);
|
||||
return resourceChksm === checksum;
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
export class MD5 {
|
||||
private static encoder: TextEncoder = new TextEncoder();
|
||||
|
||||
// prettier-ignore
|
||||
private static K: number[] = [
|
||||
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
|
||||
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
|
||||
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
|
||||
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
|
||||
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
|
||||
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
|
||||
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
|
||||
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
|
||||
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
|
||||
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
|
||||
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
|
||||
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
|
||||
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
|
||||
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
|
||||
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
|
||||
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
|
||||
];
|
||||
|
||||
// prettier-ignore
|
||||
private static S: number[] = [
|
||||
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
|
||||
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
|
||||
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
|
||||
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
|
||||
];
|
||||
|
||||
public static hash(input: string) {
|
||||
const inputArr: Uint8Array<ArrayBuffer> = this.encoder.encode(input);
|
||||
const padded = MD5.pad(inputArr);
|
||||
|
||||
let A = 0x67452301;
|
||||
let B = 0xefcdab89;
|
||||
let C = 0x98badcfe;
|
||||
let D = 0x10325476;
|
||||
|
||||
function processBlock(M: number[]) {
|
||||
function F(b: number, c: number, d: number): number {
|
||||
return (b & c) | (~b & d);
|
||||
}
|
||||
function H(b: number, c: number, d: number): number {
|
||||
return b ^ c ^ d;
|
||||
}
|
||||
function I(b: number, c: number, d: number): number {
|
||||
return c ^ (b | ~d);
|
||||
}
|
||||
function G(b: number, c: number, d: number): number {
|
||||
return (b & d) | (c & ~d);
|
||||
}
|
||||
|
||||
let AA = A,
|
||||
BB = B,
|
||||
CC = C,
|
||||
DD = D;
|
||||
|
||||
for (let i = 0; i < 64; i++) {
|
||||
let f: number, g: number;
|
||||
|
||||
if (i < 16) {
|
||||
f = F(B, C, D);
|
||||
g = i;
|
||||
} else if (i < 32) {
|
||||
f = G(B, C, D);
|
||||
g = (5 * i + 1) % 16;
|
||||
} else if (i < 48) {
|
||||
f = H(B, C, D);
|
||||
g = (3 * i + 5) % 16;
|
||||
} else {
|
||||
f = I(B, C, D);
|
||||
g = (7 * i) % 16;
|
||||
}
|
||||
|
||||
const sum = MD5.add32(A, MD5.add32(f, MD5.add32(M[g]!, MD5.K[i]!)));
|
||||
const temp = MD5.add32(B, MD5.leftRotate(sum, MD5.S[i]!));
|
||||
|
||||
A = D;
|
||||
D = C;
|
||||
C = B;
|
||||
B = temp;
|
||||
}
|
||||
|
||||
A = MD5.add32(A, AA);
|
||||
B = MD5.add32(B, BB);
|
||||
C = MD5.add32(C, CC);
|
||||
D = MD5.add32(D, DD);
|
||||
}
|
||||
|
||||
for (let i = 0; i < padded.length; i += 64) {
|
||||
const M = MD5.sliceToWords(padded.slice(i, i + 64));
|
||||
processBlock(M); // modifies A, B, C, D directly
|
||||
}
|
||||
|
||||
const hashBytes = new Uint8Array([
|
||||
...MD5.wordToBytesLE(A),
|
||||
...MD5.wordToBytesLE(B),
|
||||
...MD5.wordToBytesLE(C),
|
||||
...MD5.wordToBytesLE(D),
|
||||
]);
|
||||
|
||||
return MD5.toHexString(hashBytes);
|
||||
}
|
||||
|
||||
private static pad(input: Uint8Array): Uint8Array {
|
||||
const inputBitLength: number = input.length * 8;
|
||||
|
||||
const out: Uint8Array = new Uint8Array([...input, 0x80]);
|
||||
const NBytes: number = (56 - (out.length % 64) + 64) % 64;
|
||||
|
||||
const zeroArray = new Uint8Array(NBytes);
|
||||
|
||||
const low = inputBitLength >>> 0;
|
||||
const high = (inputBitLength / 0x100000000) >>> 0;
|
||||
|
||||
const lengthBytes = new Uint8Array([
|
||||
low & 0xff,
|
||||
(low >> 8) & 0xff,
|
||||
(low >> 16) & 0xff,
|
||||
(low >> 24) & 0xff,
|
||||
high & 0xff,
|
||||
(high >> 8) & 0xff,
|
||||
(high >> 16) & 0xff,
|
||||
(high >> 24) & 0xff,
|
||||
]);
|
||||
|
||||
return new Uint8Array([...out, ...zeroArray, ...lengthBytes]);
|
||||
}
|
||||
|
||||
private static sliceToBlocks(input: Uint8Array): number[][] {
|
||||
const blocks: number[][] = [];
|
||||
|
||||
for (let i = 0; i < input.length; i += 64) {
|
||||
const block = input.slice(i, i + 64);
|
||||
blocks.push(MD5.sliceToWords(block));
|
||||
}
|
||||
|
||||
return blocks;
|
||||
}
|
||||
|
||||
private static sliceToWords(block: Uint8Array): number[] {
|
||||
const words: number[] = new Array<number>(16);
|
||||
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const offset: number = i * 4;
|
||||
|
||||
words[i] =
|
||||
(block[offset]! |
|
||||
(block[offset + 1]! << 8) |
|
||||
(block[offset + 2]! << 16) |
|
||||
(block[offset + 3]! << 24)) >>>
|
||||
0;
|
||||
}
|
||||
|
||||
return words;
|
||||
}
|
||||
|
||||
private static leftRotate(x: number, n: number): number {
|
||||
x = x >>> 0;
|
||||
return ((x << n) | (x >>> (32 - n))) >>> 0;
|
||||
}
|
||||
|
||||
private static add32(a: number, b: number): number {
|
||||
return ((a >>> 0) + (b >>> 0)) >>> 0;
|
||||
}
|
||||
|
||||
private static wordToBytesLE(word: number): Uint8Array {
|
||||
return new Uint8Array([word & 0xff, (word >>> 8) & 0xff, (word >>> 16) & 0xff, (word >>> 24) & 0xff]);
|
||||
}
|
||||
|
||||
private static toHexString(bytes: Uint8Array): string {
|
||||
return Array.from(bytes)
|
||||
.map(b => b.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
Create an interface for the rest of the library to use to fetch nessesary data.
|
||||
To do that, implement a termos config that will contain the table and db names, aswell as other relevant information -
|
||||
maybe a flag for headless mode (uses the built-in console frontend module - need to evaluate this idea more)
|
||||
*/
|
||||
|
||||
export async function fetchFileSystem(ep: string = `/api/v1/filesystem`): Promise<string> {
|
||||
// FUCK IT NO CACHE FOR NOW, IDB IS RETARDED
|
||||
const cacheETag = "suck my dick";
|
||||
const cacheData = "no data here";
|
||||
|
||||
const headers: HeadersInit = {};
|
||||
if (cacheETag) {
|
||||
headers["If-None-Match"] = cacheETag;
|
||||
}
|
||||
|
||||
const response = await fetch(ep, { headers });
|
||||
|
||||
let json: string;
|
||||
if (response.status === 304 && cacheData) {
|
||||
json = cacheData;
|
||||
} else if (response.ok) {
|
||||
json = await response.text();
|
||||
const newETag = response.headers.get("ETag");
|
||||
// cache the json string here
|
||||
|
||||
if (newETag) {
|
||||
// cache the new checksum (etag) here
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Failed to load filesystem: ${response.status}`);
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
//export async function fetchUserGroups(ep: string = ): Promise<JSON> {}
|
||||
|
||||
//export async function fetchUsers(): Promise<JSON> {}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { getCurrentSession, type UserInfo } from "@core/session_manager";
|
||||
import { createInitialShellState, type ShellState } from "@core/shell_state";
|
||||
import { Shell } from "@shell/shell";
|
||||
import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
const testTree: FixtureNode = {
|
||||
inode: 0,
|
||||
name: "root",
|
||||
type: "Dir",
|
||||
children: [
|
||||
{
|
||||
inode: 1,
|
||||
name: "hello.txt",
|
||||
type: "File",
|
||||
content: "Goodbye World!",
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
inode: 2,
|
||||
name: "sub",
|
||||
type: "Dir",
|
||||
children: [
|
||||
{
|
||||
inode: 3,
|
||||
name: "world.txt",
|
||||
type: "File",
|
||||
content: "Goodbye!",
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
inode: 4,
|
||||
name: "bye",
|
||||
type: "Dir",
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const fs = buildTestFS(testTree);
|
||||
|
||||
const users: Map<number, UserInfo> = new Map();
|
||||
const user: UserInfo = {
|
||||
username: "root",
|
||||
uid: 0,
|
||||
gid: 0,
|
||||
group: [0],
|
||||
home: 0,
|
||||
};
|
||||
users.set(0, user);
|
||||
|
||||
const state: ShellState = createInitialShellState(fs, users, user);
|
||||
|
||||
describe("Shell tests", () => {
|
||||
test("Successfully executes the cd command", async () => {
|
||||
await Shell.init(state);
|
||||
const result = await Shell.Instance?.Execute("cd /sub");
|
||||
const statee = Shell.Instance?.State;
|
||||
|
||||
expect(result?.type).toEqual("success");
|
||||
expect(getCurrentSession(statee!).history.length).toBe(1);
|
||||
expect(getCurrentSession(statee!).history[0]).toEqual("cd /sub");
|
||||
expect(getCurrentSession(statee!).cwd).toBe(2);
|
||||
expect(getCurrentSession(statee!).exitCode).toBe(0);
|
||||
});
|
||||
test("Returns a proper command error from cd", () => {});
|
||||
test("Returns an empty success result as per parsing a whitespace character or inputing nothing", () => {});
|
||||
});
|
||||
Reference in New Issue
Block a user