Skip to content
Open
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
9 changes: 8 additions & 1 deletion apps/site/env.example
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,11 @@ INTERNAL_ORDER_EMAIL_TO="orders@toddagriscience.com"
# New Relic keys for monitoring. Private.
NEW_RELIC_ENABLED="false"
NEW_RELIC_APP_NAME="TODD_SITE_TESTING"
NEW_RELIC_LICENSE_KEY="secret"
NEW_RELIC_LICENSE_KEY="secret"

# Upstash Redis for IP-based rate limiting on public write endpoints (contact
# form, CMS forms). Optional — when unset, rate limiting fails open (allows
# requests) so local dev / CI / preview keep working. Provision via the Vercel
# Marketplace Upstash integration, which injects these automatically.
UPSTASH_REDIS_REST_URL="https://your-db.upstash.io"
UPSTASH_REDIS_REST_TOKEN="your-token"
2 changes: 2 additions & 0 deletions apps/site/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@
"@supabase/ssr": "^0.10.0",
"@supabase/supabase-js": "^2.102.1",
"@types/ua-parser-js": "^0.7.39",
"@upstash/ratelimit": "^2.0.8",
"@upstash/redis": "^1.38.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"drizzle-orm": "^0.45.2",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
submitContactToSheets: vi.fn(),
loggerError: vi.fn(),
enforceRateLimit: vi.fn(),
}));

vi.mock('@/lib/actions/googleSheets', () => ({
Expand All @@ -15,6 +16,10 @@ vi.mock('@/lib/logger', () => ({
default: { error: mocks.loggerError },
}));

vi.mock('@/lib/rate-limit', () => ({
enforceRateLimit: mocks.enforceRateLimit,
}));

import { submitPublicInquiry } from './actions';

/**
Expand All @@ -33,9 +38,27 @@ function makeFormData(fields: Record<string, string | undefined>) {

beforeEach(() => {
vi.clearAllMocks();
mocks.enforceRateLimit.mockResolvedValue(undefined);
});

describe('submitPublicInquiry', () => {
it('throws and skips submission when rate limited', async () => {
mocks.enforceRateLimit.mockRejectedValueOnce(
new Error('Too many requests. Please try again shortly.')
);

const fd = makeFormData({
name: 'Inban',
lastKnownEmail: 'inban@example.com',
response: 'Hello!',
});

await expect(submitPublicInquiry(fd)).rejects.toThrow(
'Too many requests. Please try again shortly.'
);
expect(mocks.submitContactToSheets).not.toHaveBeenCalled();
});

it('returns success and submits to the contact sheet when inputs are valid', async () => {
mocks.submitContactToSheets.mockResolvedValueOnce(undefined);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import { submitContactToSheets } from '@/lib/actions/googleSheets';
import logger from '@/lib/logger';
import { enforceRateLimit } from '@/lib/rate-limit';
import type { ActionResponse } from '@/lib/types/action-response';
import { throwActionError } from '@/lib/utils/actions';
import z from 'zod';
Expand All @@ -30,6 +31,8 @@ function getString(formData: FormData, key: string): string {
export async function submitPublicInquiry(
formData: FormData
): Promise<ActionResponse> {
await enforceRateLimit();

const raw = {
name: getString(formData, 'name'),
lastKnownEmail: getString(formData, 'lastKnownEmail'),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Copyright © Todd Agriscience, Inc. All rights reserved.

import { beforeEach, describe, expect, it, vi } from 'vitest';

const mocks = vi.hoisted(() => ({
getFormBySlug: vi.fn(),
insert: vi.fn(),
values: vi.fn(),
returning: vi.fn(),
loggerWarn: vi.fn(),
loggerError: vi.fn(),
enforceRateLimit: vi.fn(),
}));

vi.mock('@/lib/sanity/forms', () => ({
getFormBySlug: mocks.getFormBySlug,
}));

vi.mock('@nightcrawler/db', () => ({
db: { insert: mocks.insert },
}));

vi.mock('@nightcrawler/db/schema', () => ({
formSubmission: { id: 'id' },
}));

vi.mock('@nightcrawler/db/utils/extract-applicant-prefill', () => ({
enrichStoredAnswersWithSignupPrefill: (answers: unknown) => answers,
}));

vi.mock('@/lib/logger', () => ({
logger: { warn: mocks.loggerWarn, error: mocks.loggerError },
default: { warn: mocks.loggerWarn, error: mocks.loggerError },
}));

vi.mock('@/lib/rate-limit', () => ({
enforceRateLimit: mocks.enforceRateLimit,
}));

vi.mock('./utils', () => ({
buildFormAnswersSchema: () => ({
safeParse: (data: unknown) => ({ success: true, data }),
}),
buildStoredFormAnswers: (data: Record<string, unknown>) => data,
flattenFormFields: () => [],
FORM_HONEYPOT_FIELD: '_hp',
readRetentionConsentFromValues: () => false,
resolveFormFooterCheckboxes: () => [],
resolveFormSections: () => [],
}));

import { submitFormSubmission } from './actions';

beforeEach(() => {
vi.clearAllMocks();
mocks.enforceRateLimit.mockResolvedValue(undefined);
mocks.getFormBySlug.mockResolvedValue({ workflowType: 'generic' });

// db.insert(...).values(...).returning(...) fluent chain
mocks.returning.mockResolvedValue([{ id: 'row-1' }]);
mocks.values.mockReturnValue({ returning: mocks.returning });
mocks.insert.mockReturnValue({ values: mocks.values });
});

describe('submitFormSubmission', () => {
it('throws and skips the db insert when rate limited', async () => {
mocks.enforceRateLimit.mockRejectedValueOnce(
new Error('Too many requests. Please try again shortly.')
);

await expect(
submitFormSubmission({ formSlug: 'demo', answers: {} })
).rejects.toThrow('Too many requests. Please try again shortly.');

expect(mocks.getFormBySlug).not.toHaveBeenCalled();
expect(mocks.insert).not.toHaveBeenCalled();
});

it('persists the submission when allowed', async () => {
const result = await submitFormSubmission({
formSlug: 'demo',
answers: { foo: 'bar' },
});

expect(mocks.enforceRateLimit).toHaveBeenCalledTimes(1);
expect(mocks.insert).toHaveBeenCalledTimes(1);
expect(result).toEqual({ data: { id: 'row-1' } });
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { SanityFormWorkflowType } from '@/lib/sanity/form-types';
import { db } from '@nightcrawler/db';
import { formSubmission } from '@nightcrawler/db/schema';
import { logger } from '@/lib/logger';
import { enforceRateLimit } from '@/lib/rate-limit';
import type { ActionResponse } from '@/lib/types/action-response';
import { throwActionError } from '@/lib/utils/actions';
import z from 'zod';
Expand Down Expand Up @@ -50,6 +51,8 @@ function resolveWorkflowType(
export async function submitFormSubmission(
input: SubmitFormSubmissionInput
): Promise<ActionResponse> {
await enforceRateLimit();

const form = await getFormBySlug(input.formSlug, { cache: 'no-store' });
if (!form) {
throwActionError('This form is not available.');
Expand Down
Loading
Loading