From c13356b51e4fe512e99e80784500508ea0ac5be9 Mon Sep 17 00:00:00 2001 From: Zack Schuster Date: Fri, 30 Oct 2020 13:46:42 -0700 Subject: [PATCH] smtp/date: add isRFC2822Date api & use in tests --- smtp/date.ts | 15 +++++++++++++++ test/date.ts | 15 ++++++--------- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/smtp/date.ts b/smtp/date.ts index 00ed767..2bb81f6 100644 --- a/smtp/date.ts +++ b/smtp/date.ts @@ -33,3 +33,18 @@ export function getRFC2822DateUTC(date = new Date()) { dates.push('+0000'); return dates.join(' '); } + +/** + * RFC 2822 regex + * @see https://tools.ietf.org/html/rfc2822#section-3.3 + * @see https://github.com/moment/moment/blob/a831fc7e2694281ce31e4f090bbcf90a690f0277/src/lib/create/from-string.js#L101 + */ +const rfc2822re = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/.compile(); + +/** + * @param {string} [date] a string to check for conformance to the [rfc2822](https://tools.ietf.org/html/rfc2822#section-3.3) standard + * @returns {boolean} the result of the conformance check + */ +export function isRFC2822Date(date: string) { + return rfc2822re.test(date); +} diff --git a/test/date.ts b/test/date.ts index 7f3ab00..57a36a8 100644 --- a/test/date.ts +++ b/test/date.ts @@ -1,18 +1,15 @@ import test from 'ava'; -import { getRFC2822Date, getRFC2822DateUTC } from '../email'; +import { getRFC2822Date, getRFC2822DateUTC, isRFC2822Date } from '../email'; const toD_utc = (dt: number) => getRFC2822DateUTC(new Date(dt)); const toD = (dt: number, utc = false) => getRFC2822Date(new Date(dt), utc); test('rfc2822 non-UTC', async (t) => { - // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 - // thanks to moment.js for the listing: https://github.com/moment/moment/blob/a831fc7e2694281ce31e4f090bbcf90a690f0277/src/lib/create/from-string.js#L101 - const rfc2822re = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/; - t.regex(toD(0), rfc2822re); - t.regex(toD(329629726785), rfc2822re); - t.regex(toD(729629726785), rfc2822re); - t.regex(toD(1129629726785), rfc2822re); - t.regex(toD(1529629726785), rfc2822re); + t.true(isRFC2822Date(toD(0))); + t.true(isRFC2822Date(toD(329629726785))); + t.true(isRFC2822Date(toD(729629726785))); + t.true(isRFC2822Date(toD(1129629726785))); + t.true(isRFC2822Date(toD(1529629726785))); }); test('rfc2822 UTC', async (t) => {