80 lines
2.4 KiB
TypeScript
80 lines
2.4 KiB
TypeScript
import { type HistoryState } from "./history_state";
|
|
import { createShellState, type ShellState } from "./shell_state";
|
|
import { createShellError, type LoginError, type UserNotFoundError } from "./util/errors";
|
|
|
|
export interface GroupInfo {
|
|
readonly groupname: string;
|
|
readonly gid: number;
|
|
readonly members: number[];
|
|
}
|
|
|
|
export interface UserInfo {
|
|
readonly username: string;
|
|
readonly uid: number;
|
|
readonly gid: number;
|
|
readonly group: readonly number[];
|
|
readonly home: number;
|
|
}
|
|
|
|
export interface SessionState {
|
|
readonly user: UserInfo;
|
|
readonly envVars: ReadonlyMap<string, string>;
|
|
readonly history: HistoryState;
|
|
readonly cwd: number;
|
|
readonly pwd: number;
|
|
readonly exitCode: number;
|
|
}
|
|
|
|
export function createInitialSessionState(user: UserInfo): SessionState {
|
|
return Object.freeze({
|
|
user,
|
|
envVars: Object.freeze(new Map()),
|
|
history: Object.freeze([]),
|
|
cwd: user.home,
|
|
pwd: user.home,
|
|
exitCode: 0,
|
|
} satisfies SessionState);
|
|
}
|
|
|
|
export function getCurrentSession(state: ShellState): SessionState {
|
|
return state.sessionStack[state.sessionStack.length - 1]!;
|
|
}
|
|
|
|
export function login(
|
|
state: ShellState,
|
|
username: string,
|
|
password: string,
|
|
passwdMap: ReadonlyMap<number, string>,
|
|
): ShellState {
|
|
const user = state.users.values().find(value => value.username === username);
|
|
if (!user) {
|
|
throw createShellError<UserNotFoundError>("UserNotFound", "The specified user does not exist", { username });
|
|
}
|
|
|
|
const passwd = passwdMap.get(user.uid);
|
|
if (!passwd) {
|
|
throw createShellError<LoginError>("LoginError", "The user does not have a password mapped to their uid", {
|
|
user: user.uid,
|
|
});
|
|
}
|
|
|
|
// Change this to hashed passwords later on
|
|
if (!(password === passwd)) {
|
|
throw createShellError<LoginError>("LoginError", "The password is incorrect", { user: user.uid });
|
|
}
|
|
|
|
const stack = [...state.sessionStack];
|
|
stack.push(createInitialSessionState(user));
|
|
return createShellState(state.filesystem, state.users, state.groups, stack);
|
|
}
|
|
|
|
export function logout(state: ShellState): ShellState {
|
|
if (state.sessionStack.length > 1) {
|
|
const stack = [...state.sessionStack];
|
|
stack.pop();
|
|
|
|
return createShellState(state.filesystem, state.users, state.groups, stack);
|
|
}
|
|
return state;
|
|
}
|