feat: bootstrap codexdash app
This commit is contained in:
4
apps/api/.prettierrc
Normal file
4
apps/api/.prettierrc
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
98
apps/api/README.md
Normal file
98
apps/api/README.md
Normal file
@@ -0,0 +1,98 @@
|
||||
<p align="center">
|
||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||
</p>
|
||||
|
||||
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||
|
||||
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||
</p>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](https://opencollective.com/nest#sponsor)-->
|
||||
|
||||
## Description
|
||||
|
||||
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||
|
||||
## Project setup
|
||||
|
||||
```bash
|
||||
$ pnpm install
|
||||
```
|
||||
|
||||
## Compile and run the project
|
||||
|
||||
```bash
|
||||
# development
|
||||
$ pnpm run start
|
||||
|
||||
# watch mode
|
||||
$ pnpm run start:dev
|
||||
|
||||
# production mode
|
||||
$ pnpm run start:prod
|
||||
```
|
||||
|
||||
## Run tests
|
||||
|
||||
```bash
|
||||
# unit tests
|
||||
$ pnpm run test
|
||||
|
||||
# e2e tests
|
||||
$ pnpm run test:e2e
|
||||
|
||||
# test coverage
|
||||
$ pnpm run test:cov
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||
|
||||
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||
|
||||
```bash
|
||||
$ pnpm install -g @nestjs/mau
|
||||
$ mau deploy
|
||||
```
|
||||
|
||||
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||
|
||||
## Resources
|
||||
|
||||
Check out a few resources that may come in handy when working with NestJS:
|
||||
|
||||
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||
|
||||
## Support
|
||||
|
||||
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||
|
||||
## Stay in touch
|
||||
|
||||
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||
|
||||
## License
|
||||
|
||||
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||
35
apps/api/eslint.config.mjs
Normal file
35
apps/api/eslint.config.mjs
Normal file
@@ -0,0 +1,35 @@
|
||||
// @ts-check
|
||||
import eslint from '@eslint/js';
|
||||
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
|
||||
import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
export default tseslint.config(
|
||||
{
|
||||
ignores: ['eslint.config.mjs'],
|
||||
},
|
||||
eslint.configs.recommended,
|
||||
...tseslint.configs.recommendedTypeChecked,
|
||||
eslintPluginPrettierRecommended,
|
||||
{
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.node,
|
||||
...globals.jest,
|
||||
},
|
||||
sourceType: 'commonjs',
|
||||
parserOptions: {
|
||||
projectService: true,
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/no-floating-promises': 'warn',
|
||||
'@typescript-eslint/no-unsafe-argument': 'warn',
|
||||
"prettier/prettier": ["error", { endOfLine: "auto" }],
|
||||
},
|
||||
},
|
||||
);
|
||||
8
apps/api/nest-cli.json
Normal file
8
apps/api/nest-cli.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true
|
||||
}
|
||||
}
|
||||
69
apps/api/package.json
Normal file
69
apps/api/package.json
Normal file
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"name": "@codexdash/api",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"start": "nest start",
|
||||
"start:dev": "nest start --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"lint": "eslint \"{src,test}/**/*.ts\" --fix",
|
||||
"test": "jest --runInBand",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:push": "prisma db push"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codexdash/shared-types": "workspace:*",
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/config": "^4.0.2",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"@nestjs/jwt": "^11.0.1",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@prisma/client": "6.16.2",
|
||||
"argon2": "^0.44.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.2",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
"@eslint/js": "^9.18.0",
|
||||
"@nestjs/cli": "^11.0.0",
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@nestjs/testing": "^11.0.1",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/supertest": "^7.0.0",
|
||||
"eslint": "^9.18.0",
|
||||
"eslint-config-prettier": "^10.0.1",
|
||||
"eslint-plugin-prettier": "^5.2.2",
|
||||
"globals": "^17.0.0",
|
||||
"jest": "^30.0.0",
|
||||
"prettier": "^3.4.2",
|
||||
"prisma": "6.16.2",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.0.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-loader": "^9.5.2",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.7.3",
|
||||
"typescript-eslint": "^8.20.0"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": "src",
|
||||
"testRegex": ".*\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"collectCoverageFrom": ["**/*.(t|j)s"],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
||||
35
apps/api/prisma/schema.prisma
Normal file
35
apps/api/prisma/schema.prisma
Normal file
@@ -0,0 +1,35 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(cuid())
|
||||
email String @unique
|
||||
passwordHash String
|
||||
name String
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
accounts OpenAiAccount[]
|
||||
}
|
||||
|
||||
model OpenAiAccount {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
label String
|
||||
emailHint String?
|
||||
encryptedCookie String
|
||||
lastUsageJson Json?
|
||||
lastSyncedAt DateTime?
|
||||
lastError String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([userId])
|
||||
}
|
||||
13
apps/api/src/app.controller.ts
Normal file
13
apps/api/src/app.controller.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
@Get('health')
|
||||
health() {
|
||||
return {
|
||||
ok: true,
|
||||
service: 'codexdash-api',
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
18
apps/api/src/app.module.ts
Normal file
18
apps/api/src/app.module.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { AppController } from './app.controller';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { CodexModule } from './codex/codex.module';
|
||||
import { PrismaModule } from './prisma/prisma.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true }),
|
||||
PrismaModule,
|
||||
AuthModule,
|
||||
CodexModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [],
|
||||
})
|
||||
export class AppModule {}
|
||||
30
apps/api/src/auth/auth.controller.ts
Normal file
30
apps/api/src/auth/auth.controller.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
CurrentUser,
|
||||
type AuthenticatedUser,
|
||||
} from '../common/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../common/jwt-auth.guard';
|
||||
import { AuthService } from './auth.service';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Post('register')
|
||||
register(@Body() dto: RegisterDto) {
|
||||
return this.authService.register(dto);
|
||||
}
|
||||
|
||||
@Post('login')
|
||||
login(@Body() dto: LoginDto) {
|
||||
return this.authService.login(dto);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('me')
|
||||
me(@CurrentUser() user: AuthenticatedUser) {
|
||||
return this.authService.me(user.sub);
|
||||
}
|
||||
}
|
||||
23
apps/api/src/auth/auth.module.ts
Normal file
23
apps/api/src/auth/auth.module.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtAuthGuard } from '../common/jwt-auth.guard';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule,
|
||||
JwtModule.registerAsync({
|
||||
inject: [ConfigService],
|
||||
useFactory: (configService: ConfigService) => ({
|
||||
secret: configService.get<string>('JWT_SECRET') ?? 'change-me',
|
||||
signOptions: { expiresIn: '30d' },
|
||||
}),
|
||||
}),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, JwtAuthGuard],
|
||||
exports: [JwtModule, JwtAuthGuard],
|
||||
})
|
||||
export class AuthModule {}
|
||||
84
apps/api/src/auth/auth.service.ts
Normal file
84
apps/api/src/auth/auth.service.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as argon2 from 'argon2';
|
||||
import { AuthResponse, UserProfile } from '@codexdash/shared-types';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
async register(dto: RegisterDto): Promise<AuthResponse> {
|
||||
const existing = await this.prisma.user.findUnique({
|
||||
where: { email: dto.email.toLowerCase() },
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
throw new ConflictException('Email already registered');
|
||||
}
|
||||
|
||||
const user = await this.prisma.user.create({
|
||||
data: {
|
||||
email: dto.email.toLowerCase(),
|
||||
name: dto.name.trim(),
|
||||
passwordHash: await argon2.hash(dto.password),
|
||||
},
|
||||
});
|
||||
|
||||
return this.toAuthResponse(user);
|
||||
}
|
||||
|
||||
async login(dto: LoginDto): Promise<AuthResponse> {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { email: dto.email.toLowerCase() },
|
||||
});
|
||||
|
||||
if (!user || !(await argon2.verify(user.passwordHash, dto.password))) {
|
||||
throw new UnauthorizedException('Invalid email or password');
|
||||
}
|
||||
|
||||
return this.toAuthResponse(user);
|
||||
}
|
||||
|
||||
async me(userId: string): Promise<UserProfile> {
|
||||
const user = await this.prisma.user.findUniqueOrThrow({
|
||||
where: { id: userId },
|
||||
});
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
createdAt: user.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
private async toAuthResponse(user: {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
createdAt: Date;
|
||||
}): Promise<AuthResponse> {
|
||||
return {
|
||||
token: await this.jwtService.signAsync({
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
}),
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
createdAt: user.createdAt.toISOString(),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
11
apps/api/src/auth/dto/login.dto.ts
Normal file
11
apps/api/src/auth/dto/login.dto.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||
import { LoginInput } from '@codexdash/shared-types';
|
||||
|
||||
export class LoginDto implements LoginInput {
|
||||
@IsEmail()
|
||||
email!: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password!: string;
|
||||
}
|
||||
15
apps/api/src/auth/dto/register.dto.ts
Normal file
15
apps/api/src/auth/dto/register.dto.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||
import { RegisterInput } from '@codexdash/shared-types';
|
||||
|
||||
export class RegisterDto implements RegisterInput {
|
||||
@IsEmail()
|
||||
email!: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password!: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(2)
|
||||
name!: string;
|
||||
}
|
||||
52
apps/api/src/codex/codex.controller.ts
Normal file
52
apps/api/src/codex/codex.controller.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
CurrentUser,
|
||||
type AuthenticatedUser,
|
||||
} from '../common/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../common/jwt-auth.guard';
|
||||
import { CodexService } from './codex.service';
|
||||
import { ConnectAccountDto } from './dto/connect-account.dto';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('codex')
|
||||
export class CodexController {
|
||||
constructor(private readonly codexService: CodexService) {}
|
||||
|
||||
@Get('accounts')
|
||||
listAccounts(@CurrentUser() user: AuthenticatedUser) {
|
||||
return this.codexService.listAccounts(user.sub);
|
||||
}
|
||||
|
||||
@Post('accounts')
|
||||
connectAccount(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Body() dto: ConnectAccountDto,
|
||||
) {
|
||||
return this.codexService.connectAccount(user.sub, dto);
|
||||
}
|
||||
|
||||
@Delete('accounts/:accountId')
|
||||
deleteAccount(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Param('accountId') accountId: string,
|
||||
) {
|
||||
return this.codexService.deleteAccount(user.sub, accountId);
|
||||
}
|
||||
|
||||
@Get('usage-summary')
|
||||
getUsageSummary(
|
||||
@CurrentUser() user: AuthenticatedUser,
|
||||
@Query('refresh') refresh?: string,
|
||||
) {
|
||||
return this.codexService.getUsageSummary(user.sub, refresh !== 'false');
|
||||
}
|
||||
}
|
||||
11
apps/api/src/codex/codex.module.ts
Normal file
11
apps/api/src/codex/codex.module.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { CodexController } from './codex.controller';
|
||||
import { CodexService } from './codex.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [CodexController],
|
||||
providers: [CodexService],
|
||||
})
|
||||
export class CodexModule {}
|
||||
172
apps/api/src/codex/codex.service.ts
Normal file
172
apps/api/src/codex/codex.service.ts
Normal file
@@ -0,0 +1,172 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { ConnectedAccount, UsageSummary } from '@codexdash/shared-types';
|
||||
import { decryptString, encryptString } from '../common/crypto';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { ConnectAccountDto } from './dto/connect-account.dto';
|
||||
import { aggregateUsagePayloads } from './usage-aggregator';
|
||||
|
||||
type UsageApiResponse = Record<string, unknown>;
|
||||
|
||||
@Injectable()
|
||||
export class CodexService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
async connectAccount(
|
||||
userId: string,
|
||||
dto: ConnectAccountDto,
|
||||
): Promise<ConnectedAccount> {
|
||||
const usage = await this.fetchUsage(dto.cookieHeader);
|
||||
const account = await this.prisma.openAiAccount.create({
|
||||
data: {
|
||||
userId,
|
||||
label: dto.label.trim(),
|
||||
emailHint: dto.emailHint?.trim() || null,
|
||||
encryptedCookie: encryptString(
|
||||
dto.cookieHeader,
|
||||
this.getEncryptionSecret(),
|
||||
),
|
||||
lastUsageJson: usage as Prisma.InputJsonValue,
|
||||
lastSyncedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return this.toAccountView(account);
|
||||
}
|
||||
|
||||
async listAccounts(userId: string) {
|
||||
const accounts = await this.prisma.openAiAccount.findMany({
|
||||
where: { userId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
return accounts.map((account) => this.toAccountView(account));
|
||||
}
|
||||
|
||||
async deleteAccount(userId: string, accountId: string) {
|
||||
const account = await this.prisma.openAiAccount.findFirst({
|
||||
where: { id: accountId, userId },
|
||||
});
|
||||
if (!account) {
|
||||
throw new NotFoundException('Connected account not found');
|
||||
}
|
||||
|
||||
await this.prisma.openAiAccount.delete({ where: { id: accountId } });
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
async getUsageSummary(userId: string, refresh = true): Promise<UsageSummary> {
|
||||
const accounts = await this.prisma.openAiAccount.findMany({
|
||||
where: { userId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
const resolvedAccounts = await Promise.all(
|
||||
accounts.map(async (account) => {
|
||||
if (!refresh) {
|
||||
return account;
|
||||
}
|
||||
|
||||
try {
|
||||
const usage = await this.fetchUsage(
|
||||
decryptString(account.encryptedCookie, this.getEncryptionSecret()),
|
||||
);
|
||||
return this.prisma.openAiAccount.update({
|
||||
where: { id: account.id },
|
||||
data: {
|
||||
lastUsageJson: usage as Prisma.InputJsonValue,
|
||||
lastSyncedAt: new Date(),
|
||||
lastError: null,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return this.prisma.openAiAccount.update({
|
||||
where: { id: account.id },
|
||||
data: {
|
||||
lastError:
|
||||
error instanceof Error ? error.message : 'Unknown error',
|
||||
},
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const accountViews = resolvedAccounts.map((account) =>
|
||||
this.toAccountView(account),
|
||||
);
|
||||
|
||||
return {
|
||||
aggregatedUsage: aggregateUsagePayloads(
|
||||
accountViews.map((account) => account.usage),
|
||||
),
|
||||
accounts: accountViews,
|
||||
totals: {
|
||||
totalAccounts: accountViews.length,
|
||||
activeAccounts: accountViews.filter(
|
||||
(account) => account.status === 'active',
|
||||
).length,
|
||||
erroredAccounts: accountViews.filter(
|
||||
(account) => account.status === 'error',
|
||||
).length,
|
||||
},
|
||||
refreshedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchUsage(cookieHeader: string): Promise<UsageApiResponse> {
|
||||
const response = await fetch(
|
||||
'https://chatgpt.com/backend-api/api/codex/usage',
|
||||
{
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
cookie: cookieHeader,
|
||||
'user-agent': 'CodexDash/0.1 (+https://example.invalid)',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new BadRequestException(
|
||||
`Codex usage request failed with status ${response.status}`,
|
||||
);
|
||||
}
|
||||
|
||||
return (await response.json()) as UsageApiResponse;
|
||||
}
|
||||
|
||||
private getEncryptionSecret() {
|
||||
return (
|
||||
this.configService.get<string>('ENCRYPTION_SECRET') ??
|
||||
'change-me-32-characters-minimum'
|
||||
);
|
||||
}
|
||||
|
||||
private toAccountView(account: {
|
||||
id: string;
|
||||
label: string;
|
||||
emailHint: string | null;
|
||||
lastUsageJson: unknown;
|
||||
lastSyncedAt: Date | null;
|
||||
lastError: string | null;
|
||||
createdAt: Date;
|
||||
}): ConnectedAccount {
|
||||
return {
|
||||
id: account.id,
|
||||
label: account.label,
|
||||
emailHint: account.emailHint,
|
||||
status: account.lastError ? 'error' : 'active',
|
||||
lastSyncedAt: account.lastSyncedAt?.toISOString() ?? null,
|
||||
lastError: account.lastError,
|
||||
usage: (account.lastUsageJson as Record<string, unknown> | null) ?? null,
|
||||
createdAt: account.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
16
apps/api/src/codex/dto/connect-account.dto.ts
Normal file
16
apps/api/src/codex/dto/connect-account.dto.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { IsOptional, IsString, MinLength } from 'class-validator';
|
||||
import { ConnectAccountInput } from '@codexdash/shared-types';
|
||||
|
||||
export class ConnectAccountDto implements ConnectAccountInput {
|
||||
@IsString()
|
||||
@MinLength(2)
|
||||
label!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
emailHint?: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(20)
|
||||
cookieHeader!: string;
|
||||
}
|
||||
24
apps/api/src/codex/usage-aggregator.spec.ts
Normal file
24
apps/api/src/codex/usage-aggregator.spec.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { aggregateUsagePayloads } from './usage-aggregator';
|
||||
|
||||
describe('aggregateUsagePayloads', () => {
|
||||
it('sums nested numeric values while preserving useful metadata', () => {
|
||||
const result = aggregateUsagePayloads([
|
||||
{
|
||||
limit: { used: 10, remaining: 90, unit: 'requests' },
|
||||
plan: 'pro',
|
||||
buckets: [{ used: 2 }, { used: 3 }],
|
||||
},
|
||||
{
|
||||
limit: { used: 25, remaining: 75, unit: 'requests' },
|
||||
plan: 'pro',
|
||||
buckets: [{ used: 4 }, { used: 1 }],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toEqual({
|
||||
limit: { used: 35, remaining: 165, unit: 'requests' },
|
||||
plan: 'pro',
|
||||
buckets: [{ used: 6 }, { used: 4 }],
|
||||
});
|
||||
});
|
||||
});
|
||||
60
apps/api/src/codex/usage-aggregator.ts
Normal file
60
apps/api/src/codex/usage-aggregator.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
type JsonValue =
|
||||
| null
|
||||
| boolean
|
||||
| number
|
||||
| string
|
||||
| JsonValue[]
|
||||
| { [key: string]: JsonValue };
|
||||
|
||||
const isObject = (value: JsonValue): value is { [key: string]: JsonValue } =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
|
||||
function mergeValues(values: JsonValue[]): JsonValue {
|
||||
const filtered = values.filter((value) => value !== null);
|
||||
if (filtered.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (filtered.every((value) => typeof value === 'number')) {
|
||||
return filtered.reduce((sum, value) => sum + value, 0);
|
||||
}
|
||||
|
||||
if (filtered.every((value) => Array.isArray(value))) {
|
||||
const arrays = filtered as JsonValue[][];
|
||||
const maxLength = Math.max(...arrays.map((array) => array.length));
|
||||
return Array.from({ length: maxLength }, (_, index) =>
|
||||
mergeValues(arrays.map((array) => array[index] ?? null)),
|
||||
);
|
||||
}
|
||||
|
||||
if (filtered.every((value) => isObject(value))) {
|
||||
const keys = [...new Set(filtered.flatMap((value) => Object.keys(value)))];
|
||||
return Object.fromEntries(
|
||||
keys.map((key) => [
|
||||
key,
|
||||
mergeValues(
|
||||
filtered.map(
|
||||
(value) => (value as Record<string, JsonValue>)[key] ?? null,
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
const unique = [
|
||||
...new Set(filtered.map((value) => JSON.stringify(value))),
|
||||
].map((value) => JSON.parse(value) as JsonValue);
|
||||
return unique.length === 1 ? unique[0] : unique[0];
|
||||
}
|
||||
|
||||
export function aggregateUsagePayloads(
|
||||
payloads: Array<Record<string, unknown> | null | undefined>,
|
||||
) {
|
||||
const normalized = payloads.filter(Boolean) as Array<Record<string, unknown>>;
|
||||
|
||||
if (normalized.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return mergeValues(normalized as JsonValue[]) as Record<string, unknown>;
|
||||
}
|
||||
37
apps/api/src/common/crypto.ts
Normal file
37
apps/api/src/common/crypto.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import {
|
||||
createCipheriv,
|
||||
createDecipheriv,
|
||||
createHash,
|
||||
randomBytes,
|
||||
} from 'node:crypto';
|
||||
|
||||
const ALGORITHM = 'aes-256-gcm';
|
||||
|
||||
function getKey(secret: string) {
|
||||
return createHash('sha256').update(secret).digest();
|
||||
}
|
||||
|
||||
export function encryptString(value: string, secret: string) {
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv(ALGORITHM, getKey(secret), iv);
|
||||
const encrypted = Buffer.concat([
|
||||
cipher.update(value, 'utf8'),
|
||||
cipher.final(),
|
||||
]);
|
||||
const tag = cipher.getAuthTag();
|
||||
|
||||
return Buffer.concat([iv, tag, encrypted]).toString('base64url');
|
||||
}
|
||||
|
||||
export function decryptString(value: string, secret: string) {
|
||||
const buffer = Buffer.from(value, 'base64url');
|
||||
const iv = buffer.subarray(0, 12);
|
||||
const tag = buffer.subarray(12, 28);
|
||||
const encrypted = buffer.subarray(28);
|
||||
const decipher = createDecipheriv(ALGORITHM, getKey(secret), iv);
|
||||
decipher.setAuthTag(tag);
|
||||
|
||||
return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString(
|
||||
'utf8',
|
||||
);
|
||||
}
|
||||
16
apps/api/src/common/current-user.decorator.ts
Normal file
16
apps/api/src/common/current-user.decorator.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
|
||||
export type AuthenticatedUser = {
|
||||
sub: string;
|
||||
email: string;
|
||||
};
|
||||
|
||||
type RequestWithUser = Request & { user?: AuthenticatedUser };
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_: unknown, ctx: ExecutionContext) => {
|
||||
const request = ctx.switchToHttp().getRequest<RequestWithUser>();
|
||||
return request.user as AuthenticatedUser;
|
||||
},
|
||||
);
|
||||
42
apps/api/src/common/jwt-auth.guard.ts
Normal file
42
apps/api/src/common/jwt-auth.guard.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { Request } from 'express';
|
||||
import type { AuthenticatedUser } from './current-user.decorator';
|
||||
|
||||
type RequestWithUser = Request & { user?: AuthenticatedUser };
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
||||
const authorization = request.headers.authorization;
|
||||
|
||||
if (!authorization?.startsWith('Bearer ')) {
|
||||
throw new UnauthorizedException('Missing bearer token');
|
||||
}
|
||||
|
||||
try {
|
||||
const token = authorization.slice('Bearer '.length);
|
||||
request.user = await this.jwtService.verifyAsync<AuthenticatedUser>(
|
||||
token,
|
||||
{
|
||||
secret: this.configService.get<string>('JWT_SECRET') ?? 'change-me',
|
||||
},
|
||||
);
|
||||
return true;
|
||||
} catch {
|
||||
throw new UnauthorizedException('Invalid token');
|
||||
}
|
||||
}
|
||||
}
|
||||
18
apps/api/src/main.ts
Normal file
18
apps/api/src/main.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
app.enableCors({ origin: true, credentials: true });
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
transform: true,
|
||||
forbidNonWhitelisted: true,
|
||||
}),
|
||||
);
|
||||
|
||||
await app.listen(process.env.PORT ?? 3001);
|
||||
}
|
||||
void bootstrap();
|
||||
9
apps/api/src/prisma/prisma.module.ts
Normal file
9
apps/api/src/prisma/prisma.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class PrismaModule {}
|
||||
16
apps/api/src/prisma/prisma.service.ts
Normal file
16
apps/api/src/prisma/prisma.service.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService
|
||||
extends PrismaClient
|
||||
implements OnModuleInit, OnModuleDestroy
|
||||
{
|
||||
async onModuleInit() {
|
||||
await this.$connect();
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
await this.$disconnect();
|
||||
}
|
||||
}
|
||||
29
apps/api/test/app.e2e-spec.ts
Normal file
29
apps/api/test/app.e2e-spec.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { App } from 'supertest/types';
|
||||
import { AppModule } from './../src/app.module';
|
||||
|
||||
describe('AppController (e2e)', () => {
|
||||
let app: INestApplication<App>;
|
||||
|
||||
beforeEach(async () => {
|
||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
|
||||
app = moduleFixture.createNestApplication();
|
||||
await app.init();
|
||||
});
|
||||
|
||||
it('/ (GET)', () => {
|
||||
return request(app.getHttpServer())
|
||||
.get('/')
|
||||
.expect(200)
|
||||
.expect('Hello World!');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
9
apps/api/test/jest-e2e.json
Normal file
9
apps/api/test/jest-e2e.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"moduleFileExtensions": ["js", "json", "ts"],
|
||||
"rootDir": ".",
|
||||
"testEnvironment": "node",
|
||||
"testRegex": ".e2e-spec.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
}
|
||||
}
|
||||
4
apps/api/tsconfig.build.json
Normal file
4
apps/api/tsconfig.build.json
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
}
|
||||
25
apps/api/tsconfig.json
Normal file
25
apps/api/tsconfig.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "nodenext",
|
||||
"moduleResolution": "nodenext",
|
||||
"resolvePackageJsonExports": true,
|
||||
"esModuleInterop": true,
|
||||
"isolatedModules": true,
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2023",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strictNullChecks": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noImplicitAny": true,
|
||||
"strictBindCallApply": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user