Skip to content

Commit

Permalink
ench: add hpx token authentication;
Browse files Browse the repository at this point in the history
ench: improve external pixie thumbnail fetching;
  • Loading branch information
twiddli committed May 5, 2023
1 parent 78e6dfb commit 6b42ac2
Show file tree
Hide file tree
Showing 9 changed files with 200 additions and 52 deletions.
19 changes: 19 additions & 0 deletions packages/client/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,17 @@ Object.entries(process.env).forEach(([key, value]) => {
`> Using HPX server port ${value} from HPX_SERVER_PORT environment variable`
);
}

if (key === 'HPX_DEV' && value.toLowerCase() === 'true') {
console.log(`> Setting NODE_ENV=development`);
process.env.NODE_ENV = 'development';
}

if (key === 'PUBLIC_DOMAIN_URL') {
console.log(
`> Using PUBLIC_DOMAIN_URL ${value} from PUBLIC_DOMAIN_URL environment variable`
);
}
});

if (cwd) {
Expand All @@ -118,6 +129,14 @@ if (cliPort) {
port = parseInt(cliPort, 10);
}

if (!process.env.PUBLIC_DOMAIN_URL) {
process.env.PUBLIC_DOMAIN_URL = `http://${hostname}:${port}`;

console.log(
`> Setting PUBLIC_DOMAIN_URL to ${process.env.PUBLIC_DOMAIN_URL} (from hostname and port)`
);
}

// Make sure commands gracefully respect termination signals (e.g. from Docker)
// Allow the graceful termination to be manually configurable
if (!process.env.NEXT_MANUAL_SIG_HANDLE) {
Expand Down
16 changes: 14 additions & 2 deletions packages/client/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { queryClient } from '../client/queries';
import { LoginModal } from '../components/Login';
import {
DISABLE_SERVER_CONNECT,
HPX_INSTANCE_TOKEN,
HPX_SERVER_HOST,
HPX_SERVER_PORT,
IS_SERVER,
Expand Down Expand Up @@ -310,7 +311,14 @@ HappyPandaApp.getInitialProps = async function (
}
}

if (!loggedIn && !['/login', '/_error'].includes(context.router.pathname)) {
let bypass =
context.ctx.req.headers?.['x-hpx-token'] === HPX_INSTANCE_TOKEN;

if (
!bypass &&
!loggedIn &&
!['/login', '/_error'].includes(context.router.pathname)
) {
return redirect({
location: `/login?next=${encodeURIComponent(context.router.asPath)}`,
ctx: context.ctx,
Expand All @@ -321,7 +329,11 @@ HappyPandaApp.getInitialProps = async function (
let propsData: AppPageProps['pageProps'] = {
disableServerConnect,
serverHost,
packageJson,
packageJson:
context.router.pathname.startsWith('/api') ||
['/404'].includes(context.router.pathname)
? {}
: packageJson,
serverPort,
pathname,
loggedIn,
Expand Down
60 changes: 50 additions & 10 deletions packages/client/pages/api/server/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import axios from 'axios';
import { fileTypeFromBuffer, fileTypeFromFile } from 'file-type';
import { createReadStream, existsSync } from 'fs';
import path from 'path';
Expand Down Expand Up @@ -57,19 +58,20 @@ async function imageFromPath(path_type, req, res) {
}
}

let LOCAL: boolean | undefined = undefined;

export function createImageHandler(path_type: string) {
return handler().get(async (req, res) => {
const { t, ...rest } = req.query;
if (LOCAL === undefined) {
const pixie = await getPixie();
LOCAL = pixie.isLocal;
const pixie = await getPixie(false);

if (!pixie.isHPXInstanced) {
const token = req.headers?.['x-hpx-token'];
if (token != pixie.HPXToken) {
return res.status(404).end("Momo: invalid token!");
}
}

if (t && Object.keys(rest ?? {}).length) {
if (!LOCAL || t === 'g' || (rest?.l1 && rest?.l2 && rest?.l3)) {
const pixie = await getPixie();
if (pixie.isLocal && pixie.connected && t && Object.keys(rest ?? {}).length) {
if (t === 'g' || (rest?.l1 && rest?.l2 && rest?.l3)) {
try {
const b = await pixie.image({ t, ...(rest as any) });
if (b.data && Buffer.isBuffer(b.data)) {
Expand Down Expand Up @@ -100,9 +102,47 @@ export function createImageHandler(path_type: string) {
} else {
return await imageFromPath(path_type, req, res);
}
} else {
return res.status(404).end(errTxt);
}

if (!pixie.isHPXInstanced && pixie.webserver_endpoint) {

// forward
const url = pixie.webserver_endpoint + req.url

try {
const r = await axios(url, {
responseType: "stream",
method: req.method ?? 'GET',
headers: {
'x-hpx-token': pixie.HPXToken,
}
});


const type = r.headers['content-type'];
if (type) {
res.setHeader('Content-Type', type);
}

r.data.on('error', function (e) {
if (process.env.NODE_ENV === 'development') {
throw e;
}
return res.status(404).end(errTxt);
});

r.data.pipe(res)

return;
} catch (err) {
if (process.env.NODE_ENV === 'development') {
throw err;
}
return res.status(404).end(errTxt);
}
}

return res.status(404).end(errTxt);
});
}

Expand Down
6 changes: 5 additions & 1 deletion packages/client/server/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,15 @@ export const DISABLE_SERVER_CONNECT = ['true', '1'].includes(
process.env?.HPX_DISABLE_SERVER_CONNECT?.toLocaleLowerCase?.()
);

export const HPX_INSTANCE_TOKEN = process.env.HPX_INSTANCE_TOKEN
? process.env.HPX_INSTANCE_TOKEN
: '';

export const HPX_SECRET = process.env.HPX_SECRET
? process.env.HPX_SECRET
: 'secret';

export const DOMAIN_URL = process.env.PUBLIC_DOMAIN_URL
export const HPX_DOMAIN_URL = process.env.PUBLIC_DOMAIN_URL
? process.env.PUBLIC_DOMAIN_URL
: 'http://localhost:7008';

Expand Down
2 changes: 1 addition & 1 deletion packages/client/server/initialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { getServerSession } from './requests';

export async function serverInitialize() {
global.app = global?.app ?? ({} as any);
global.app.log = setupLogger();
global.app.log = setupLogger({});
try {
global.app.getServerSession = getServerSession;
global.app.IS_SERVER = true;
Expand Down
6 changes: 3 additions & 3 deletions packages/client/server/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { MomoActions, MomoType, QueryActions } from '../shared/query';
import { urlparse, urlstring } from '../shared/utility';
import {
DISABLE_SERVER_CONNECT,
DOMAIN_URL,
HPX_DOMAIN_URL,
HPX_SECRET,
HPX_SERVER_HOST,
HPX_SERVER_PORT,
Expand Down Expand Up @@ -140,7 +140,7 @@ export async function fetchQuery<
headers['Content-Type'] = 'application/json';
}

const url = urlstring(DOMAIN_URL + endpoint, params as any);
const url = urlstring(HPX_DOMAIN_URL + endpoint, params as any);

const cfg: RequestInit = {
method,
Expand Down Expand Up @@ -268,7 +268,7 @@ export const nextAuthOptions: NextAuthOptions = {
return true;
},
async redirect({ url, baseUrl }) {
return DOMAIN_URL;
return HPX_DOMAIN_URL;
},
async session({ session, token, user }) {
return session;
Expand Down

0 comments on commit 6b42ac2

Please sign in to comment.