Skip to content
Draft
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
7 changes: 7 additions & 0 deletions health-check-server/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
PORT=3000
NODE_ENV=development
API_URL=https://api.internxt.com
AUTH_TOKEN=your-jwt-token-here
CLIENT_NAME=health-check-server
CLIENT_VERSION=1.0.0
CRYPTO_SECRET=your-crypto-secret-here
6 changes: 6 additions & 0 deletions health-check-server/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
node_modules/
dist/
.env
*.log
.DS_Store

29 changes: 29 additions & 0 deletions health-check-server/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "@internxt/health-check-server",
"version": "1.0.0",
"description": "Health check server for monitoring Internxt API endpoints",
"private": true,
"main": "dist/index.js",
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc",
"start": "node dist/index.js",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@dashlane/pqc-kem-kyber512-node": "^1.0.0",
"@fastify/env": "^4.4.0",
"bip39": "^3.1.0",
"crypto-js": "^4.2.0",
"dotenv": "^16.4.5",
"fastify": "^4.28.1",
"openpgp": "^5.11.3"
},
"devDependencies": {
"@types/crypto-js": "^4.2.2",
"@types/node": "^20.14.10",
"pino-pretty": "^11.2.1",
"tsx": "^4.16.2",
"typescript": "^5.9.3"
}
}
43 changes: 43 additions & 0 deletions health-check-server/src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { config as loadEnv } from 'dotenv';
import { Config } from './types';

loadEnv();

function loadConfig(): Config {
const requiredVars = [
'API_URL',
'AUTH_TOKEN',
'CLIENT_NAME',
'CLIENT_VERSION',
'LOGIN_EMAIL',
'LOGIN_PASSWORD',
'CRYPTO_SECRET',
'MAGIC_IV',
'MAGIC_SALT',
];

const missing = requiredVars.filter((varName) => !process.env[varName]);

if (missing.length > 0) {
throw new Error(
`Missing required environment variables: ${missing.join(', ')}\n` +
'Please ensure all required variables are set in your .env file',
);
}

return {
port: Number.parseInt(process.env.PORT ?? '7001'),
apiUrl: process.env.API_URL!,
authToken: process.env.AUTH_TOKEN!,
clientName: process.env.CLIENT_NAME!,
clientVersion: process.env.CLIENT_VERSION!,
nodeEnv: process.env.NODE_ENV || 'development',
loginEmail: process.env.LOGIN_EMAIL!,
loginPassword: process.env.LOGIN_PASSWORD!,
cryptoSecret: process.env.CRYPTO_SECRET!,
magicIv: process.env.MAGIC_IV!,
magicSalt: process.env.MAGIC_SALT!,
};
}

export const config = loadConfig();
64 changes: 64 additions & 0 deletions health-check-server/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import Fastify from 'fastify';
import { config } from './config';
import { loggingPlugin } from './plugins/logging';
import { errorHandlerPlugin } from './plugins/errorHandler';
import { driveRoutes } from './routes/drive';

async function start() {
const fastify = Fastify({
logger: {
level: config.nodeEnv === 'development' ? 'info' : 'warn',
transport:
config.nodeEnv === 'development'
? {
target: 'pino-pretty',
options: {
translateTime: 'HH:MM:ss Z',
ignore: 'pid,hostname',
},
}
: undefined,
},
});

try {
await fastify.register(loggingPlugin);
await fastify.register(errorHandlerPlugin);

await fastify.register(driveRoutes);

fastify.get('/health', async () => {
return {
status: 'healthy',
service: 'health-check-server',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
};
});

await fastify.listen({
port: config.port,
host: '0.0.0.0',
});

fastify.log.info('Health check server started successfully');
fastify.log.info(`Listening on port ${config.port}`);
fastify.log.info(`API URL: ${config.apiUrl}`);
fastify.log.info(`Environment: ${config.nodeEnv}`);
} catch (error) {
fastify.log.error(error);
process.exit(1);
}
}

process.on('SIGINT', () => {
process.stdout.write('\nShutting down gracefully...\n');
process.exit(0);
});

process.on('SIGTERM', () => {
process.stdout.write('\nShutting down gracefully...\n');
process.exit(0);
});

start();
30 changes: 30 additions & 0 deletions health-check-server/src/plugins/errorHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { FastifyInstance, FastifyError, FastifyRequest, FastifyReply } from 'fastify';

/**
* Error handler plugin for Fastify
* Transforms errors into standardized health check responses
*/
export async function errorHandlerPlugin(fastify: FastifyInstance) {
fastify.setErrorHandler(async (error: FastifyError, request: FastifyRequest, reply: FastifyReply) => {
request.log.error(
{
error: error.message,
stack: error.stack,
url: request.url,
method: request.method,
},
'Error occurred during request',
);

const statusCode = error.statusCode ?? 503;

return reply.status(statusCode).send({
status: 'unhealthy',
endpoint: request.url,
timestamp: new Date().toISOString(),
error: error.message,
});
});

fastify.log.info('Error handler plugin registered');
}
32 changes: 32 additions & 0 deletions health-check-server/src/plugins/logging.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';

/**
* Logging plugin for Fastify
* Logs all incoming requests and their responses
*/
export async function loggingPlugin(fastify: FastifyInstance) {
fastify.addHook('onRequest', async (request: FastifyRequest) => {
request.log.info(
{
method: request.method,
url: request.url,
userAgent: request.headers['user-agent'],
},
'Incoming request',
);
});

fastify.addHook('onResponse', async (request: FastifyRequest, reply: FastifyReply) => {
request.log.info(
{
method: request.method,
url: request.url,
statusCode: reply.statusCode,
responseTime: reply.elapsedTime,
},
'Request completed',
);
});

fastify.log.info('Logging plugin registered');
}
137 changes: 137 additions & 0 deletions health-check-server/src/routes/drive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import * as bip39 from 'bip39';
import { LoginDetails, RegisterDetails } from '../../../src/auth';
import { UserSettings } from '../../../src/shared/types/userSettings';
import { config } from '../config';
import { HealthCheckResponse } from '../types';
import { getAuthClient, cryptoProvider } from '../utils/auth';
import { handleHealthCheckError } from '../utils/healthCheck';
import { passToHash, encryptText, encryptTextWithKey } from '../utils/crypto';

export async function driveRoutes(fastify: FastifyInstance) {
const authClient = getAuthClient();

fastify.post('/drive/login', async (request: FastifyRequest, reply: FastifyReply) => {
const startTime = Date.now();

try {
const securityDetails = await authClient.securityDetails(config.loginEmail);

if (!securityDetails.encryptedSalt) {
throw new Error('Security details did not return encryptedSalt');
}

const responseTime = Date.now() - startTime;

const response: HealthCheckResponse = {
status: 'healthy',
endpoint: 'drive/login',
timestamp: new Date().toISOString(),
responseTime,
};

return reply.status(200).send(response);
} catch (error: unknown) {
handleHealthCheckError(error, reply, 'drive/login', startTime);
}
});

fastify.post('/drive/access', async (request: FastifyRequest, reply: FastifyReply) => {
const startTime = Date.now();

try {
const loginDetails: LoginDetails = {
email: config.loginEmail,
password: config.loginPassword,
tfaCode: undefined,
};

const loginResponse = await authClient.loginWithoutKeys(loginDetails, cryptoProvider);

// Verify we got both JWT tokens
if (!loginResponse.token || !loginResponse.newToken) {
throw new Error('Login response did not return both JWT tokens');
}

const responseTime = Date.now() - startTime;

const response: HealthCheckResponse = {
status: 'healthy',
endpoint: 'drive/access',
timestamp: new Date().toISOString(),
responseTime,
};

return reply.status(200).send(response);
} catch (error: unknown) {
handleHealthCheckError(error, reply, 'drive/access', startTime);
}
});

fastify.post('/drive/signup', async (request: FastifyRequest, reply: FastifyReply) => {
const startTime = Date.now();

try {
const timestamp = Date.now();
const email = `dev+${timestamp}@internxt.com`;
const password = config.loginPassword;

// Generate password hash and salt
const hashObj = passToHash({ password });
const encPass = encryptText(hashObj.hash);
const encSalt = encryptText(hashObj.salt);

const mnemonic = bip39.generateMnemonic(256);
const encMnemonic = encryptTextWithKey(mnemonic, password);

const keys = await cryptoProvider.generateKeys(password);

const registerDetails: RegisterDetails = {
name: 'Health',
lastname: 'Check',
email: email.toLowerCase(),
password: encPass,
salt: encSalt,
mnemonic: encMnemonic,
keys: keys,
captcha: '',
referral: undefined,
referrer: undefined,
};

const data = await authClient.register(registerDetails);

const user = data.user as unknown as UserSettings;

const hasRequiredFields =
user.email &&
user.rootFolderId &&
user.bucket &&
user.keys?.ecc?.publicKey &&
user.keys?.ecc?.privateKey &&
user.keys?.kyber?.publicKey &&
user.keys?.kyber?.privateKey;

if (!hasRequiredFields) {
throw new Error('Response missing required fields: kyber/ecc keys, email, rootFolderId, or bucket');
}

const responseTime = Date.now() - startTime;

const response: HealthCheckResponse = {
status: 'healthy',
endpoint: 'drive/signup',
timestamp: new Date().toISOString(),
responseTime,
};

fastify.log.info(`Signup health check successful - created account: ${email}`);

return reply.status(200).send(response);
} catch (error: unknown) {
handleHealthCheckError(error, reply, 'drive/signup', startTime);
}
});

fastify.log.info('Drive routes registered');
}
21 changes: 21 additions & 0 deletions health-check-server/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export interface HealthCheckResponse {
status: 'healthy' | 'unhealthy';
endpoint: string;
timestamp: string;
responseTime?: number;
error?: string;
}

export interface Config {
port: number;
apiUrl: string;
authToken: string;
clientName: string;
clientVersion: string;
nodeEnv: string;
loginEmail: string;
loginPassword: string;
cryptoSecret: string;
magicIv: string;
magicSalt: string;
}
Loading
Loading