Harold #01 — server.js, the Harold Hub

Words
274
Reading
2 min
16m
Listen to this post
~2 min

One safety note before you try this: the archived prototype below has permissive CORS and an unauthenticated webhook. Keep it local; do not expose it publicly until those parts are hardened.

Hey Hive, I thought I’d start this code series with the file that ties Harold Hub together. This little Express server serves the web page, connects the chat route, mounts the FTP module, and lets connected clients hear about events through Socket.IO. It’s the front door to this early version of Harold Hub.

I’m sharing the real code here, including the rough edges. The chat response function is still a placeholder, and this is not ready to expose as a public service: CORS is permissive and the webhook has no authentication. Treat it as an early local prototype, not a production-ready server. Those are things I’d want to harden before anyone runs it where other people can reach it.

To try the prototype locally, install its dependencies with npm install, then run node server.js. It listens on port 3000 by default, serves the portal, and accepts chat messages at /api/chat. I’m building this archive one piece at a time so people can follow how the parts fit together; there’s still work to do before it becomes the resilient, independently rebuildable Harold I have in mind.

const express = require('express');
const cors = require('cors');
const { createServer } = require('http');
const { Server } = require('socket.io');
const path = require('path');

const app = express();
const server = createServer(app);
const io = new Server(server, {
  cors: {
    origin: '*',
    methods: ['GET', 'POST'],
  },
});

const PORT = process.env.PORT || 3000;

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));

// FTP routes
const { router: ftpRouter } = require('./ftp-server.js');
app.use('/api/ftp', ftpRouter);

// Chat API
app.post('/api/chat', async (req, res) => {
  try {
    const { message, history, sessionId } = req.body;

    if (!message) {
      return res.status(400).json({ error: 'Message is required' });
    }

    const response = generateHaroldResponse(message, history);

    io.emit('harold-event', {
      event: 'chat-response',
      data: { message, response, sessionId },
      timestamp: new Date().toISOString(),
    });

    res.json({ response });
  } catch (error) {
    console.error('Chat API error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// Webhook for local machine events
app.post('/api/webhook', (req, res) => {
  const { event, data } = req.body;

  io.emit('harold-event', {
    event,
    data,
    timestamp: new Date().toISOString(),
  });

  res.json({ success: true });
});

// Health check
app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// WebSocket connection
io.on('connection', (socket) => {
  console.log('Client connected:', socket.id);

  socket.on('join', (sessionId) => {
    socket.join(sessionId);
    console.log(`Socket ${socket.id} joined session ${sessionId}`);
  });

  socket.on('disconnect', () => {
    console.log('Client disconnected:', socket.id);
  });
});

// Response generation (placeholder for actual Harold logic)
function generateHaroldResponse(message, history) {
  const lower = message.toLowerCase();

  if (lower.includes('hello') || lower.includes('hi')) {
    return "Hello! I'm Harold, your AI assistant with file management capabilities. How can I help you today?";
  }
  if (lower.includes('how are you')) {
    return "I'm just a program, but I'm functioning perfectly! How about you?";
  }
  if (lower.includes('name')) {
    return "I'm Harold, your AI assistant. I can help with chat and file management!";
  }
  if (lower.includes('help')) {
    return "I'm here to help! You can ask me questions, request information, or manage files. Try saying 'list files' or 'search for [filename]'";
  }
  if (lower.includes('cool') || lower.includes('awesome') || lower.includes('great')) {
    return "Yes! With the FTP server integration, I can help you manage files remotely. It's pretty cool!";
  }

  const responses = [
    "That's interesting! Tell me more.",
    "I understand. What else would you like to discuss?",
    "Thanks for sharing that with me.",
    "I'm here to help with whatever you need. I can also manage files if you ask!",
  ];
  return responses[Math.floor(Math.random() * responses.length)];
}

server.listen(PORT, () => {
  console.log(`
  ╔════════════════════════════════════════════════════════════╗
  ║         Harold Hub Server — Post #01                      ║
  ║                                              ║
  ║  Chat API:  http://localhost:${PORT}/api/chat           ║
  ║  Webhook:   http://localhost:${PORT}/api/webhook         ║
  ║  Health:    http://localhost:${PORT}/health              ║
  ║  WebSocket: ws://localhost:${PORT}                       ║
  ╚════════════════════════════════════════════════════════════╝
  `);
});

This is the first piece in the archive. I’ll share the other parts as I get them ready, and I’ll link them back here so the trail is easy to follow.

Source file: server.js. SHA-256 recorded in the archive draft: 5643da55179ab9060f09b12cd357509fe41f725b0b8b086fdd95cff8c1c19911.

#harold #judithgroup #decentralized #code-archive #ecency #haroldhub #server #hive-ai #node-code #harold01 #pimp #archon #waivio #palnet #creativecoin #javascript #nodejs #express #ftp