Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/telnet-charset #122

Merged
merged 5 commits into from
Nov 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 1 addition & 25 deletions backend/src/core/environment/environment.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ describe('Environment', () => {

process.env.SOCKET_ROOT = '/socket.io';

process.env.CHARSET = 'utf8';

const env = await getFreshEnvironmentInstance();

const { Environment } = await import('./environment');
Expand All @@ -47,15 +45,11 @@ describe('Environment', () => {

process.env.SOCKET_ROOT = '/socket.io';

process.env.CHARSET = 'utf8';

const env = await getFreshEnvironmentInstance();

expect(env.telnetHost).toBe('localhost');

expect(env.telnetPort).toBe(3000);

expect(env.charset).toBe('utf8');
});

it('should handle optional TLS configuration', async () => {
Expand All @@ -65,8 +59,6 @@ describe('Environment', () => {

process.env.SOCKET_ROOT = '/socket.io';

process.env.CHARSET = 'utf8';

process.env.TELNET_TLS = 'true';

const env = await getFreshEnvironmentInstance();
Expand All @@ -81,8 +73,6 @@ describe('Environment', () => {

process.env.SOCKET_ROOT = '/socket.io';

process.env.CHARSET = 'utf8';

process.env.TELNET_TLS = 'TRUE';

const env = await getFreshEnvironmentInstance();
Expand All @@ -97,31 +87,17 @@ describe('Environment', () => {

process.env.SOCKET_ROOT = '/socket.io';

process.env.CHARSET = 'utf8';

const env = await getFreshEnvironmentInstance();

expect(env.telnetTLS).toBe(false);
});

it('should use default charset if not set', async () => {
process.env.TELNET_HOST = 'localhost';

process.env.TELNET_PORT = '3000';

process.env.SOCKET_ROOT = '/socket.io';

const env = await getFreshEnvironmentInstance();

expect(env.charset).toBe('utf8');
});

it('should set projectRoot correctly', async () => {
process.env.TELNET_HOST = 'localhost';

process.env.TELNET_PORT = '3000';

process.env.CHARSET = 'utf8';
process.env.CHARSET = 'utf-8';

process.env.SOCKET_ROOT = '/socket.io';

Expand Down
16 changes: 13 additions & 3 deletions backend/src/core/environment/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ export class Environment implements IEnvironment {
public readonly telnetHost: string;
public readonly telnetPort: number;
public readonly telnetTLS: boolean;
public readonly charset: string;
public readonly projectRoot: string;
public readonly socketRoot: string;
public readonly socketTimeout: number;
public readonly environment: 'production' | 'development';

/**
* Private constructor to enforce singleton pattern.
Expand All @@ -46,12 +46,22 @@ export class Environment implements IEnvironment {

this.socketRoot = String(getEnvironmentVariable('SOCKET_ROOT'));

this.charset = String(getEnvironmentVariable('CHARSET', false, 'utf8'));

this.socketTimeout = Number(
getEnvironmentVariable('SOCKET_TIMEOUT', false, '900000'),
);

const environment = String(
getEnvironmentVariable('ENVIRONMENT', false, 'production'),
).toLocaleLowerCase();

if (environment !== 'production' && environment !== 'development') {
throw new Error(
'Environment variable "ENVIRONMENT" must be either "production" or "development" or unset.',
);
}

this.environment = environment;

this.projectRoot = resolveModulePath('../../../main.js');

logger.info('[Environment] initialized', this);
Expand Down
4 changes: 2 additions & 2 deletions backend/src/core/environment/types/environment-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ export type EnvironmentKeys =
| 'TELNET_PORT' // Required. Example '23'
| 'TELNET_TLS' // Optional. Defaults to 'false'
| 'SOCKET_TIMEOUT' // in milliseconds | default: 900000 (15 min) | determines how long messages are buffed for the disconnected frontend and when the telnet connection is closed
| 'SOCKET_ROOT' // Required. Example '/socket.io'
| 'CHARSET'; // Optional. Defaults to 'utf8';
| 'SOCKET_ROOT'
| 'ENVIRONMENT';
22 changes: 1 addition & 21 deletions backend/src/core/environment/types/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,7 @@ export interface IEnvironment {
readonly projectRoot: string;
readonly socketRoot: string;

readonly charset: string;

readonly socketTimeout: number;

// backend: {
// host: string;
// port: number;
// };
// frontend: {
// host: string;
// port: number;
// };
// mudrpc: {
// socketfile: string;
// };
// webmud: {
// mudname: string;
// autoConnect: boolean;
// autoLogin: boolean;
// autoUser: string;
// autoToken: string;
// localEcho: boolean;
// };
readonly environment: 'production' | 'development';
}
53 changes: 53 additions & 0 deletions backend/src/core/middleware/use-rest-endpoints.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { Express, Request, Response } from 'express';

import { TelnetControlSequences } from '../../features/telnet/types/telnet-control-sequences.js';
import { TelnetOptions } from '../../features/telnet/types/telnet-options.js';
import { logger } from '../../shared/utils/logger.js';
import { SocketManager } from '../sockets/socket-manager.js';

export const useRestEndpoints = (
app: Express,
socketManager: SocketManager,
) => {
app.use('/api/info', (req: Request, res: Response) => {
logger.info(`[Middleware] [Rest] requested /api/info`);

const connections = Object.entries(socketManager.mudConnections).flatMap(
([connectionKey, con]) => {
const negotiations = Object.entries(con.telnet?.negotiations || {}).map(
([negotiationKey, negotiations]) => {
const key = Number(negotiationKey);

return {
code: TelnetOptions[key],
...{
server: negotiations?.server
? TelnetControlSequences[negotiations?.server]
: {},
},
...{
client: negotiations?.client
? TelnetControlSequences[negotiations?.client]
: {},
},
...negotiations?.subnegotiation,
};
},
);

return {
connection: connectionKey,
telnet: {
connected:
con.telnet?.isConnected === undefined
? 'no instance'
: con.telnet.isConnected,
negotiations,
},
};
},
);

res.send(connections);
});
};
2 changes: 1 addition & 1 deletion backend/src/core/middleware/use-sockets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const useSockets = (
httpServer: HttpServer | HttpsServer,
environment: Environment,
) => {
new SocketManager(httpServer, {
return new SocketManager(httpServer, {
telnetHost: environment.telnetHost,
telnetPort: environment.telnetPort,
useTelnetTls: environment.telnetTLS,
Expand Down
39 changes: 32 additions & 7 deletions backend/src/core/sockets/socket-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { TelnetClient } from '../../features/telnet/telnet-client.js';
import { TelnetControlSequences } from '../../features/telnet/types/telnet-control-sequences.js';
import { TelnetOptions } from '../../features/telnet/types/telnet-options.js';
import { logger } from '../../shared/utils/logger.js';
import { mapToServerEncodings } from '../../shared/utils/supported-encodings.js';
import { Environment } from '../environment/environment.js';
import { ClientToServerEvents } from './types/client-to-server-events.js';
import { InterServerEvents } from './types/inter-server-events.js';
Expand All @@ -17,7 +18,7 @@ export class SocketManager extends Server<
ServerToClientEvents,
InterServerEvents
> {
private readonly mudConnections: MudConnections = {};
public readonly mudConnections: MudConnections = {};

public constructor(
server: HttpServer | HttpsServer,
Expand Down Expand Up @@ -126,10 +127,7 @@ export class SocketManager extends Server<
return;
}

telnetClient.sendMessage(
// data.toString(Environment.getInstance().charset) + '\r\n',
`${data}\r\n`,
);
telnetClient.sendMessage(`${data}\r\n`);
});

socket.on('mudConnect', () => {
Expand All @@ -149,7 +147,34 @@ export class SocketManager extends Server<
);

telnetClient.on('data', (data: string | Buffer) => {
socket.emit('mudOutput', data.toString('utf8'));
const mudCharset =
this.mudConnections[socket.id].telnet?.negotiations[
TelnetOptions.TELOPT_CHARSET
]?.subnegotiation?.clientOption;

if (mudCharset === undefined) {
logger.warn(
'[Socket-Manager] [Client] no charset negotiated before sending data. Default to utf-8',
);

socket.emit('mudOutput', data.toString('utf-8'));

return;
}

const charset = mapToServerEncodings(mudCharset);

if (charset !== null) {
socket.emit('mudOutput', data.toString(charset));

return;
}

logger.warn(
`[Socket-Manager] [Client] unknown charset ${mudCharset}. Default to utf-8`,
);

socket.emit('mudOutput', data.toString('utf-8'));
});

telnetClient.on('close', () => {
Expand All @@ -163,7 +188,7 @@ export class SocketManager extends Server<
});

telnetClient.on('negotiationChanged', (negotiation) => {
logger.info(
logger.verbose(
`[Socket-Manager] [Client] ${socket.id} telnet negotiation changed. Emitting 'negotiationChanged'`,
negotiation,
);
Expand Down
Loading
Loading