Skip to content

Commit

Permalink
Try adding subdomain support
Browse files Browse the repository at this point in the history
  • Loading branch information
vgrichina committed Sep 10, 2024
1 parent c7f84aa commit 8601cc5
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
24 changes: 24 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,11 +160,35 @@ router.get('/', async ctx => {
router.get('/ipfs/:cid/:path(.+)', serveFile);
router.get('/ipfs/:cid', serveFile);

const handleSubdomain = async (ctx, next) => {
const hostname = ctx.hostname;
const parts = hostname.split('.');
if (parts.length > 2) {
const subdomain = parts[0];
try {
// Check if the subdomain is a valid CID
const cid = multibase.decode(subdomain);
// Set the params to be used by serveFile
ctx.params = ctx.params || {};
ctx.params.cid = subdomain;
ctx.params.path = ctx.path.slice(1); // Remove leading slash
await serveFile(ctx);
} catch (error) {
// If it's not a valid CID, continue to the next middleware
console.error('Invalid CID in subdomain:', error);
await next();
}
} else {
await next();
}
};

app
.use(async (ctx, next) => {
console.log(ctx.method, ctx.path);
await next();
})
.use(handleSubdomain)
.use(cors({ credentials: true }))
.use(router.routes())
.use(router.allowedMethods());
Expand Down
31 changes: 31 additions & 0 deletions test/app.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,37 @@ test('/', async t => {
t.match(text, /vgrichina\/nearfs/);
});

test('handleSubdomain middleware serves content for valid CID subdomains', async t => {
await loadCar('test/data/hello.car');

const { status, text } = await request
.get('/')
.set('Host', 'bafybeicit72w2sl3agal2jftpkrzwd773fjgdk4dym7pq2pbojyif72v5e.example.com');

t.isEqual(status, 200);
t.isEqual(text, 'Hello, World\n');
});

test('handleSubdomain middleware ignores invalid CID subdomains', async t => {
const { status, text } = await request
.get('/')
.set('Host', 'invalid-cid.example.com');

t.isEqual(status, 200);
t.match(text, /vgrichina\/nearfs/);
});

test('handleSubdomain middleware serves content for valid CID subdomains with path', async t => {
await loadCar('test/data/littlelink.car');

const { status, headers } = await request
.get('/css/normalize.css')
.set('Host', 'bafybeiepywlzwr2yzyin2bo7k2v5oi37lsgleyvfrf6erjvlze2qec6wkm.example.com');

t.isEqual(status, 200);
t.isEqual(headers['content-type'], 'text/css; charset=utf-8');
});

test('/ipfs/:cid not found', async t => {
const { status } = await request.get('/ipfs/bafkreib3mbbrhmal34xx7loxzxc4ue36y5rg7wvc24xwryg2j2ozek3p4y');
t.isEqual(status, 404);
Expand Down

0 comments on commit 8601cc5

Please sign in to comment.