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
1,134 changes: 966 additions & 168 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@
"main": "build/index.js",
"dependencies": {
"@colony/core": "^2.0.1",
"@graphql-tools/executor-http": "^3.0.7",
"@graphql-tools/wrap": "^11.1.2",
"cors": "^2.8.5",
"express": "^4.18.2",
"express-session": "^1.17.3",
"http-proxy-middleware": "^2.0.6",
"graphql-middleware": "^6.1.35",
"graphql-shield": "^7.6.5",
"node-fetch": "2.6",
"siwe": "^2.1.4",
"ws": "^8.16.0"
Expand All @@ -27,7 +30,7 @@
"ts-node": "^10.9.1",
"tsc-alias": "^1.8.8",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.2.2"
"typescript": "^5.9.3"
},
"scripts": {
"dev": "NODE_ENV=dev nodemon",
Expand Down
15 changes: 0 additions & 15 deletions src/RequestError.ts

This file was deleted.

164 changes: 62 additions & 102 deletions src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { parse } from 'graphql';
import dotenv from "dotenv";
import dotenv from 'dotenv';
import { default as fetch, Request as NodeFetchRequst } from 'node-fetch';

import { Response as ExpressResponse, Request } from 'express-serve-static-core';
import { RequestError } from './RequestError';
import {
OperationTypes,
Response as ExpressResponse,
Request,
} from 'express-serve-static-core';
import {
StaticOriginCallback,
HttpStatuses,
Response,
ApiResponse,
Headers,
ContentTypes,
ServerMethods,
Expand All @@ -20,58 +20,21 @@ const BLOCK_TIME = Number(process.env.DEFAULT_BLOCK_TIME) * 1000 || 5000;

export const isDevMode = (): boolean => process.env.NODE_ENV !== 'prod';

export const detectOperation = (body: Record<string, any>): {
operationType: OperationTypes,
operations: string[],
variables?: string,
} => {
let isMutation = false;

if (!body) {
throw new RequestError('no body');
}
if (!body?.query) {
throw new RequestError('graphql request malformed');
}

if (JSON.stringify(body).includes(OperationTypes.Mutation)) {
isMutation = true;
}

let parsedQuery: any;
try {
parsedQuery = parse(body.query);
} catch (error) {
// silent
}

if (!parsedQuery) {
throw new RequestError('graphql request malformed');
}

const [{ operation: operationType }] = parsedQuery.definitions || [{}];
if (operationType === OperationTypes.Mutation) {
isMutation = true;
}

const operationNames = parsedQuery.definitions[0].selectionSet.selections.map(
(selection: any) => selection.name.value,
);

return {
operationType: isMutation ? OperationTypes.Mutation : OperationTypes.Query,
operations: operationNames,
variables: body.variables ? JSON.stringify(body.variables) : undefined,
};
};

export const getStaticOrigin = (origin?: string, callback?: StaticOriginCallback): string | undefined => {
export const getStaticOrigin = (
origin?: string,
callback?: StaticOriginCallback,
): string | undefined => {
let isAllowedOrigin = false;
if (isDevMode()) {
if (origin?.includes('http://localhost') || origin?.includes('https://localhost') || origin?.includes('http://127') || origin?.includes('https://127')) {
if (
origin?.includes('http://localhost') ||
origin?.includes('https://localhost') ||
origin?.includes('http://127') ||
origin?.includes('https://127')
) {
isAllowedOrigin = true;
}
};
}
if (origin === process.env.ORIGIN_URL) {
isAllowedOrigin = true;
}
Expand All @@ -84,23 +47,27 @@ export const getStaticOrigin = (origin?: string, callback?: StaticOriginCallback
export const sendResponse = (
response: ExpressResponse,
request: Request,
message?: Response,
message?: ApiResponse,
status: HttpStatuses = HttpStatuses.OK,
) => response.set({
[Headers.AllowOrigin]: getStaticOrigin(request.headers.origin),
[Headers.ContentType]: ContentTypes.Json,
[Headers.PoweredBy]: 'Colony',
}).status(status).json(message);
) =>
response
.set({
[Headers.AllowOrigin]: getStaticOrigin(request.headers.origin),
[Headers.ContentType]: ContentTypes.Json,
[Headers.PoweredBy]: 'Colony',
})
.status(status)
.json(message);

export const getRemoteIpAddress = (request: Request): string =>
typeof request.headers[Headers.ForwardedFor] === 'string'
? request.headers[Headers.ForwardedFor]
: request.headers[Headers.ForwardedFor]?.join(';') ||
request.ip ||
request.ips.join(';') ||
request.connection.remoteAddress ||
request.socket.remoteAddress ||
'';
request.ip ||
request.ips.join(';') ||
request.connection.remoteAddress ||
request.socket.remoteAddress ||
'';

export const resetSession = (request: Request): void => {
request.session.auth = undefined;
Expand All @@ -117,14 +84,21 @@ export const logger = (...args: any[]): void => {

export const graphqlRequest = async (
queryOrMutation: string,
variables?: Record<string, any>
variables?: Record<string, unknown>,
walletAddress?: string,
) => {
const headers: Record<string, string> = {
[Headers.ApiKey]: process.env.APPSYNC_API_KEY || '',
[Headers.ContentType]: ContentTypes.Json,
};

if (walletAddress) {
headers[Headers.WalletAddress] = walletAddress;
}

const options = {
method: ServerMethods.Post.toUpperCase(),
headers: {
[Headers.ApiKey]: process.env.APPSYNC_API_KEY || '',
[Headers.ContentType]: ContentTypes.Json,
},
headers,
body: JSON.stringify({
query: queryOrMutation,
variables,
Expand All @@ -133,12 +107,9 @@ export const graphqlRequest = async (

const request = new NodeFetchRequst(process.env.APPSYNC_API || '', options);

let body;
let response;

try {
response = await fetch(request);
body = await response.json();
const response = await fetch(request);
const body = await response.json();
return body;
} catch (error) {
/*
Expand All @@ -149,37 +120,26 @@ export const graphqlRequest = async (
}
};

export const delay = async (timeout: number) => {
return new Promise(resolve => {
setTimeout(resolve, timeout);
});
}
const MAX_RETRIES = 3;

export const tryFetchGraphqlQuery = async (
queryOrMutation: string,
variables?: Record<string, any>,
maxRetries: number = 3,
blockTime: number = BLOCK_TIME
) => {
let currentTry = 0;
while (true) {
const result = await graphqlRequest(queryOrMutation, variables);
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

/*
* @NOTE That this limits to only fetching one operation at a time
*/
export const fetchWithRetry = async <T>(
query: string,
variables: Record<string, unknown>,
): Promise<T | null> => {
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
const result = await graphqlRequest(query, variables);
if (result?.data) {
const { data } = result;
if (data[Object.keys(data)[0]]) {
return data[Object.keys(data)[0]];
const data = result.data;
const value = data[Object.keys(data)[0]];
if (value) {
return value as T;
}
}

if (currentTry < maxRetries) {
await delay(blockTime);
currentTry += 1;
} else {
throw new Error('Could not fetch graphql data in time');
if (attempt < MAX_RETRIES) {
await delay(BLOCK_TIME);
}
}
}
return null;
};
32 changes: 22 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
import dotenv from "dotenv";
import dotenv from 'dotenv';

import proxyServerInstance from './server';
import { handleWsUpgrade } from './routes/graphql/ws';
import { initSchema } from './schema';

dotenv.config();

const port = process.env.DEFAULT_PORT || 3005;
const proxy = proxyServerInstance();

const server = proxy.listen(port, () => {
/*
* @NOTE Use console log here as to ensure it will always be logged
*/
console.log(`Authentication proxy listening on port ${port}`);
});
(async () => {
try {
await initSchema();
console.log('GraphQL schema loaded successfully');
} catch (error) {
console.error('Failed to load GraphQL schema:', error);
process.exit(1);
}

// Custom websocker upgrade proxy handler
server.on('upgrade', handleWsUpgrade)
const proxy = proxyServerInstance();

const server = proxy.listen(port, () => {
/*
* @NOTE Use console log here as to ensure it will always be logged
*/
console.log(`Authentication proxy listening on port ${port}`);
});

// Custom websocker upgrade proxy handler
server.on('upgrade', handleWsUpgrade);
})();
Loading
Loading