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
5 changes: 5 additions & 0 deletions lib/validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,15 @@ export function truncateToCharLength (value, maxLength) {
return out
}

export function hasUrlProtocol (value) {
return /\b[a-z][a-z0-9+.-]*:\/\//i.test(value || '')
}

const titleValidator = string().required('required').trim().max(
MAX_TITLE_LENGTH,
({ max, value }) => `-${Math.abs(max - value.length)} characters remaining`
).min(MIN_TITLE_LENGTH, `must be at least ${MIN_TITLE_LENGTH} characters`)
.test('no-url-protocol', 'title cannot contain URLs', value => !hasUrlProtocol(value))

const textValidator = (max) => string().trim().max(
max,
Expand Down
40 changes: 40 additions & 0 deletions lib/validate.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/* eslint-env jest */

import { bountySchema, discussionSchema, hasUrlProtocol, jobSchema, linkSchema, pollSchema } from './validate'

const mockArgs = (postTypes = ['DISCUSSION', 'LINK', 'POLL', 'BOUNTY']) => ({
models: {
sub: {
findMany: jest.fn(async ({ where: { name: { in: subNames } } }) =>
subNames.map(name => ({ name, status: 'ACTIVE', postTypes })))
}
}
})

describe('title validation', () => {
test('detects URL protocols without rejecting bare domains or non-URL URI schemes', () => {
expect(hasUrlProtocol('https://stacker.news')).toBe(true)
expect(hasUrlProtocol('See ftp://example.com')).toBe(true)
expect(hasUrlProtocol('Crypto.com stadium hosts big game')).toBe(false)
expect(hasUrlProtocol('example.com/path')).toBe(false)
expect(hasUrlProtocol('mailto:jobs@example.com')).toBe(false)
})

test.each([
['discussion', discussionSchema(mockArgs()), { subNames: ['bitcoin'], title: 'https://example.com', text: '' }],
['link', linkSchema(mockArgs()), { subNames: ['bitcoin'], title: 'Read https://example.com', url: 'https://stacker.news', text: '' }],
['poll', pollSchema({ ...mockArgs(), numExistingChoices: 0 }), { subNames: ['bitcoin'], title: 'ftp://example.com', options: ['yes', 'no'] }],
['bounty', bountySchema(mockArgs()), { subNames: ['bitcoin'], title: 'bitcoin://invoice', text: '', bounty: 1000 }],
['job', jobSchema(mockArgs()), { title: 'Apply at https://example.com', company: 'SN', text: 'job', url: 'jobs@example.com', remote: true }]
])('rejects URL protocols in %s titles', async (_name, schema, value) => {
await expect(schema.validate(value)).rejects.toThrow('title cannot contain URLs')
})

test('allows bare domains in titles', async () => {
await expect(discussionSchema(mockArgs()).validate({
subNames: ['bitcoin'],
title: 'Crypto.com stadium hosts big game',
text: ''
})).resolves.toMatchObject({ title: 'Crypto.com stadium hosts big game' })
})
})