我为 NestJS 9.4.0 安装了 @fastify/csrf-protection 包来保护它,但它给我一个结束错误。任何人都知道我做错了什么以及它应该是什么样子?我一直在努力解决这个问题很长一段时间,ChatGPT 表明一切都很好。我发现的各种示例与我有类似的实现。我为 Nest 添加了装饰器,这样它们就不会与 Passport 冲突。我没有检查或调用控制器中的 CSRF 方法,因为它应该适用于所有路由。
主要代码:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { fastifyCookie } from '@fastify/cookie';
import { ThrottlerModule } from '@nestjs/throttler';
import fastifyCsrf from '@fastify/csrf-protection';
import { FastifyInstance } from 'fastify';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);
const fastifyInstance: FastifyInstance = app.getHttpAdapter().getInstance();
fastifyInstance
.addHook('onRequest', async (req, res) => {
req.socket['encrypted'] = process.env.NODE_ENV === 'production';
})
.decorateReply('setHeader', function (name: string, value: unknown) {
this.header(name, value);
})
.decorateReply('end', function () {
this.send('');
});
const configService = app.get(ConfigService);
const port = configService.get<string>('PORT', '');
// Throttler - Protection
app.enableCors({
origin: '*',
methods: 'GET, HEAD, PUT, PATCH, POST, DELETE',
allowedHeaders: 'Content-Type, Authorization',
credentials: true,
});
// XCSRF - Protection
app.use(fastifyCookie);
app.use(fastifyCsrf, {
cookie: {
httpOnly: true,
sameSite: 'strict',
path: '^/',
secure: true,
},
});
await app.listen(port);
}
bootstrap();
错误:
[Nest] 1132 - 02.05.2023, 14:15:59 ERROR [ExceptionHandler] Unexpected CHAR at 1, expected END
TypeError: Unexpected CHAR at 1, expected END
at mustConsume (H:\xampp\htdocs\facebook-app\server\node_modules\@fastify\middie\node_modules\path-to-regexp\src\index.ts:157:11)
at parse (H:\xampp\htdocs\facebook-app\server\node_modules\@fastify\middie\node_modules\path-to-regexp\src\index.ts:227:5)
at stringToRegexp (H:\xampp\htdocs\facebook-app\server\node_modules\@fastify\middie\node_modules\path-to-regexp\src\index.ts:493:25)
at pathToRegexp (H:\xampp\htdocs\facebook-app\server\node_modules\@fastify\middie\node_modules\path-to-regexp\src\index.ts:620:10)
at Object.use (H:\xampp\htdocs\facebook-app\server\node_modules\@fastify\middie\engine.js:23:16)
at Object.use (H:\xampp\htdocs\facebook-app\server\node_modules\@fastify\middie\index.js:26:21)
at FastifyAdapter.use (H:\xampp\htdocs\facebook-app\server\node_modules\@nestjs\core\adapters\http-adapter.js:14:30)
at NestApplication.use (H:\xampp\htdocs\facebook-app\server\node_modules\@nestjs\core\nest-application.js:146:26)
at H:\xampp\htdocs\facebook-app\server\node_modules\@nestjs\core\nest-factory.js:145:40
at Function.run (H:\xampp\htdocs\facebook-app\server\node_modules\@nestjs\core\errors\exceptions-zone.js:10:13)