Skip to content
Open
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
2 changes: 1 addition & 1 deletion .github/workflows/pull-request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ jobs:
- name: Use Node.js
uses: actions/setup-node@v4
with:
node-version: v22.21.0
node-version: v22.22.0
cache: 'npm'
cache-dependency-path: '**/package-lock.json'

Expand Down
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:21.1.0-alpine AS packages
FROM node:22.22.0-alpine AS packages
WORKDIR /usr/src/app

COPY LICENSE /usr/src/app/
Expand Down
3,595 changes: 2,093 additions & 1,502 deletions package-lock.json

Large diffs are not rendered by default.

47 changes: 23 additions & 24 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "jetkvm-cloud-api",
"version": "1.0.0",
"version": "2026.01.29.0845",
"description": "JetKVM Cloud API and Websocket Server",
"main": "dist/src/index.js",
"scripts": {
Expand All @@ -16,45 +16,44 @@
"test:coverage": "vitest run --coverage"
},
"engines": {
"node": "22.x"
"node": "^22.22.0"
},
"keywords": [],
"author": "JetKVM",
"license": "GPL-2.0",
"dependencies": {
"@aws-sdk/client-s3": "^3.654.0",
"@prisma/client": "^5.13.0",
"@tsconfig/node22": "^22.0.0",
"@aws-sdk/client-s3": "^3.978.0",
"@prisma/client": "^6.19.2",
"@tsconfig/node22": "^22.0.5",
"@types/cookie-session": "^2.0.49",
"@types/cors": "^2.8.17",
"@types/node": "^20.12.10",
"@types/ws": "^8.5.10",
"cookie-session": "^2.1.0",
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"express": "^5",
"helmet": "^7.1.0",
"http-proxy-middleware": "^3.0.3",
"jose": "^5.2.4",
"lru-cache": "^11.2.2",
"openid-client": "^5.6.5",
"prisma": "^5.13.0",
"semver": "^7.6.3",
"@types/cors": "^2.8.19",
"@types/node": "^25.1.0",
"@types/ws": "^8.18.1",
"cookie-session": "^2.1.1",
"cors": "^2.8.6",
"dotenv": "^17.2.3",
"express": "^5.2.1",
"helmet": "^8.1.0",
"http-proxy-middleware": "^3.0.5",
"jose": "^6.1.3",
"lru-cache": "^11.2.5",
"openid-client": "^6.8.1",
"prisma": "^6.19.2",
"semver": "^7.7.3",
"ts-node": "^10.9.2",
"typescript": "^5.4.5",
"ws": "^8.17.1",
"typescript": "^5.9.3",
"ws": "^8.19.0",
"zod": "^4.3.6"
},
"optionalDependencies": {
"bufferutil": "^4.0.8"
},
"devDependencies": {
"@types/express": "^5.0.6",
"@types/lru-cache": "^7.10.9",
"@types/semver": "^7.5.8",
"@types/semver": "^7.7.1",
"@vitest/coverage-v8": "^4.0.18",
"aws-sdk-client-mock": "^4.1.0",
"prettier": "3.2.5",
"prettier": "3.8.1",
"vitest": "^4.0.18"
}
}
9 changes: 9 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ model User {
picture String?
device Device[]
Activity TurnActivity[]

@@index([googleId], type: Hash)
}

model Device {
Expand All @@ -31,6 +33,10 @@ model Device {
tempToken String?
tempTokenExpiresAt DateTime?
secretToken String? @unique

@@index([userId], type: Hash)
@@index([tempToken], type: Hash)
@@index([secretToken], type: Hash)
}

model TurnActivity {
Expand All @@ -40,6 +46,8 @@ model TurnActivity {
createdAt DateTime? @default(now()) @db.Timestamp(6)
bytesSent Int
bytesReceived Int

@@index([userId], type: Hash)
}

model Release {
Expand All @@ -53,4 +61,5 @@ model Release {
hash String

@@unique([version, type])
@@index([type, rolloutPercentage])
}
53 changes: 33 additions & 20 deletions src/auth.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,50 @@
import { type NextFunction, type Request, type Response } from "express";
import * as jose from "jose";
import { UnauthorizedError } from "./errors";

import { BadRequestError, UnauthorizedError } from "./errors";

const JWKS_URL = new URL("https://www.googleapis.com/oauth2/v3/certs")
const JWKS = jose.createRemoteJWKSet(JWKS_URL);
const verificationOptions = {
//algorithms: ['RS256'],
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The example shows S256 but really should be RS256... until I can test I can't be sure which is right.

issuer: "https://accounts.google.com",
audience: process.env.GOOGLE_CLIENT_ID,
};

export const verifyToken = async (idToken: string) => {
const JWKS = jose.createRemoteJWKSet(
new URL("https://www.googleapis.com/oauth2/v3/certs"),
);

try {
const { payload } = await jose.jwtVerify(idToken, JWKS, {
issuer: "https://accounts.google.com",
audience: process.env.GOOGLE_CLIENT_ID,
});

const { payload } = await jose.jwtVerify(idToken, JWKS, verificationOptions);
console.log('JWT Payload:', payload);
return payload;
} catch (e) {
console.error(e);
} catch (error: any) {
console.error('JWT Verification Failed:', error.message);
return null;
}
};

export const authenticated = async (req: Request, res: Response, next: NextFunction) => {
const idToken = req.session?.id_token;
if (!idToken) throw new UnauthorizedError();
const session = req.session;
if (!session) throw new UnauthorizedError("No session found");

const idToken = session.id_token;
if (!idToken) throw new UnauthorizedError("No ID token found in session");

const payload = await verifyToken(idToken);
if (!payload) throw new UnauthorizedError();
if (!payload.exp) throw new UnauthorizedError();
if (!payload) throw new UnauthorizedError("Invalid ID token");

if (new Date(payload.exp * 1000) < new Date()) {
throw new UnauthorizedError();
const { sub, iss, exp } = payload;
if (!sub) throw new UnauthorizedError("Missing sub (subject) in token");
if (!iss) throw new UnauthorizedError("Missing iss (issuer) in token");
if (!exp) throw new UnauthorizedError("Missing exp (expiration) in token");

if (new Date(payload.exp! * 1000) < new Date()) {
throw new UnauthorizedError("ID token has expired");
}

const isGoogle = iss === "https://accounts.google.com";
if (!isGoogle) throw new BadRequestError("Token is not from Google");

req.subject = sub;
req.issuer = iss;

next();
};
};
1 change: 0 additions & 1 deletion src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ if (process.env.NODE_ENV !== "development") {
prismaClient = global.__db;
}


// Have to cast it manually, because webstorm can't infer it for some reason
// https://github.com/prisma/prisma/issues/2359#issuecomment-963340538
export const prisma = prismaClient;
68 changes: 30 additions & 38 deletions src/devices.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as jose from "jose";
import { prisma } from "./db";
import express from "express";
import {
Expand All @@ -12,45 +11,40 @@ import { authenticated } from "./auth";
import { activeConnections } from "./webrtc-signaling";

export const List = async (req: express.Request, res: express.Response) => {
const idToken = req.session?.id_token;
const { iss, sub } = jose.decodeJwt(idToken);

// Authorization server’s identifier for the user
const isGoogle = iss === "https://accounts.google.com";
if (isGoogle) {
const devices = await prisma.device.findMany({
where: { user: { googleId: sub } },
select: { id: true, name: true, lastSeen: true },
});
const { subject } = req;
if (!subject) throw new UnauthorizedError("Missing subject in token");

return res.json({
devices: devices.map(device => {
const activeDevice = activeConnections.get(device.id);
const version = activeDevice?.[2] || null;

return {
...device,
online: !!activeDevice,
version,
};
}),
});
} else {
throw new BadRequestError("Token is not from Google");
}
const devices = await prisma.device.findMany({
where: { user: { googleId: subject } },
select: { id: true, name: true, lastSeen: true },
});

return res.json({
devices: devices.map(device => {
const activeDevice = activeConnections.get(device.id);
const version = activeDevice?.[2] || null;

return {
...device,
online: !!activeDevice,
version,
};
}),
});
};

export const Retrieve = async (
req: express.Request<{ id: string }>,
res: express.Response
) => {
const idToken = req.session?.id_token;
const { sub } = jose.decodeJwt(idToken);
const { subject } = req;
if (!subject) throw new UnauthorizedError("Missing subject in token");

const { id } = req.params;
if (!id) throw new UnprocessableEntityError("Missing device id in params");

const device = await prisma.device.findUnique({
where: { id, user: { googleId: sub } },
where: { id, user: { googleId: subject } },
select: { id: true, name: true, user: { select: { googleId: true } } },
});

Expand All @@ -62,18 +56,17 @@ export const Update = async (
req: express.Request<{ id: string }>,
res: express.Response
) => {
const idToken = req.session?.id_token;
const { sub } = jose.decodeJwt(idToken);
if (!sub) throw new UnauthorizedError("Missing sub in token");
const { subject } = req;
if (!subject) throw new UnauthorizedError("Missing subject in token");

const { id } = req.params;
if (!id) throw new UnprocessableEntityError("Missing device id in params");

const { name } = req.body as { name: string };
if (!name) throw new UnprocessableEntityError("Missing name in body");
if (!name) throw new UnprocessableEntityError("Missing device name in body");

const device = await prisma.device.update({
where: { id, user: { googleId: sub } },
where: { id, user: { googleId: subject } },
data: { name },
select: { id: true },
});
Expand Down Expand Up @@ -125,14 +118,13 @@ export const Delete = async (
throw new BadRequestError("Unauthorized");
}

const idToken = req.session?.id_token;
const { sub } = jose.decodeJwt(idToken);
if (!sub) throw new UnauthorizedError("Missing sub in token");
const { subject } = req;
if (!subject) throw new UnauthorizedError("Missing subject in token");

const { id } = req.params;
if (!id) throw new UnprocessableEntityError("Missing device id in params");

await prisma.device.delete({ where: { id, user: { googleId: sub } } });
await prisma.device.delete({ where: { id, user: { googleId: subject } } });

// We just removed the device, so we should close any running open socket connections
const conn = activeConnections.get(id);
Expand Down
24 changes: 9 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import express from "express";
import cors from "cors";
import cookieSession from "cookie-session";
import * as jose from "jose";
import helmet from "helmet";
import 'dotenv/config';

Expand Down Expand Up @@ -97,26 +96,25 @@ app.get(
"/me",
authenticated,
async (req: express.Request, res: express.Response) => {
const idToken = req.session?.id_token;
const { sub, iss, exp, aud, iat, jti, nbf } = jose.decodeJwt(idToken);
const { subject, issuer } = req;
if (!subject || !issuer) {
return res.status(401).json({ message: "Unauthorized" });
}

let user;
if (iss === "https://accounts.google.com") {
if (issuer === "https://accounts.google.com") {
user = await prisma.user.findUnique({
where: { googleId: sub },
where: { googleId: subject },
select: { picture: true, email: true },
});
}

return res.json({ ...user, sub });
return res.json({ ...user, subject });
},
);

app.get("/releases", Releases.Retrieve);
app.get(
"/releases/system_recovery/latest",
Releases.RetrieveLatestSystemRecovery,
);
app.get("/releases/system_recovery/latest", Releases.RetrieveLatestSystemRecovery);
app.get("/releases/app/latest", Releases.RetrieveLatestApp);

app.get("/devices", authenticated, Devices.List);
Expand All @@ -127,11 +125,7 @@ app.delete("/devices/:id", Devices.Delete);

app.post("/webrtc/session", authenticated, Webrtc.CreateSession);
app.post("/webrtc/ice_config", authenticated, Webrtc.CreateIceCredentials);
app.post(
"/webrtc/turn_activity",
authenticated,
Webrtc.CreateTurnActivity,
);
app.post("/webrtc/turn_activity", authenticated, Webrtc.CreateTurnActivity);

app.post("/oidc/google", OIDC.Google);
app.get("/oidc/callback_o", OIDC.Callback);
Expand Down
Loading