Skip to content
Merged
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
37 changes: 0 additions & 37 deletions .eslintrc.js

This file was deleted.

1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.github/
29 changes: 29 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import js from '@eslint/js';
import globals from 'globals';
import prettier from 'eslint-plugin-prettier';
import tseslint from 'typescript-eslint';

export default [
{
ignores: ['dist/**', '.github/**']
},
{
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
globals: {
...globals.node
}
}
},
js.configs.recommended,
...tseslint.configs.recommended,
{
plugins: {
prettier
},
rules: {
'prettier/prettier': 'warn'
}
}
];
18 changes: 7 additions & 11 deletions lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,37 +8,33 @@ export const postgres = {
username: process.env.POSTGRES_USERNAME,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DATABASE
}
};

if(
!process.env.JWT_SECRET ||
!process.env.JWT_ORDER_SECRET ||
!process.env.JWT_TICKET_SECRET
) throw new Error('JWT config is not set');
if (!process.env.JWT_SECRET || !process.env.JWT_ORDER_SECRET || !process.env.JWT_TICKET_SECRET) throw new Error('JWT config is not set');
export const jwt = {
secret: process.env.JWT_SECRET,
orderSecret: process.env.JWT_ORDER_SECRET,
ticketSecret: process.env.JWT_TICKET_SECRET
}
};

export const google = {
identityClientId: process.env.GOOGLE_IDENTITY_CLIENT_ID
}
};

export const mailgun = {
domain: process.env.MAILGUN_DOMAIN,
apiKey: process.env.MAILGUN_API_KEY
}
};

export const mailchimp = {
domain: process.env.MAILCHIMP_DOMAIN,
apiKey: process.env.MAILCHIMP_API_KEY
}
};

export const braintree = {
environment: process.env.BRAINTREE_ENV || 'Sandbox',
merchantId: process.env.BRAINTREE_MERCHANT_ID,
publicKey: process.env.BRAINTREE_PUBLIC_KEY,
privateKey: process.env.BRAINTREE_PRIVATE_KEY,
serviceFee: 0
}
};
53 changes: 16 additions & 37 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,12 @@ app.proxyIpHeader = 'X-Real-IP';
app.use(async (ctx, next) => {
try {
await next();
} catch(e) {
if(e instanceof HttpError) {
ctx.status = e.status
} catch (e) {
if (e instanceof HttpError) {
ctx.status = e.status;

ctx.body = e.expose ? e.message : 'Internal Server Error';
} else if(e instanceof Error) {
} else if (e instanceof Error) {
ctx.status = 500;
ctx.body = 'Internal Server Error';
}
Expand Down Expand Up @@ -100,18 +100,12 @@ app.use(
const origin = ctx.get('origin');

// Accept dev origins only in non-production environments
if(
corsEnv !== 'production'
&& (
/^https:\/\/(.+\.)?localhost(:\d*)?$/.test(origin) ||
/^https:\/\/.+\.local\.mrstache\.io(:\d*)?$/.test(origin)
)
) {
if (corsEnv !== 'production' && (/^https:\/\/(.+\.)?localhost(:\d*)?$/.test(origin) || /^https:\/\/.+\.local\.mrstache\.io(:\d*)?$/.test(origin))) {
return origin;
}

// Mustache bash root and single subdomain, HTTPS only
if(/^https:\/\/(\w+\.)?mustachebash\.com$/.test(origin)) {
if (/^https:\/\/(\w+\.)?mustachebash\.com$/.test(origin)) {
return origin;
}

Expand All @@ -121,35 +115,20 @@ app.use(
const origin = ctx.get('origin');

// Accept dev origins only in non-production environments
if(corsEnv !== 'production' && /^https:\/\/(.+\.)?localhost(:\d*)?$/.test(origin)) {
if (corsEnv !== 'production' && /^https:\/\/(.+\.)?localhost(:\d*)?$/.test(origin)) {
return true;
}

// Mustache bash root and single subdomain, HTTPS only
if(/^https:\/\/(\w+\.)?mustachebash\.com$/.test(origin)) {
if (/^https:\/\/(\w+\.)?mustachebash\.com$/.test(origin)) {
return true;
}

return false;
},
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowHeaders: [
'Accept',
'Authorization',
'Cache-Control',
'Content-Type',
'DNT',
'If-Modified-Since',
'Keep-Alive',
'Origin',
'User-Agent',
'X-Requested-With'
],
exposeHeaders: [
'Location',
'Retry-After',
'Warning'
]
allowHeaders: ['Accept', 'Authorization', 'Cache-Control', 'Content-Type', 'DNT', 'If-Modified-Since', 'Keep-Alive', 'Origin', 'User-Agent', 'X-Requested-With'],
exposeHeaders: ['Location', 'Retry-After', 'Warning']
})
);

Expand All @@ -159,14 +138,14 @@ app.use(
* a child logger for each request
*/
app.use(async (ctx, next) => {
ctx.state.log = log.child({requestId: ctx.requestId});
ctx.state.log = log.child({ requestId: ctx.requestId });

await next();

const { request, response } = ctx,
message = `${request.method} ${request.originalUrl} ${response.status}`;

ctx.state.log.info({request, response, ctx}, message);
ctx.state.log.info({ request, response, ctx }, message);
});

/**
Expand All @@ -179,7 +158,7 @@ app.use(async (ctx, next) => {
try {
await next();
} finally {
const [ seconds, nanoseconds ] = process.hrtime(start);
const [seconds, nanoseconds] = process.hrtime(start);

ctx.state.responseTime = seconds * 1e3 + nanoseconds * 1e-6;
}
Expand Down Expand Up @@ -209,10 +188,10 @@ app.on('error', (err, ctx) => {

response.status = err.status || response.status;

if(err.status < 500) {
ctx.state.log.warn({request, response, ctx, err}, `${request.method} ${request.originalUrl} ${response.status} - ${err.message}`);
if (err.status < 500) {
ctx.state.log.warn({ request, response, ctx, err }, `${request.method} ${request.originalUrl} ${response.status} - ${err.message}`);
} else {
ctx.state.log.error({request, response, ctx, err}, err.message);
ctx.state.log.error({ request, response, ctx, err }, err.message);
}
});

Expand Down
11 changes: 5 additions & 6 deletions lib/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ import { Next } from 'koa';
import { AppContext } from '../index.js';
import { validateAccessToken, checkScope } from '../services/auth.js';


export async function authorizeUser(ctx: AppContext, next: Next) {
const authHeader = ctx.headers.authorization && ctx.headers.authorization.split(' ');

if(!authHeader || authHeader.length !== 2 && authHeader[0] !== 'Bearer') throw ctx.throw(403);
if (!authHeader || (authHeader.length !== 2 && authHeader[0] !== 'Bearer')) throw ctx.throw(403);

const accessToken = authHeader[1];

if(!accessToken) throw ctx.throw(403);
if (!accessToken) throw ctx.throw(403);

try {
const { role, sub } = validateAccessToken(accessToken);
Expand All @@ -20,7 +19,7 @@ export async function authorizeUser(ctx: AppContext, next: Next) {
role
};
} catch (e) {
throw ctx.throw(401);
throw ctx.throw(401, e, { expose: false });
}

await next();
Expand All @@ -29,9 +28,9 @@ export async function authorizeUser(ctx: AppContext, next: Next) {
export function requiresPermission(scopeRequired: string) {
return async (ctx: AppContext, next: Next) => {
// Just don't even try if it's not there
if(!ctx.state.user || !ctx.state.user.role) throw ctx.throw(403);
if (!ctx.state.user || !ctx.state.user.role) throw ctx.throw(403);

if(!checkScope(ctx.state.user.role, scopeRequired)) throw ctx.throw(403);
if (!checkScope(ctx.state.user.role, scopeRequired)) throw ctx.throw(403);

await next();
};
Expand Down
30 changes: 15 additions & 15 deletions lib/routes/customers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,22 @@ customersRouter
try {
const customers = await getCustomers(ctx.query);

return ctx.body = customers;
} catch(e) {
return (ctx.body = customers);
} catch (e) {
throw ctx.throw(e);
}
})
.post('/', authorizeUser, requiresPermission('admin'), async ctx => {
if(!isRecordLike(ctx.request.body)) throw ctx.throw(400);
if (!isRecordLike(ctx.request.body)) throw ctx.throw(400);

try {
const customer = await createCustomer({...ctx.request.body, createdBy: ctx.state.user.id});
const customer = await createCustomer({ ...ctx.request.body, createdBy: ctx.state.user.id });

ctx.set('Location', `https://${ctx.host}${ctx.path}/${customer.id}`);
ctx.status= 201;
return ctx.body = customer;
} catch(e) {
if(e.code === 'INVALID') throw ctx.throw(400);
ctx.status = 201;
return (ctx.body = customer);
} catch (e) {
if (e.code === 'INVALID') throw ctx.throw(400);

throw ctx.throw(e);
}
Expand All @@ -41,20 +41,20 @@ customersRouter
try {
const customer = await getCustomer(ctx.params.id);

return ctx.body = customer;
} catch(e) {
if(e.code === 'NOT_FOUND') throw ctx.throw(404);
return (ctx.body = customer);
} catch (e) {
if (e.code === 'NOT_FOUND') throw ctx.throw(404);

throw ctx.throw(e);
}
})
.delete('/:id', authorizeUser, requiresPermission('admin'), async ctx => {
try {
const customer = await updateCustomer(ctx.params.id, {updatedBy: ctx.state.user.id, status: 'disabled'});
const customer = await updateCustomer(ctx.params.id, { updatedBy: ctx.state.user.id, status: 'disabled' });

return ctx.body = customer;
} catch(e) {
if(e.code === 'INVALID') throw ctx.throw(400);
return (ctx.body = customer);
} catch (e) {
if (e.code === 'INVALID') throw ctx.throw(400);

throw ctx.throw(e);
}
Expand Down
Loading
Loading