Skip to content

Commit

Permalink
Merge pull request #30 from irensaltali/develop
Browse files Browse the repository at this point in the history
Version 0.0.2
  • Loading branch information
irensaltali authored Jan 27, 2024
2 parents f562098 + 83ab7f8 commit b7a3050
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 50 deletions.
18 changes: 9 additions & 9 deletions worker/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion worker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@
"devDependencies": {
"@cloudflare/workers-types": "^4.20240117.0",
"typescript": "^5.0.4",
"wrangler": "^3.0.0"
"wrangler": "^3.25.0"
}
}
24 changes: 12 additions & 12 deletions worker/src/api-config.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
"description": "Configuration for the Serverless API Gateway",
"servers": [
{
"alias": "ngrok",
"url": "https://a8ee-176-88-98-23.ngrok-free.app"
"alias": "serverlessapigateway-api",
"url": "https://api.serverlessapigateway.com"
}
],
"cors": {
"allow_origins": ["*"],
"allow_origins": ["https://api1.serverlessapigateway.com", "http://api1.serverlessapigateway.com", "https://api2.serverlessapigateway.com"],
"allow_methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
"allow_headers": ["*"],
"expose_headers": ["*"],
Expand All @@ -29,7 +29,7 @@
"path": "/api/v1/mapping",
"integration": {
"type": "http_proxy",
"server": "ngrok"
"server": "serverlessapigateway-api"
},
"auth": true,
"mapping": {
Expand Down Expand Up @@ -80,26 +80,26 @@
},
{
"method": "GET",
"path": "/api/v1/ngrok",
"path": "/api/v1/proxy",
"integration": {
"type": "http_proxy",
"server": "ngrok"
"server": "serverlessapigateway-api"
}
},
{
"method": "GET",
"path": "/api/v1/ngrok/{parameter}",
"path": "/api/v1/proxy/{parameter}",
"integration": {
"type": "http_proxy",
"server": "ngrok"
"server": "serverlessapigateway-api"
}
},
{
"method": "GET",
"path": "/api/v1/ngrok/proxy/{.+}",
"path": "/api/v1/proxy/{.+}",
"integration": {
"type": "http_proxy",
"server": "ngrok"
"server": "serverlessapigateway-api"
}
},
{
Expand Down Expand Up @@ -132,10 +132,10 @@
},
{
"method": "POST",
"path": "/api/v1/ngrok",
"path": "/api/v1/proxy",
"integration": {
"type": "http_proxy",
"server": "ngrok"
"server": "serverlessapigateway-api"
}
},
{
Expand Down
7 changes: 5 additions & 2 deletions worker/src/cors.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import apiConfig from './api-config.json';

function setCorsHeaders(response: Response) {
function setCorsHeaders(request: Request, response: Response) {
console.log('Setting CORS headers');
const corsConfig = apiConfig.cors;

const origin = request.headers.get('Origin');
const matchingOrigin = corsConfig.allow_origins.find(allowedOrigin => allowedOrigin === origin);

const headers = new Headers(response.headers);
headers.set('Access-Control-Allow-Origin', corsConfig.allow_origins.join(','));
headers.set('Access-Control-Allow-Origin', matchingOrigin || corsConfig.allow_origins[0]);
headers.set('Access-Control-Allow-Methods', corsConfig.allow_methods.join(','));
headers.set('Access-Control-Allow-Headers', corsConfig.allow_headers.join(','));
headers.set('Access-Control-Expose-Headers', corsConfig.expose_headers.join(','));
Expand Down
17 changes: 6 additions & 11 deletions worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { setCorsHeaders } from "./cors";
import { applyValueMapping } from "./mapping";
import { setPoweredByHeader } from "./powered-by";
import { pathsMatch, createProxiedRequest } from './path-ops';
import * as responses from './responses';


export default {
Expand All @@ -12,7 +13,7 @@ export default {

// Handle CORS preflight (OPTIONS) requests first
if (apiConfig.cors && request.method === 'OPTIONS' && !apiConfig.paths.find(item => item.method === 'OPTIONS' && pathsMatch(item.path, url.pathname))) {
return setPoweredByHeader(setCorsHeaders(new Response(null, { status: 204 })));
return setPoweredByHeader(setCorsHeaders(request, new Response(null, { status: 204 })));
}


Expand All @@ -30,10 +31,7 @@ export default {
if (apiConfig.authorizer && matchedPath.auth) {
jwtPayload = await jwtAuth(request);
if (!jwtPayload.iss) {
return setPoweredByHeader(setCorsHeaders(new Response(
JSON.stringify({ message: 'Unauthorized' }),
{ headers: { 'Content-Type': 'application/json' }, status: 401 }
)));
return setPoweredByHeader(setCorsHeaders(request, responses.unauthorizedResponse));
}
}

Expand All @@ -46,16 +44,13 @@ export default {
console.log('Applying mapping:', matchedPath.mapping);
modifiedRequest = await applyValueMapping(modifiedRequest, matchedPath.mapping, jwtPayload, matchedPath.variables);
}
return fetch(modifiedRequest).then(response => setPoweredByHeader(setCorsHeaders(response)));
return fetch(modifiedRequest).then(response => setPoweredByHeader(setCorsHeaders(request, response)));
}
} else {
return setPoweredByHeader(setCorsHeaders(new Response(JSON.stringify(matchedPath.response), { headers: { 'Content-Type': 'application/json' } })));
return setPoweredByHeader(setCorsHeaders(request, new Response(JSON.stringify(matchedPath.response), { headers: { 'Content-Type': 'application/json' } })));
}
}

return setPoweredByHeader(setCorsHeaders(new Response(
JSON.stringify({ message: 'No match found.' }),
{ headers: { 'Content-Type': 'application/json' }, status: 404 }
)));
return setPoweredByHeader(setCorsHeaders(request, responses.noMatchResponse));
}
};
2 changes: 2 additions & 0 deletions worker/src/responses.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const noMatchResponse = () => new Response( JSON.stringify({ message: 'No match found.' }), { headers: { 'Content-Type': 'application/json' }, status: 404 })
export const unauthorizedResponse = () => new Response(JSON.stringify({ message: 'Unauthorized' }),{ headers: { 'Content-Type': 'application/json' }, status: 401 })
24 changes: 9 additions & 15 deletions worker/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,28 +1,25 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */

/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2021" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"lib": [
] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,

/* Language and Environment */
"target": "es2021" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"lib": ["es2021"] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
"jsx": "react" /* Specify what JSX code is generated. */,
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */

/* Modules */
"module": "es2022" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
Expand All @@ -31,16 +28,16 @@
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
"types": ["@cloudflare/workers-types/2023-07-01"] /* Specify type package names to be included without being referenced in a source file. */,
"types": [
"@cloudflare/workers-types/2023-07-01"
] /* Specify type package names to be included without being referenced in a source file. */,
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
"resolveJsonModule": true /* Enable importing .json files */,
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */

/* JavaScript Support */
"allowJs": true /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */,
"checkJs": false /* Enable error reporting in type-checked JavaScript files. */,
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */

/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
Expand All @@ -65,19 +62,17 @@
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

/* Interop Constraints */
"isolatedModules": true /* Ensure that each file can be safely transpiled without relying on other imports. */,
"allowSyntheticDefaultImports": true /* Allow 'import x from y' when a module doesn't have a default export. */,
// "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,

/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
"strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
"strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
"strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
"strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
Expand All @@ -93,7 +88,6 @@
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */

/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
Expand Down

0 comments on commit b7a3050

Please sign in to comment.