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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
"@radix-ui/react-dropdown-menu": "2.1.24",
"@radix-ui/react-label": "2.1.15",
"@radix-ui/react-slot": "1.3.3",
"@saas-maker/app-health": "https://github.com/sass-maker/app-health/releases/download/node-v0.4.0/saas-maker-app-health-0.4.0.tgz",
"@saas-maker/feedback": "^0.2.1",
"@tailwindcss/typography": "0.5.20",
"@tanstack/react-query": "5.101.4",
Expand Down
19 changes: 19 additions & 0 deletions pnpm-lock.yaml

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

2 changes: 2 additions & 0 deletions src/lib/worker-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export type WorkerEnv = {
LOCAL_AI_URL?: string;
CLI_BRIDGE_URL?: string;
NODE_ENV?: string;
APP_HEALTH_INGEST_KEY?: string;
APP_HEALTH_ENVIRONMENT?: string;
PDFS_BUCKET: R2Bucket;
ASSETS: Fetcher;
};
3 changes: 3 additions & 0 deletions src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import miscRoutes from './worker/routes/misc';
import pdfRoutes from './worker/routes/pdf';
import rssRoutes from './worker/routes/rss';
import shareRoutes from './worker/routes/share';
import { appHealthMiddleware } from './worker/app-health';

const SECURITY_HEADERS: Record<string, string> = {
'X-Content-Type-Options': 'nosniff',
Expand All @@ -40,6 +41,8 @@ api.use('*', async (c, next) => {
await next();
});

api.use('*', appHealthMiddleware);

api.use('/api/*', async (c, next) => {
await next();
const response = c.res;
Expand Down
82 changes: 82 additions & 0 deletions src/worker/app-health.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { Hono } from 'hono';
import { describe, expect, it, vi } from 'vitest';

import type { WorkerEnv } from '../lib/worker-env';
import { createReaderAppHealthMiddleware } from './app-health';

describe('Reader App Health endpoint middleware', () => {
it('is disabled without an ingest key', async () => {
const createClient = vi.fn();
const app = new Hono<{ Bindings: WorkerEnv }>();
app.use('*', createReaderAppHealthMiddleware(createClient));
app.get('/api/articles/:articleId', (c) => c.json({ ok: true }));

const response = await app.request('/api/articles/private-id?search=secret', {}, {});

expect(response.status).toBe(200);
expect(createClient).not.toHaveBeenCalled();
});

it('records only the matched route summary and preserves the response', async () => {
const record = vi.fn();
const flush = vi.fn().mockResolvedValue(undefined);
const waitUntil = vi.fn();
const createClient = vi.fn(() => ({ record, flush }) as never);
const app = new Hono<{ Bindings: WorkerEnv }>();
app.use('*', createReaderAppHealthMiddleware(createClient));
app.on(['GET', 'POST'], '/api/articles/:articleId', (c) =>
c.json({ content: 'private article body' })
);

const response = await app.request(
'/api/articles/private-id?search=private-query',
{
method: 'POST',
headers: { Authorization: 'Bearer private-token', Cookie: 'session=private-cookie' },
body: 'private request body',
},
{ APP_HEALTH_INGEST_KEY: 'synthetic-test-key' } as WorkerEnv,
{ waitUntil } as unknown as ExecutionContext
);

expect(response.status).toBe(200);
expect(await response.json()).toEqual({ content: 'private article body' });
expect(createClient).toHaveBeenCalledWith({
key: 'synthetic-test-key',
environment: 'production',
endpoint: 'https://ingest.sassmaker.com/v1/ingest',
runtime: 'worker',
disableTimer: true,
});
expect(record).toHaveBeenCalledOnce();
const event = record.mock.calls[0][0];
expect(event).toMatchObject({
method: 'POST',
route: '/api/articles/:articleId',
status_code: 200,
});
expect(JSON.stringify(event)).not.toContain('private-id');
expect(JSON.stringify(event)).not.toContain('private-query');
expect(JSON.stringify(event)).not.toContain('private-token');
expect(JSON.stringify(event)).not.toContain('private-cookie');
expect(JSON.stringify(event)).not.toContain('private request body');
expect(JSON.stringify(event)).not.toContain('private article body');
expect(flush).toHaveBeenCalledOnce();
expect(waitUntil).toHaveBeenCalledOnce();

const secondResponse = await app.request(
'/api/articles/another-private-id?search=another-private-query',
{},
{ APP_HEALTH_INGEST_KEY: 'synthetic-test-key' } as WorkerEnv,
{ waitUntil } as unknown as ExecutionContext
);

expect(secondResponse.status).toBe(200);
expect(createClient).toHaveBeenCalledOnce();
expect(record).toHaveBeenCalledTimes(2);
expect(waitUntil).toHaveBeenCalledTimes(2);
expect(record.mock.calls[1][0].route).toBe('/api/articles/:articleId');
expect(JSON.stringify(record.mock.calls[1][0])).not.toContain('another-private-id');
expect(JSON.stringify(record.mock.calls[1][0])).not.toContain('another-private-query');
});
});
45 changes: 45 additions & 0 deletions src/worker/app-health.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import {
createAppHealthClient,
type AppHealthClient,
type AppHealthClientOptions,
} from '@saas-maker/app-health';
import { honoMiddleware } from '@saas-maker/app-health/hono';
import type { Context, Env } from 'hono';

import type { WorkerEnv } from '../lib/worker-env';

type ReaderEnv = Env & { Bindings: WorkerEnv };
type ClientFactory = (options: AppHealthClientOptions) => AppHealthClient;

export function createReaderAppHealthMiddleware(
createClient: ClientFactory = createAppHealthClient
) {
let cachedKey: string | null = null;
let cachedEnvironment = '';
let cachedClient: AppHealthClient | null = null;

return honoMiddleware<ReaderEnv>({
client: (context: Context<ReaderEnv>) => {
const key = context.env.APP_HEALTH_INGEST_KEY?.trim();
if (!key) return null;

const environment = context.env.APP_HEALTH_ENVIRONMENT?.trim() || 'production';
if (cachedClient && cachedKey === key && cachedEnvironment === environment) {
return cachedClient;
}

cachedKey = key;
cachedEnvironment = environment;
cachedClient = createClient({
key,
environment,
endpoint: 'https://ingest.sassmaker.com/v1/ingest',
runtime: 'worker',
disableTimer: true,
});
return cachedClient;
},
});
}

export const appHealthMiddleware = createReaderAppHealthMiddleware();
Loading