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
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"class-transformer": "^0.5.1",
"class-validator": "^0.14.4",
"helmet": "^8.1.0",
"nodemailer": "^9.0.5",
"passport-jwt": "^4.0.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2",
Expand All @@ -52,6 +53,7 @@
"@types/express": "^5.0.6",
"@types/jest": "^30.0.0",
"@types/node": "^22.19.17",
"@types/nodemailer": "^8.0.1",
"@types/passport-jwt": "^4.0.1",
"@types/supertest": "^6.0.3",
"eslint": "^9.39.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/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { DashboardModule } from './v1/dashboard/dashboard.module';
import { PaymentsModule } from './v1/payments/payments.module';
import { LineModule } from './v1/line/line.module';
import { PushModule } from './v1/push/push.module';
import { AccountRemovalModule } from './v1/account-removal/account-removal.module';
import { CropwatchMcpModule } from './v1/mcp/mcp.module';

@Module({
Expand Down Expand Up @@ -72,6 +73,7 @@ import { CropwatchMcpModule } from './v1/mcp/mcp.module';
PaymentsModule,
LineModule,
PushModule,
AccountRemovalModule,
CropwatchMcpModule,
],
controllers: [AppController],
Expand Down
54 changes: 54 additions & 0 deletions src/v1/account-removal/account-removal.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import {
Body,
Controller,
Get,
HttpCode,
HttpStatus,
Post,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Throttle } from '@nestjs/throttler';
import {
AccountRemovalService,
type AccountRemovalChallenge,
} from './account-removal.service';
import { RequestAccountRemovalDto } from './dto/request-account-removal.dto';

// Public, unauthenticated endpoints. Anonymous callers are IP-keyed by
// UserThrottlerGuard (trust proxy is pinned in main.ts), so these tight
// per-route limits track the real client, not Vercel's shared egress —
// provided the browser calls the API directly rather than via SSR.
@ApiTags('account-removal')
@Controller({ path: 'account-removal', version: '1' })
export class AccountRemovalController {
constructor(

Check failure on line 24 in src/v1/account-removal/account-removal.controller.ts

View workflow job for this annotation

GitHub Actions / build

Replace `⏎····private·readonly·accountRemovalService:·AccountRemovalService,⏎··` with `private·readonly·accountRemovalService:·AccountRemovalService`

Check failure on line 24 in src/v1/account-removal/account-removal.controller.ts

View workflow job for this annotation

GitHub Actions / build

Replace `⏎····private·readonly·accountRemovalService:·AccountRemovalService,⏎··` with `private·readonly·accountRemovalService:·AccountRemovalService`
private readonly accountRemovalService: AccountRemovalService,
) {}

@Throttle({ default: { ttl: 60_000, limit: 10 } })
@Get('challenge')
@ApiOperation({
summary: 'Issue a human-verification math challenge (public)',
})
getChallenge(): AccountRemovalChallenge {
return this.accountRemovalService.createChallenge();
}

@Throttle({ default: { ttl: 60_000, limit: 3 } })
@Post('request')
@HttpCode(HttpStatus.ACCEPTED)
@ApiOperation({
summary:

Check failure on line 41 in src/v1/account-removal/account-removal.controller.ts

View workflow job for this annotation

GitHub Actions / build

Delete `⏎·····`

Check failure on line 41 in src/v1/account-removal/account-removal.controller.ts

View workflow job for this annotation

GitHub Actions / build

Delete `⏎·····`
'Submit an account removal request (public; emails the operators)',
})
async submitRequest(
@Body() body: RequestAccountRemovalDto,
): Promise<{ requested: boolean }> {
this.accountRemovalService.verifyChallenge(body.answer, body.token);
await this.accountRemovalService.sendRemovalRequest(
body.email,
body.message,
);
return { requested: true };
}
}
11 changes: 11 additions & 0 deletions src/v1/account-removal/account-removal.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AccountRemovalController } from './account-removal.controller';
import { AccountRemovalService } from './account-removal.service';

@Module({
imports: [ConfigModule],
controllers: [AccountRemovalController],
providers: [AccountRemovalService],
})
export class AccountRemovalModule {}
119 changes: 119 additions & 0 deletions src/v1/account-removal/account-removal.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import {
BadRequestException,
ServiceUnavailableException,
} from '@nestjs/common';
import type { ConfigService } from '@nestjs/config';
import { AccountRemovalService } from './account-removal.service';

const sendMailMock = jest.fn();

jest.mock('nodemailer', () => ({
createTransport: jest.fn(() => ({ sendMail: sendMailMock })),
}));

function buildService(
overrides: Record<string, string | undefined> = {},
): AccountRemovalService {
const values: Record<string, string | undefined> = {
PRIVATE_SUPABASE_JWT_SECRET: 'test-secret',
SMTP_HOST: 'smtp.example.com',
SMTP_PORT: '465',
SMTP_USER: 'noreply@example.com',
SMTP_PASS: 'hunter2',
...overrides,
};
const configService = {
get: jest.fn((key: string) => values[key]),
} as unknown as ConfigService;
return new AccountRemovalService(configService);
}

describe('AccountRemovalService', () => {
beforeEach(() => {
sendMailMock.mockReset();
sendMailMock.mockResolvedValue(undefined);
});

describe('challenge', () => {
it('issues a solvable challenge that verifies with the correct answer', () => {
const service = buildService();
const challenge = service.createChallenge();

const [a, b] = challenge.question.split(' + ').map(Number);
expect(Number.isInteger(a)).toBe(true);
expect(Number.isInteger(b)).toBe(true);

expect(() => service.verifyChallenge(a + b, challenge.token)).not.toThrow();

Check failure on line 46 in src/v1/account-removal/account-removal.service.spec.ts

View workflow job for this annotation

GitHub Actions / build

Replace `·service.verifyChallenge(a·+·b,·challenge.token)` with `⏎········service.verifyChallenge(a·+·b,·challenge.token),⏎······`

Check failure on line 46 in src/v1/account-removal/account-removal.service.spec.ts

View workflow job for this annotation

GitHub Actions / build

Replace `·service.verifyChallenge(a·+·b,·challenge.token)` with `⏎········service.verifyChallenge(a·+·b,·challenge.token),⏎······`
});

it('rejects a wrong answer', () => {
const service = buildService();
const challenge = service.createChallenge();
const [a, b] = challenge.question.split(' + ').map(Number);

expect(() => service.verifyChallenge(a + b + 1, challenge.token)).toThrow(
BadRequestException,
);
});

it('rejects an expired token', () => {
const service = buildService();
const challenge = service.createChallenge();
const [a, b] = challenge.question.split(' + ').map(Number);
const [, signature] = challenge.token.split('.');
const expiredToken = `${Date.now() - 1000}.${signature}`;

expect(() => service.verifyChallenge(a + b, expiredToken)).toThrow(
/expired/i,
);
});

it('rejects a malformed token', () => {
const service = buildService();
expect(() => service.verifyChallenge(4, 'not-a-token')).toThrow(
BadRequestException,
);
});

it('fails closed when the signing secret is missing', () => {
const service = buildService({ PRIVATE_SUPABASE_JWT_SECRET: undefined });
expect(() => service.createChallenge()).toThrow(
ServiceUnavailableException,
);
});
});

describe('sendRemovalRequest', () => {
it('emails both operators with the requester email and message', async () => {
const service = buildService();
await service.sendRemovalRequest('leaving@example.com', ' bye now ');

expect(sendMailMock).toHaveBeenCalledTimes(1);
const args = sendMailMock.mock.calls[0][0] as {

Check failure on line 92 in src/v1/account-removal/account-removal.service.spec.ts

View workflow job for this annotation

GitHub Actions / build

Unsafe member access [0] on an `any` value

Check failure on line 92 in src/v1/account-removal/account-removal.service.spec.ts

View workflow job for this annotation

GitHub Actions / build

Unsafe member access [0] on an `any` value
to: string[];
subject: string;
text: string;
};
expect(args.to).toEqual(['kevin@cropwatch.io', 'sayaka@cropwatch.io']);
expect(args.subject).toContain('leaving@example.com');
expect(args.text).toContain('leaving@example.com');
expect(args.text).toContain('bye now');
});

it('fails closed when SMTP is not configured', async () => {
const service = buildService({ SMTP_HOST: undefined });
await expect(
service.sendRemovalRequest('leaving@example.com'),
).rejects.toThrow(ServiceUnavailableException);
expect(sendMailMock).not.toHaveBeenCalled();
});

it('maps transport failures to a 503 without leaking details', async () => {
sendMailMock.mockRejectedValueOnce(new Error('SMTP down'));
const service = buildService();
await expect(
service.sendRemovalRequest('leaving@example.com'),
).rejects.toThrow(ServiceUnavailableException);
});
});
});
Loading
Loading