Skip to content
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
Binary file added assets/trayTemplate.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions assets/trayTemplate.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/trayTemplate@2x.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
138 changes: 135 additions & 3 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"dependencies": {
"@fastify/cors": "^11.0.1",
"@fastify/rate-limit": "^10.3.0",
"@fastify/websocket": "^11.3.0",
"async-mutex": "^0.5.0",
"chokidar": "^4.0.3",
"dotenv": "^16.5.0",
Expand Down
74 changes: 74 additions & 0 deletions backend/src/api/realtime-websocket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import websocket from '@fastify/websocket';
import type { FastifyInstance } from 'fastify';
import { extractRequestToken, validateRequestToken } from '../utils/auth.js';

interface RealtimeSocket {
readyState: number;
send(data: string): void;
on(event: 'message', listener: (data: unknown) => void): void;
on(event: 'close' | 'error', listener: () => void): void;
}

const OPEN_STATE = 1;
const clients = new Set<RealtimeSocket>();

export interface FileChangeMessage {
type: 'file_change';
event: string;
path: string;
timestamp: number;
}

export function broadcastFileChange(event: string, filePath: string): void {
const message: FileChangeMessage = {
type: 'file_change',
event,
path: filePath,
timestamp: Date.now(),
};
const payload = JSON.stringify(message);

for (const client of clients) {
if (client.readyState === OPEN_STATE) {
client.send(payload);
}
}
}

export async function registerRealtimeWebSocket(app: FastifyInstance): Promise<void> {
await app.register(websocket);

app.get<{ Querystring: { access_token?: string } }>('/ws', {
websocket: true,
preValidation: async (request, reply) => {
const token = extractRequestToken(
request.headers['x-papyrus-token'],
request.query.access_token,
);
if (!validateRequestToken(token)) {
await reply.status(401).send({ success: false, error: 'Unauthorized' });
}
},
}, (socket) => {
clients.add(socket);

socket.on('message', (data: unknown) => {
try {
const message = JSON.parse(String(data)) as { type?: unknown };
if (message.type === 'ping' && socket.readyState === OPEN_STATE) {
socket.send(JSON.stringify({ type: 'pong', timestamp: Date.now() }));
}
} catch {
// Ignore malformed client messages; the channel only accepts optional heartbeat pings.
}
});

const removeClient = () => clients.delete(socket);
socket.on('close', removeClient);
socket.on('error', removeClient);
});
}

export function clearRealtimeClients(): void {
clients.clear();
}
7 changes: 7 additions & 0 deletions backend/src/api/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ import {
validateRequestToken,
} from '../utils/auth.js';
import { closeDb } from '../db/database.js';
import {
broadcastFileChange,
registerRealtimeWebSocket,
} from './realtime-websocket.js';

const logger = new PapyrusLogger(
paths.logDir,
Expand Down Expand Up @@ -139,6 +143,8 @@ export async function initApp(): Promise<void> {
timeWindow: '1 minute',
});

await registerRealtimeWebSocket(app);

// Local API protection: require token on all /api routes except /api/health.
if (isAuthEnabled()) {
app.addHook('onRequest', async (request, reply) => {
Expand Down Expand Up @@ -227,6 +233,7 @@ export async function start(): Promise<void> {

startFileWatching((eventType, filePath) => {
logger.info(`文件${eventType}: ${filePath}`);
broadcastFileChange(eventType, filePath);
});
const { getAutomationScheduler } = await import('../core/automation-scheduler.js');
getAutomationScheduler().start();
Expand Down
Loading
Loading