FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Kevin/dashboard integration by kevinwang5658 · Pull Request #48 · codifycli/codify · GitHub

Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .json  (2) .ts  (9) All 2 file types selected
Only manifest files
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
1,124 changes: 1,095 additions & 29 deletions package-lock.json

Large diffs are not rendered by default.

22 changes: 17 additions & 5 deletions package.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
"dependencies": {
"@codifycli/ink-form": "0.0.12",
"@homebridge/node-pty-prebuilt-multiarch": "^0.12.0-beta.5",
"@hono/node-server": "^1.17.1",
"@hono/node-ws": "^1.2.0",
"@inkjs/ui": "^2",
"@mischnic/json-sourcemap": "^0.1.1",
"@oclif/core": "^4.0.8",
"@oclif/plugin-autocomplete": "^3.2.24",
"@oclif/plugin-help": "^6.2.4",
Expand All @@ -15,26 +18,31 @@
"ajv-formats": "^3.0.1",
"chalk": "^5.3.0",
"codify-schemas": "^1.0.76",
"cors": "^2.8.5",
"debug": "^4.3.4",
"detect-indent": "^7.0.1",
"diff": "^7.0.0",
"express": "^5.1.0",
"hono": "^4.8.9",
"ink": "^5.1.0",
"ink-big-text": "^2.0.0",
"ink-gradient": "^3.0.0",
"ink-select-input": "^6.0.0",
"jju": "^1.4.0",
"jotai": "^2.11.1",
"js-yaml": "^4.1.0",
"js-yaml-source-map": "^0.2.2",
"json-source-map": "^0.6.1",
"json5": "^2.2.3",
"latest-semver": "^4.0.0",
"nanoid": "^5.0.9",
"open": "^10.1.2",
"parse-json": "^8.1.0",
"react": "^18.3.1",
"semver": "^7.5.4",
"socket.io": "^4.8.1",
"supports-color": "^9.4.0",
"json5": "^2.2.3",
"@mischnic/json-sourcemap": "^0.1.1",
"jju": "^1.4.0"
"ws": "^8.18.3"
},
"description": "Codify allows users to configure settings, install new packages, and automate their systems using code instead of the GUI. Get set up on a new laptop in one click, maintain a Codify file within your project so anyone can get started and never lose your cool apps or favourite settings again.",
"devDependencies": {
Expand All @@ -43,15 +51,18 @@
"@types/chalk": "^2.2.0",
"@types/debug": "^4.1.12",
"@types/diff": "^7.0.1",
"@types/express": "^5.0.3",
"@types/jju": "^1.4.5",
"@types/js-yaml": "^4.0.9",
"@types/json5": "^2.2.0",
"@types/mocha": "^10.0.10",
"@types/node": "^20",
"@types/react": "^18.3.1",
"@types/semver": "^7.5.4",
"@types/strip-ansi": "^5.2.1",
"@types/jju": "^1.4.5",
"@types/uuid": "^10.0.0",
"@types/ws": "^8.18.1",
"@typescript-eslint/eslint-plugin": "^8.16.0",
"@types/json5": "^2.2.0",
"codify-plugin-lib": "^1.0.151",
"esbuild": "^0.24.0",
"esbuild-plugin-copy": "^2.1.1",
Expand All @@ -68,6 +79,7 @@
"strip-ansi": "^7.1.0",
"tsx": "^4.7.3",
"typescript": "5.3.3",
"uuid": "^10.0.0",
"vitest": "^2.1.6"
},
"overrides": {
Expand Down
24 changes: 24 additions & 0 deletions src/commands/connect.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { BaseCommand } from '../common/base-command.js';
import { LoginOrchestrator } from '../orchestrators/login.js';
import { ConnectOrchestrator } from '../orchestrators/connect.js';

export default class Connect extends BaseCommand {
static description =
`Validate a codify.jsonc/codify.json/codify.yaml file.

For more information, visit: https://docs.codifycli.com/commands/validate
`

static flags = {}

static examples = [
'<%= config.bin %> <%= command.id %>',
'<%= config.bin %> <%= command.id %> --path=../../import.codify.jsonc',
]

public async run(): Promise<void> {
const { flags } = await this.parse(Connect)

await ConnectOrchestrator.run();
}
}
23 changes: 23 additions & 0 deletions src/commands/login.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { BaseCommand } from '../common/base-command.js';
import { LoginOrchestrator } from '../orchestrators/login.js';

export default class Login extends BaseCommand {
static description =
`Validate a codify.jsonc/codify.json/codify.yaml file.

For more information, visit: https://docs.codifycli.com/commands/validate
`

static flags = {}

static examples = [
'<%= config.bin %> <%= command.id %>',
'<%= config.bin %> <%= command.id %> --path=../../import.codify.jsonc',
]

public async run(): Promise<void> {
const { flags } = await this.parse(Login)

await LoginOrchestrator.run();
}
}
10 changes: 10 additions & 0 deletions src/config.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export const config = {
loginServerPort: 51_039,
connectServerPort: 51_040,

corsAllowedOrigins: [
'https://codify-dashboard.com',
'https://https://codify-dashboard.kevinwang5658.workers.dev',
'http://localhost:3000'
]
}
51 changes: 51 additions & 0 deletions src/connect/apply.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { spawn } from '@homebridge/node-pty-prebuilt-multiarch';
import * as fs from 'node:fs/promises';
import * as os from 'node:os';
import * as path from 'node:path';
import { v4 as uuid } from 'uuid';
import { WebSocket } from 'ws';

import { WsServerManager } from './server.js';

export function connectApplyInitHandler(msg: any, initWs: WebSocket, manager: WsServerManager) {
const sessionId = uuid();

manager.addAdhocWsServer(sessionId, async (ws) => {
console.log('connected apply ws');

const { config } = msg;
console.log('apply ws open', config);

const tmpDir = await fs.mkdtemp(os.tmpdir());
const filePath = path.join(tmpDir, 'codify.json');

await fs.writeFile(filePath, JSON.stringify(config));

const pty = spawn('zsh', ['-c', 'codify apply'], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.env.HOME,
env: process.env
});

pty.onData((data) => {
ws.send(Buffer.from(data, 'utf8'));
});

ws.on('message', (message) => {
pty.write(message.toString('utf8'));
})

pty.onExit(({ exitCode, signal }) => {
console.log('pty exit', exitCode, signal);
// ws.close(exitCode);
ws.terminate();
})
});

initWs.send(JSON.stringify({
cmd: 'apply_init_response',
sessionId,
}))
}
54 changes: 54 additions & 0 deletions src/connect/http-route-handler.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { spawn } from '@homebridge/node-pty-prebuilt-multiarch';
import { ResourceConfig } from 'codify-schemas';
import { Router } from 'express';
import * as fs from 'node:fs/promises';
import * as os from 'node:os';
import * as path from 'node:path';
import { v4 as uuid } from 'uuid';
import { WebSocket } from 'ws';

import { WsServerManager } from './server.js';

const router = Router({
mergeParams: true,
});

router.post('/apply', (req, res) => {
const sessionId = uuid();
const manager = WsServerManager.get();
const config = req.body;

manager.addAdhocWsServer(sessionId, async (ws: WebSocket) => wsHandler(ws, config));

return res.status(200).json({ sessionId });
});

async function wsHandler(ws: WebSocket, config: ResourceConfig): Promise<void> {
const tmpDir = await fs.mkdtemp(os.tmpdir());
const filePath = path.join(tmpDir, 'codify.json');

await fs.writeFile(filePath, JSON.stringify(config));

const pty = spawn('zsh', ['-c', 'codify apply'], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.env.HOME,
env: process.env
});

pty.onData((data) => {
ws.send(Buffer.from(data, 'utf8'));
});

ws.on('message', (message) => {
pty.write(message.toString('utf8'));
})

pty.onExit(({ exitCode, signal }) => {
console.log('pty exit', exitCode, signal);
ws.terminate();
})
}

export default router;
99 changes: 99 additions & 0 deletions src/connect/server.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { IncomingMessage, Server, createServer } from 'node:http';
import { Duplex } from 'node:stream';
import { v4 as uuid } from 'uuid';
import { WebSocket, WebSocketServer } from 'ws';
import { config } from '../config.js';

let instance: WsServerManager | undefined;

export class WsServerManager {

server: Server;
port?: number;

private wsServerMap = new Map<string, WebSocketServer>();
private handlerMap = new Map<string, (ws: WebSocket, manager: WsServerManager, request: IncomingMessage) => void>();

private connectionSecret;

static init(server: Server, connectionSecret?: string): WsServerManager {
instance = new WsServerManager(server, connectionSecret);
return instance;
}

static get(): WsServerManager {
if (!instance) {
throw new Error('You must call WsServerManager.init before using it');
}

return instance;
}

private constructor(server: Server, connectionSecret?: string) {
this.server = server
this.connectionSecret = connectionSecret;
this.wsServerMap.set('default', this.createWssServer());

this.server.on('upgrade', this.onUpgrade)
}

setDefaultHandler(handler: (ws: WebSocket, manager: WsServerManager) => void): WsServerManager {
const wss = this.createWssServer();
this.wsServerMap.set('default', wss);
this.handlerMap.set('default', handler);

return this;
}

addAdhocWsServer(sessionId: string, handler: (ws: WebSocket, manager: WsServerManager) => void) {
this.wsServerMap.set(sessionId, this.createWssServer());
this.handlerMap.set(sessionId, handler);
}

private onUpgrade = (request: IncomingMessage, socket: Duplex, head: Buffer): void => {
const { pathname } = new URL(request.url!, 'ws://localhost:51040')

if (!this.validateOrigin(request.headers.origin!)
|| this.validateConnectionSecret(request)) {
console.error('Unauthorized request from', request.headers.origin);
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n')
socket.destroy();
return;
}

if (pathname === '/ws' && this.handlerMap.has('default')) {
const wss = this.wsServerMap.get('default');
wss?.handleUpgrade(request, socket, head, (ws, request) => this.handlerMap.get('default')!(ws, this, request));
return;
}

const pathSections = pathname.split('/').filter(Boolean);
if (
pathSections[0] === 'ws'
&& pathSections[1] === 'session'
&& pathSections[2]
&& this.handlerMap.has(pathSections[2])
) {
const sessionId = pathSections[2];
console.log('session found, upgrading', sessionId);

const wss = this.wsServerMap.get(sessionId)!;

wss.handleUpgrade(request, socket, head, (ws, request) => this.handlerMap.get(sessionId)!(ws, this, request));
}
}

private validateOrigin = (origin: string): boolean =>
config.corsAllowedOrigins.includes(origin)

private validateConnectionSecret = (request: IncomingMessage): boolean => {
const connectionSecret = request.headers['connection-secret'] as string;
return connectionSecret === this.connectionSecret;
}

private createWssServer(): WebSocketServer {
return new WebSocketServer({
noServer: true,
})
}
}
35 changes: 35 additions & 0 deletions src/connect/ws-route-handler.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { WebSocket } from 'ws';

import { connectApplyInitHandler } from './apply.js';
import { WsServerManager } from './server.js';

export async function defaultWsHandler(ws: WebSocket, manager: WsServerManager) {
console.log('[WS] Connection opened');

ws.on('message', (message) => {
let msg;
try {
msg = JSON.parse(message.toString('utf8'));
console.log(msg);
} catch (error) {
console.error(error);
return;
}

const { cmd } = msg;
if (!cmd) {
console.error('No cmd found');
return;
}

switch (cmd) {
case 'apply_init': {
connectApplyInitHandler(msg, ws, manager);
break;
}
}

})
}


Loading
Loading

Back | FazBrowse Home | New Git URL