Files
sign/packages/trpc/server/trpc.ts

197 lines
5.3 KiB
TypeScript
Raw Normal View History

2023-06-09 18:21:18 +10:00
import { TRPCError, initTRPC } from '@trpc/server';
import SuperJSON from 'superjson';
import type { AnyZodObject } from 'zod';
2023-06-09 18:21:18 +10:00
import { AppError, genericErrorCodeToTrpcErrorCodeMap } from '@documenso/lib/errors/app-error';
2024-12-14 01:23:35 +09:00
import { getApiTokenByToken } from '@documenso/lib/server-only/public-api/get-api-token-by-token';
import type { ApiRequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
2025-02-13 20:56:44 +11:00
import { isAdmin } from '@documenso/lib/utils/is-admin';
2023-10-11 12:32:33 +03:00
import type { TrpcContext } from './context';
2023-06-09 18:21:18 +10:00
// Can't import type from trpc-to-openapi because it breaks nextjs build, not sure why.
type OpenApiMeta = {
openapi?: {
enabled?: boolean;
method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
path: `/${string}`;
summary?: string;
description?: string;
protect?: boolean;
tags?: string[];
// eslint-disable-next-line @typescript-eslint/ban-types
contentTypes?: ('application/json' | 'application/x-www-form-urlencoded' | (string & {}))[];
deprecated?: boolean;
requestHeaders?: AnyZodObject;
responseHeaders?: AnyZodObject;
successDescription?: string;
errorResponses?: number[] | Record<number, string>;
};
} & Record<string, unknown>;
2024-12-14 01:23:35 +09:00
const t = initTRPC
.meta<OpenApiMeta>()
.context<TrpcContext>()
.create({
transformer: SuperJSON,
errorFormatter(opts) {
const { shape, error } = opts;
2024-12-14 01:23:35 +09:00
const originalError = error.cause;
2024-12-14 01:23:35 +09:00
let data: Record<string, unknown> = shape.data;
2024-12-14 01:23:35 +09:00
// Default unknown errors to 400, since if you're throwing an AppError it is expected
// that you already know what you're doing.
if (originalError instanceof AppError) {
data = {
...data,
appError: AppError.toJSON(originalError),
code: originalError.code,
httpStatus:
originalError.statusCode ??
genericErrorCodeToTrpcErrorCodeMap[originalError.code]?.status ??
400,
};
}
2024-12-14 01:23:35 +09:00
return {
...shape,
data,
};
},
});
2023-06-09 18:21:18 +10:00
/**
* Middlewares
*/
2023-08-29 13:01:19 +10:00
export const authenticatedMiddleware = t.middleware(async ({ ctx, next }) => {
2025-01-02 15:33:37 +11:00
const authorizationHeader = ctx.req.headers.get('authorization');
2024-12-14 01:23:35 +09:00
// Taken from `authenticatedMiddleware` in `@documenso/api/v1/middleware/authenticated.ts`.
if (authorizationHeader) {
// Support for both "Authorization: Bearer api_xxx" and "Authorization: api_xxx"
const [token] = (authorizationHeader || '').split('Bearer ').filter((s) => s.length > 0);
if (!token) {
throw new Error('Token was not provided for authenticated middleware');
}
const apiToken = await getApiTokenByToken({ token });
return await next({
ctx: {
...ctx,
user: apiToken.user,
teamId: apiToken.teamId || undefined,
2024-12-14 01:23:35 +09:00
session: null,
metadata: {
...ctx.metadata,
auditUser: apiToken.team
? {
id: null,
email: null,
name: apiToken.team.name,
}
: {
id: apiToken.user.id,
email: apiToken.user.email,
name: apiToken.user.name,
},
auth: 'api',
} satisfies ApiRequestMetadata,
2024-12-14 01:23:35 +09:00
},
});
}
2023-06-09 18:21:18 +10:00
if (!ctx.session) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'Invalid session or API token.',
2023-06-09 18:21:18 +10:00
});
}
2023-08-29 13:01:19 +10:00
return await next({
2023-06-09 18:21:18 +10:00
ctx: {
...ctx,
user: ctx.user,
session: ctx.session,
metadata: {
...ctx.metadata,
auditUser: {
id: ctx.user.id,
name: ctx.user.name,
email: ctx.user.email,
},
auth: 'session',
} satisfies ApiRequestMetadata,
2023-06-09 18:21:18 +10:00
},
});
});
export const maybeAuthenticatedMiddleware = t.middleware(async ({ ctx, next }) => {
return await next({
ctx: {
...ctx,
user: ctx.user,
session: ctx.session,
metadata: {
...ctx.metadata,
auditUser: ctx.user
? {
id: ctx.user.id,
name: ctx.user.name,
email: ctx.user.email,
}
: undefined,
auth: ctx.session ? 'session' : null,
} satisfies ApiRequestMetadata,
},
});
});
2023-10-11 12:32:33 +03:00
export const adminMiddleware = t.middleware(async ({ ctx, next }) => {
if (!ctx.session || !ctx.user) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'You must be logged in to perform this action.',
});
}
const isUserAdmin = isAdmin(ctx.user);
if (!isUserAdmin) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: 'Not authorized to perform this action.',
});
}
return await next({
ctx: {
...ctx,
user: ctx.user,
session: ctx.session,
metadata: {
...ctx.metadata,
auditUser: {
id: ctx.user.id,
name: ctx.user.name,
email: ctx.user.email,
},
auth: 'session',
} satisfies ApiRequestMetadata,
2023-10-11 12:32:33 +03:00
},
});
});
2023-06-09 18:21:18 +10:00
/**
* Routers and Procedures
*/
export const router = t.router;
export const procedure = t.procedure;
export const authenticatedProcedure = t.procedure.use(authenticatedMiddleware);
// While this is functionally the same as `procedure`, it's useful for indicating purpose
export const maybeAuthenticatedProcedure = t.procedure.use(maybeAuthenticatedMiddleware);
2023-10-11 12:32:33 +03:00
export const adminProcedure = t.procedure.use(adminMiddleware);