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
88 changes: 88 additions & 0 deletions src/activitypub/nodeinfo.dispatcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import type { Protocol } from '@fedify/fedify';

import type { Account } from '@/account/account.entity';
import type {
NodeInfoData,
NodeInfoService,
} from '@/activitypub/nodeinfo.service';
import type { FedifyRequestContext } from '@/app';
import { getError, getValue, isError } from '@/core/result';
import type { HostDataContextLoader } from '@/http/host-data-context-loader';

export class NodeInfoDispatcher {
constructor(
private readonly hostDataContextLoader: HostDataContextLoader,
private readonly nodeInfoService: NodeInfoService,
) {}

async dispatch(ctx: FedifyRequestContext) {
const hostData = await this.hostDataContextLoader.loadDataForHost(
ctx.host,
);

if (isError(hostData)) {
ctx.data.logger.error('NodeInfo: failed to resolve host', {
host: ctx.host,
error: getError(hostData),
});
throw new Error('NodeInfo requested without site context');
}

const { site, account } = getValue(hostData);
const data = await this.nodeInfoService.getData(site, account);

return {
software: {
name: 'ghost' as const,
version: { major: 0, minor: 1, patch: 0 },
homepage: new URL('https://ghost.org/'),
repository: new URL('https://github.com/TryGhost/Ghost'),
},
protocols: ['activitypub'] satisfies Protocol[],
services: {
inbound: [],
outbound: [],
},
openRegistrations: false,
usage: {
users: {
total: 1,
activeMonth: this.isActiveWithin(data.lastActivityAt, 30),
activeHalfyear: this.isActiveWithin(
data.lastActivityAt,
180,
),
},
localPosts: data.localPosts,
localComments: data.localComments,
},
metadata: this.getMetadata(account),
};
}

private isActiveWithin(
lastActivityAt: NodeInfoData['lastActivityAt'],
days: number,
): 0 | 1 {
if (lastActivityAt === null) {
return 0;
}

const activeSince = Date.now() - days * 24 * 60 * 60 * 1000;

return lastActivityAt.getTime() >= activeSince ? 1 : 0;
}

private getMetadata(account: Account) {
return {
nodeName: account.name ?? account.url.hostname,
...(account.bio ? { nodeDescription: account.bio } : {}),
...(account.avatarUrl ? { nodeIcon: account.avatarUrl.href } : {}),
...(account.bannerImageUrl
? { nodeBanner: account.bannerImageUrl.href }
: {}),
private: false,
postFormats: ['text/html'],
};
}
}
203 changes: 203 additions & 0 deletions src/activitypub/nodeinfo.dispatcher.unit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';

import type { AccountEntity } from '@/account/account.entity';
import { NodeInfoDispatcher } from '@/activitypub/nodeinfo.dispatcher';
import type { NodeInfoService } from '@/activitypub/nodeinfo.service';
import type { FedifyRequestContext } from '@/app';
import { error, ok } from '@/core/result';
import type { HostDataContextLoader } from '@/http/host-data-context-loader';
import type { Site } from '@/site/site.service';

describe('NodeInfoDispatcher', () => {
let mockAccount: AccountEntity;
let mockSite: Site;

beforeEach(() => {
mockAccount = {
id: 1,
username: 'testuser',
name: 'Test Site',
bio: 'Test description',
url: new URL('https://example.com/'),
avatarUrl: new URL('https://example.com/icon.png'),
bannerImageUrl: new URL('https://example.com/banner.png'),
apId: new URL('https://example.com/user/testuser'),
apInbox: new URL('https://example.com/user/testuser/inbox'),
isInternal: true,
} as AccountEntity;

mockSite = {
id: 1,
host: 'example.com',
webhook_secret: 'test-secret',
ghost_uuid: 'e604ed82-188c-4f55-a5ce-9ebfb4184970',
} as Site;

vi.clearAllMocks();
});

it('resolves host data and returns node info', async () => {
const hostDataContextLoader = {
loadDataForHost: vi.fn().mockResolvedValue(
ok({
site: mockSite,
account: mockAccount,
}),
),
};
const nodeInfoService = {
getData: vi.fn().mockResolvedValue({
lastActivityAt: new Date(),
localPosts: 2,
localComments: 1,
}),
};

const dispatcher = new NodeInfoDispatcher(
hostDataContextLoader as unknown as HostDataContextLoader,
nodeInfoService as unknown as NodeInfoService,
);

const result = await dispatcher.dispatch({
host: mockSite.host,
data: {
logger: {
error: vi.fn(),
},
},
} as unknown as FedifyRequestContext);

expect(result.usage.users.total).toBe(1);
expect(result.usage.users.activeMonth).toBe(1);
expect(result.usage.users.activeHalfyear).toBe(1);
expect(result.usage.localPosts).toBe(2);
expect(result.usage.localComments).toBe(1);
expect(result.metadata).toEqual({
nodeName: mockAccount.name,
nodeDescription: mockAccount.bio,
nodeIcon: mockAccount.avatarUrl?.href,
nodeBanner: mockAccount.bannerImageUrl?.href,
private: false,
postFormats: ['text/html'],
});
expect(hostDataContextLoader.loadDataForHost).toHaveBeenCalledWith(
mockSite.host,
);
expect(nodeInfoService.getData).toHaveBeenCalledWith(
mockSite,
mockAccount,
);
});

it('maps last activity into active user windows', async () => {
const now = new Date('2026-01-01T00:00:00.000Z');
const daysAgo = (days: number) =>
new Date(now.getTime() - days * 24 * 60 * 60 * 1000);

vi.useFakeTimers();
vi.setSystemTime(now);

try {
const cases = [
{
lastActivityAt: null,
activeMonth: 0,
activeHalfyear: 0,
},
{
lastActivityAt: daysAgo(30),
activeMonth: 1,
activeHalfyear: 1,
},
{
lastActivityAt: daysAgo(31),
activeMonth: 0,
activeHalfyear: 1,
},
{
lastActivityAt: daysAgo(180),
activeMonth: 0,
activeHalfyear: 1,
},
{
lastActivityAt: daysAgo(181),
activeMonth: 0,
activeHalfyear: 0,
},
];

for (const {
lastActivityAt,
activeMonth,
activeHalfyear,
} of cases) {
const hostDataContextLoader = {
loadDataForHost: vi.fn().mockResolvedValue(
ok({
site: mockSite,
account: mockAccount,
}),
),
};
const nodeInfoService = {
getData: vi.fn().mockResolvedValue({
lastActivityAt,
localPosts: 0,
localComments: 0,
}),
};

const dispatcher = new NodeInfoDispatcher(
hostDataContextLoader as unknown as HostDataContextLoader,
nodeInfoService as unknown as NodeInfoService,
);

const result = await dispatcher.dispatch({
host: mockSite.host,
data: {
logger: {
error: vi.fn(),
},
},
} as unknown as FedifyRequestContext);

expect(result.usage.users.activeMonth).toBe(activeMonth);
expect(result.usage.users.activeHalfyear).toBe(activeHalfyear);
}
} finally {
vi.useRealTimers();
}
});

it('throws when host data cannot be resolved', async () => {
const logger = {
error: vi.fn(),
};
const hostDataContextLoader = {
loadDataForHost: vi.fn().mockResolvedValue(error('site-not-found')),
};
const nodeInfoService = {
getData: vi.fn(),
};

const dispatcher = new NodeInfoDispatcher(
hostDataContextLoader as unknown as HostDataContextLoader,
nodeInfoService as unknown as NodeInfoService,
);

await expect(
dispatcher.dispatch({
host: mockSite.host,
data: { logger },
} as unknown as FedifyRequestContext),
).rejects.toThrow('NodeInfo requested without site context');
expect(nodeInfoService.getData).not.toHaveBeenCalled();
expect(logger.error).toHaveBeenCalledWith(
'NodeInfo: failed to resolve host',
{
host: mockSite.host,
error: 'site-not-found',
},
);
});
});
Loading
Loading