Skip to content

Commit

Permalink
Added auth middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
allouis committed Jul 10, 2024
1 parent f506e25 commit e40b448
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import jose from 'node-jose';
import jwt from 'jsonwebtoken';
import { serve } from '@hono/node-server';
import {
Article,
Expand Down Expand Up @@ -138,9 +140,12 @@ fedify.setObjectDispatcher(

/** Hono */

type GhostRole = 'Anonymous' | 'Owner' | 'Administrator' | 'Editor' | 'Author' | 'Contributor';

export type HonoContextVariables = {
db: KvStore;
globaldb: KvStore;
role: GhostRole;
};

const app = new Hono<{ Variables: HonoContextVariables }>();
Expand Down Expand Up @@ -208,6 +213,55 @@ app.use(async (ctx, next) => {
await next();
});

app.use(async (ctx, next) => {
const request = ctx.req;
const host = request.header('host');
if (!host) {
// TODO handle
throw new Error('No Host header');
}
ctx.set('role', 'Anonymous');

const authorization = request.header('authorization');

if (!authorization) {
return next();
}

const [match, token] = authorization.match(/Bearer\s+(.*)$/) || [null];

if (!match) {
throw new Error('Invalid Authorization header');
}

const jwksURL = new URL('/ghost/.well-known/jwks.json', `https://${host}`);

const jwksResponse = await fetch(jwksURL, {
redirect: 'follow'
});

const jwks = await jwksResponse.json();

const key = await jose.JWK.asKey(jwks.keys[0]);

try {
const claims = jwt.verify(token, key.toPEM());
if (typeof claims === 'string' || typeof claims.role !== 'string') {
return;
}
if (['Owner', 'Administrator', 'Editor', 'Author', 'Contributor'].includes(claims.role)) {
ctx.set('role', claims.role as GhostRole);
} else {
ctx.set('role', 'Anonymous');
}
} catch (err) {
ctx.set('role', 'Anonymous');
}

next();
});


/** Custom API routes */

app.get('/.ghost/activitypub/inbox/:handle', inboxHandler);
Expand Down

0 comments on commit e40b448

Please sign in to comment.