Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
cskrov committed Aug 26, 2024
1 parent 92c529d commit 2aeb9d6
Show file tree
Hide file tree
Showing 15 changed files with 227 additions and 72 deletions.
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@ Digital innsending av klager og anker. Samt ettersendelse.
# Komme i gang

## Autorisering mot @navikt-NPM-registeret
1. Lag et Personal Access Token (PAT) med scope: `read:packages`. _PAT-en må være autorisert for organisasjonen `navikt`._
2. Sett verdien i miljøvariabelen NODE_AUTH_TOKEN
1. [Lag et Personal Access Token (PAT)](https://github.com/settings/tokens) med scope: `read:packages`. _Tokenet må være autorisert for organisasjonen `navikt`._
2. Opprett filen `bunfig.toml` i din `$HOME`-mappe med følgende innhold:
```toml
[install.scopes]
"@navikt" = { token = "ghp_Qj6Xxn8HTUSJL9dNiZ0TW7R5YvupTZclTXsK", url = "https://npm.pkg.github.com/" }
```
3. Bytt ut `ghp_Qj6Xxn8HTUSJL9dNiZ0TW7R5YvupTZclTXsK` med ditt eget token.

### Referanser
- https://github.com/navikt/nav-dekoratoren-moduler?tab=readme-ov-file#kom-i-gang
Expand Down
6 changes: 6 additions & 0 deletions server/biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@
"noUnusedImports": {
"level": "error"
}
},
"style": {
"noUnusedTemplateLiteral": {
"level": "warn",
"fix": "unsafe"
}
}
}
},
Expand Down
Binary file modified server/bun.lockb
Binary file not shown.
2 changes: 0 additions & 2 deletions server/bunfig.toml

This file was deleted.

1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"@fastify/cors": "9.0.1",
"@fastify/http-proxy": "9.5.0",
"@fastify/type-provider-typebox": "4.1.0",
"@navikt/nav-dekoratoren-moduler": "^1.6.9",
"fastify": "4.28.1",
"fastify-metrics": "11.0.0",
"jose": "5.7.0",
Expand Down
16 changes: 7 additions & 9 deletions server/src/index-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,13 @@ class IndexFile {
const indexHtml = await injectDecoratorServerSide({
env: isDeployedToProd ? 'prod' : 'dev',
filePath: this.INDEX_HTML_PATH,
params: {
simple: true,
chatbot: true,
redirectToApp: true,
logoutUrl: '/oauth2/logout',
context: 'privatperson',
level: 'Level4',
logoutWarning: true,
},
simple: true,
chatbot: true,
redirectToApp: true,
logoutUrl: '/oauth2/logout',
context: 'privatperson',
level: 'Level4',
utloggingsvarsel: true,
});

const end = performance.now();
Expand Down
11 changes: 11 additions & 0 deletions server/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@ type SerializableValue =
| AnyObject
| AnyObject[];

export const isSerializable = (value: unknown): value is SerializableValue => {
return (
typeof value === 'number' ||
typeof value === 'string' ||
typeof value === 'boolean' ||
Array.isArray(value) ||
value === null ||
typeof value === 'object'
);
};

export interface AnyObject {
[key: string]: SerializableValue;
}
Expand Down
4 changes: 3 additions & 1 deletion server/src/plugins/api-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export interface ApiProxyPluginOptions {
appNames: string[];
}

export const API_PROXY_PLUGIN_ID = 'api-proxy';

export const apiProxyPlugin = fastifyPlugin<ApiProxyPluginOptions>(
(app, { appNames }, pluginDone) => {
app.decorateRequest('proxyStartTime', 0);
Expand Down Expand Up @@ -114,7 +116,7 @@ export const apiProxyPlugin = fastifyPlugin<ApiProxyPluginOptions>(

pluginDone();
},
{ fastify: '4', name: 'api-proxy', dependencies: [OBO_ACCESS_TOKEN_PLUGIN_ID, SERVER_TIMING_PLUGIN_ID] },
{ fastify: '4', name: API_PROXY_PLUGIN_ID, dependencies: [OBO_ACCESS_TOKEN_PLUGIN_ID, SERVER_TIMING_PLUGIN_ID] },
);

const prefixServerTimingEntry = (entry: string, appName: string): string => {
Expand Down
25 changes: 25 additions & 0 deletions server/src/plugins/error-report.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { getLogger, isSerializable } from '@app/logger';
import fastifyPlugin from 'fastify-plugin';

const log = getLogger('frontend-error-reporter');

export const ERROR_REPORT_PLUGIN_ID = 'error-report';

export const frontendLogPlugin = fastifyPlugin(
(app, _, pluginDone) => {
app.post('/error-report', (req, reply) => {
if (!isSerializable(req.body)) {
reply.status(400).send('Invalid request body');

return;
}

log.warn({ msg: 'Error report', data: req.body });

reply.status(200).send();
});

pluginDone();
},
{ fastify: '4', name: ERROR_REPORT_PLUGIN_ID },
);
81 changes: 81 additions & 0 deletions server/src/plugins/frontend-log/frontend-log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { getLogger } from '@app/logger';
import { FrontendEventTypes, Level } from '@app/plugins/frontend-log/types';
import { Type, type TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import fastifyPlugin from 'fastify-plugin';

const log = getLogger('frontend-log');

export const FRONTEND_LOG_PLUGIN_ID = 'frontend-log';

export const frontendLogPlugin = fastifyPlugin(
(app, _, pluginDone) => {
app.withTypeProvider<TypeBoxTypeProvider>().post(
'/frontend-log',
{
schema: {
body: Type.Composite([
Type.Object({
session_id: Type.String(),
level: Type.Enum(Level),
client_timestamp: Type.Number({ description: 'Current client Unix timestamp in milliseconds.' }),
token_expires: Type.Optional(Type.Number({ description: 'Milliseconds until the token expires.' })),
is_logged_in: Type.Boolean(),
client_version: Type.String(),
session_time: Type.Number({ description: 'Milliseconds since start of session.' }),
session_time_formatted: Type.String({
description: 'Formatted time since start of session.',
format: 'time',
examples: ['1:35:45.987'],
}),
route: Type.String({
description: 'Current path.',
examples: ['/nb/sak/uuid-uuid-uuid-uuid/begrunnelse'],
}),
message: Type.String(),
}),
Type.Union([
// Navigation event
Type.Object({
type: Type.Literal(FrontendEventTypes.NAVIGATION),
}),
// App event
Type.Object({
type: Type.Literal(FrontendEventTypes.APP),
action: Type.String(),
}),
// Error event
Type.Object(
{
type: Type.Literal(FrontendEventTypes.ERROR),
message: Type.String(),
stack: Type.Optional(Type.String({ description: 'Stack trace of the error.' })),
},
{ description: 'Error event.' },
),
// API event
Type.Object(
{
type: Type.Literal(FrontendEventTypes.API),
request: Type.String(),
response_time: Type.Number({ description: 'API response time in milliseconds.' }),
status: Type.Union([Type.Number(), Type.String()]),
},
{ description: 'API event.' },
),
]),
]),
},
},
(req, reply) => {
const { level, message, ...data } = req.body;

log[level]({ msg: message, data });

reply.status(200).send();
},
);

pluginDone();
},
{ fastify: '4', name: FRONTEND_LOG_PLUGIN_ID },
);
83 changes: 83 additions & 0 deletions server/src/plugins/frontend-log/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
export enum Level {
DEBUG = 'debug',
INFO = 'info',
WARN = 'warn',
ERROR = 'error',
}

export enum FrontendEventTypes {
NAVIGATION = 'navigation',
APP = 'app',
ERROR = 'error',
API = 'api',
SESSION = 'session',
}

interface BaseEventData {
session_id: string;
level: Level;
/** Current client Unix timestamp in milliseconds. */
client_timestamp: number;
/** Milliseconds until the token expires. */
token_expires?: number;
/** If the user is logged in. */
is_logged_in: boolean;
/** Current client version. */
client_version: string;
/** Milliseconds since start of session. */
session_time: number;
/** Formatted time since start of session.
* @example `1:35:45.987`
*/
session_time_formatted: string;
/** Current path.
* @example `/nb/klage/1234/begrunnelse`
* */
route: string;
message: string;
}

interface NavigationEvent extends BaseEventData {
type: FrontendEventTypes.NAVIGATION;
}

interface AppEvent extends BaseEventData {
type: FrontendEventTypes.APP;
action: string;
}

interface ErrorEvent extends BaseEventData {
type: FrontendEventTypes.ERROR;
message: string;
stack?: string;
}

interface ApiEvent extends BaseEventData {
type: FrontendEventTypes.API;
request: string;
response_time: number;
status: number | string;
}

enum SessionAction {
/** Load session case */
LOAD = 'load',
/** Create session case */
CREATE = 'create',
/** Load or create session case */
LOAD_OR_CREATE = 'load-create',
/** Delete session case */
DELETE = 'delete',
/** Set session case */
SET = 'set',
/** Update session case */
UPDATE = 'update',
}

interface SessionEvent extends BaseEventData {
type: FrontendEventTypes.SESSION;
message: string;
action: SessionAction;
}

export type FrontendLogEvent = NavigationEvent | AppEvent | ErrorEvent | ApiEvent | SessionEvent;
2 changes: 1 addition & 1 deletion server/src/plugins/http-logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { getDuration } from '@app/helpers/duration';
import { type AnyObject, getLogger } from '@app/logger';
import { PROXY_VERSION_PLUGIN_ID } from '@app/plugins/proxy-version';
import { SERVE_ASSETS_PLUGIN_ID } from '@app/plugins/serve-assets';
import { SERVE_INDEX_PLUGIN_ID } from '@app/plugins/serve-index';
import { SERVE_INDEX_PLUGIN_ID } from '@app/plugins/serve-index/serve-index';
import fastifyPlugin from 'fastify-plugin';

export const HTTP_LOGGER_PLUGIN_ID = 'http-logger';
Expand Down
3 changes: 2 additions & 1 deletion server/src/plugins/serve-index/serve-index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { isDeployedToProd } from '@app/config/env';
import { indexFile } from '@app/index-file';
import { getLogger } from '@app/logger';
import { API_PROXY_PLUGIN_ID } from '@app/plugins/api-proxy';
import { externalRedirectCounter, viewCountCounter } from '@app/plugins/serve-index/counters';
import { getPaths } from '@app/plugins/serve-index/get-paths';
import { removeSaksnummer } from '@app/plugins/serve-index/remove-saksnummer';
Expand Down Expand Up @@ -43,7 +44,7 @@ export const serveIndexPlugin = fastifyPlugin(

pluginDone();
},
{ fastify: '4', name: SERVE_INDEX_PLUGIN_ID },
{ fastify: '4', name: SERVE_INDEX_PLUGIN_ID, dependencies: [API_PROXY_PLUGIN_ID] },
);

const YTELSE_OVERVIEW_URL = isDeployedToProd ? 'https://www.nav.no/klage' : 'https://www.ekstern.dev.nav.no/klage';
15 changes: 0 additions & 15 deletions server/src/routes/error-report.ts

This file was deleted.

41 changes: 0 additions & 41 deletions server/src/routes/frontend-log.ts

This file was deleted.

0 comments on commit 2aeb9d6

Please sign in to comment.