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 bin/server
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import optimist from 'optimist';
import log from 'book';
import Debug from 'debug';

import CreateServer from '../server';
import CreateServer from '../server.js';

const debug = Debug('localtunnel');

Expand Down
2 changes: 1 addition & 1 deletion lib/Client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Duplex } from 'stream';
import WebSocket from 'ws';
import net from 'net';

import Client from './Client';
import Client from './Client.js';

class DummySocket extends Duplex {
constructor(options) {
Expand Down
4 changes: 2 additions & 2 deletions lib/ClientManager.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { hri } from 'human-readable-ids';
import Debug from 'debug';

import Client from './Client';
import TunnelAgent from './TunnelAgent';
import Client from './Client.js';
import TunnelAgent from './TunnelAgent.js';

// Manage sets of clients
//
Expand Down
2 changes: 1 addition & 1 deletion lib/ClientManager.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import assert from 'assert';
import net from 'net';

import ClientManager from './ClientManager';
import ClientManager from './ClientManager.js';

describe('ClientManager', () => {
it('should construct with no tunnels', () => {
Expand Down
2 changes: 1 addition & 1 deletion lib/TunnelAgent.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import http from 'http';
import net from 'net';
import assert from 'assert';

import TunnelAgent from './TunnelAgent';
import TunnelAgent from './TunnelAgent.js';

describe('TunnelAgent', () => {
it('should create an empty agent', async () => {
Expand Down
37 changes: 37 additions & 0 deletions lib/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { initializeApp, applicationDefault, cert } from 'firebase-admin/app';
import { getAuth } from 'firebase-admin/auth';
import crypto from 'crypto';
import { getDb } from './db.js';

let firebaseAuth;
if (process.env.FIREBASE_SERVICE_ACCOUNT) {
const config = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT);
initializeApp({ credential: cert(config) });
firebaseAuth = getAuth();
} else if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
initializeApp({ credential: applicationDefault() });
firebaseAuth = getAuth();
}

export async function loginWithFirebase(idToken) {
if (!firebaseAuth) {
throw new Error('Firebase not configured');
}
const decoded = await firebaseAuth.verifyIdToken(idToken);
const db = await getDb();
if (!db) {
throw new Error('MongoDB not configured');
}
const token = crypto.randomBytes(20).toString('hex');
await db.collection('tokens').insertOne({ uid: decoded.uid, token });
return token;
}

export async function verifyTunnelToken(token) {
const db = await getDb();
if (!db) {
return true;
}
const entry = await db.collection('tokens').findOne({ token });
return !!entry;
}
15 changes: 15 additions & 0 deletions lib/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { MongoClient } from 'mongodb';

let client;

export async function getDb() {
const uri = process.env.MONGODB_URI;
if (!uri) {
return null;
}
if (!client) {
client = new MongoClient(uri);
await client.connect();
}
return client.db();
}
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,18 @@
"type": "git",
"url": "git://github.com/localtunnel/server.git"
},
"type": "module",
"dependencies": {
"book": "1.3.3",
"debug": "3.1.0",
"esm": "3.0.34",
"firebase-admin": "^11.11.1",
"human-readable-ids": "1.0.3",
"koa": "2.5.1",
"koa-bodyparser": "^4.4.1",
"koa-router": "7.4.0",
"localenv": "0.2.2",
"mongodb": "^5.7.0",
"optimist": "0.6.1",
"pump": "3.0.0",
"tldjs": "2.3.1"
Expand All @@ -27,7 +31,7 @@
"ws": "5.1.1"
},
"scripts": {
"test": "mocha --check-leaks --require esm './**/*.test.js'",
"test": "mocha --check-leaks --require esm 'server.test.js' 'lib/*.test.js'",
"start": "./bin/server",
"dev": "node-dev bin/server --port 3000"
}
Expand Down
38 changes: 37 additions & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ import Debug from 'debug';
import http from 'http';
import { hri } from 'human-readable-ids';
import Router from 'koa-router';
import bodyParser from 'koa-bodyparser';

import ClientManager from './lib/ClientManager';
import { loginWithFirebase, verifyTunnelToken } from './lib/auth.js';

import ClientManager from './lib/ClientManager.js';

const debug = Debug('localtunnel:server');

Expand All @@ -27,6 +30,7 @@ export default function(opt) {

const app = new Koa();
const router = new Router();
app.use(bodyParser());

router.get('/api/status', async (ctx, next) => {
const stats = manager.stats;
Expand All @@ -36,6 +40,21 @@ export default function(opt) {
};
});

router.post('/api/login', async (ctx) => {
const idToken = ctx.request.body && ctx.request.body.idToken;
if (!idToken) {
ctx.throw(400, 'idToken required');
return;
}
try {
const token = await loginWithFirebase(idToken);
ctx.body = { token };
} catch (err) {
ctx.status = 401;
ctx.body = { message: err.message };
}
});

router.get('/api/tunnels/:id/status', async (ctx, next) => {
const clientId = ctx.params.id;
const client = manager.getClient(clientId);
Expand Down Expand Up @@ -65,6 +84,14 @@ export default function(opt) {

const isNewClientRequest = ctx.query['new'] !== undefined;
if (isNewClientRequest) {
const authToken = ctx.headers['authorization'] && ctx.headers['authorization'].startsWith('Bearer ')
? ctx.headers['authorization'].slice(7)
: ctx.query['token'];
const valid = await verifyTunnelToken(authToken);
if (!valid) {
ctx.throw(401, 'invalid token');
return;
}
const reqId = hri.random();
debug('making new client with id %s', reqId);
const info = await manager.newClient(reqId);
Expand Down Expand Up @@ -92,6 +119,15 @@ export default function(opt) {
return;
}

const authToken = ctx.headers['authorization'] && ctx.headers['authorization'].startsWith('Bearer ')
? ctx.headers['authorization'].slice(7)
: ctx.query['token'];
const validToken = await verifyTunnelToken(authToken);
if (!validToken) {
ctx.throw(401, 'invalid token');
return;
}

const reqId = parts[1];

// limit requested hostnames to 63 characters
Expand Down
4 changes: 2 additions & 2 deletions server.test.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import request from 'supertest';
import assert from 'assert';
import { Server as WebSocketServer } from 'ws';
import WebSocket from 'ws';
const WebSocketServer = WebSocket.Server;
import net from 'net';

import createServer from './server';
import createServer from './server.js';

describe('Server', () => {
it('server starts and stops', async () => {
Expand Down