@meghjs/core 0.6.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -15
- package/dist/core/application.d.ts +50 -0
- package/dist/core/application.js +105 -0
- package/dist/core/application.js.map +1 -1
- package/dist/core/interfaces.d.ts +10 -0
- package/dist/core/router.d.ts +28 -0
- package/dist/core/router.js +26 -1
- package/dist/core/router.js.map +1 -1
- package/dist/core/types.d.ts +3 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/mail/config.d.ts +141 -0
- package/dist/mail/config.js +199 -0
- package/dist/mail/config.js.map +1 -0
- package/dist/mail/errors.d.ts +4 -0
- package/dist/mail/errors.js +12 -0
- package/dist/mail/errors.js.map +1 -0
- package/dist/mail/http-transports.d.ts +44 -0
- package/dist/mail/http-transports.js +319 -0
- package/dist/mail/http-transports.js.map +1 -0
- package/dist/mail/index.d.ts +8 -0
- package/dist/mail/index.js +46 -0
- package/dist/mail/index.js.map +1 -0
- package/dist/mail/mailable.d.ts +34 -0
- package/dist/mail/mailable.js +38 -0
- package/dist/mail/mailable.js.map +1 -0
- package/dist/mail/mailer.d.ts +208 -0
- package/dist/mail/mailer.js +502 -0
- package/dist/mail/mailer.js.map +1 -0
- package/dist/mail/queue.d.ts +32 -0
- package/dist/mail/queue.js +59 -0
- package/dist/mail/queue.js.map +1 -0
- package/dist/mail/transports.d.ts +37 -0
- package/dist/mail/transports.js +152 -0
- package/dist/mail/transports.js.map +1 -0
- package/dist/mail/types.d.ts +95 -0
- package/dist/mail/types.js +3 -0
- package/dist/mail/types.js.map +1 -0
- package/dist/security/headers.d.ts +65 -0
- package/dist/security/headers.js +148 -0
- package/dist/security/headers.js.map +1 -0
- package/dist/security/index.d.ts +3 -0
- package/dist/security/index.js +5 -0
- package/dist/security/index.js.map +1 -1
- package/dist/security/rate-limit.d.ts +129 -0
- package/dist/security/rate-limit.js +260 -0
- package/dist/security/rate-limit.js.map +1 -0
- package/package.json +10 -13
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ArrayTransport = exports.FailoverTransport = exports.LogTransport = exports.SmtpTransport = void 0;
|
|
4
|
+
exports.smtpTransportOptions = smtpTransportOptions;
|
|
5
|
+
exports.toNodemailerMessage = toNodemailerMessage;
|
|
6
|
+
const internal_logger_1 = require("../observability/internal-logger");
|
|
7
|
+
const errors_1 = require("./errors");
|
|
8
|
+
function requireNodemailer() {
|
|
9
|
+
try {
|
|
10
|
+
return require("nodemailer");
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
throw new errors_1.MailError("The smtp mailer needs nodemailer, which is not installed.\nRun: npm install nodemailer");
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** Nodemailer transport options for an SMTP mailer. */
|
|
17
|
+
function smtpTransportOptions(config) {
|
|
18
|
+
if (!config.host && !config.options) {
|
|
19
|
+
throw new errors_1.MailError("The smtp mailer has no host. Set MEGH_MAIL_HOST in .env, or pass mailers.smtp.host to app.useMail().");
|
|
20
|
+
}
|
|
21
|
+
const secure = config.encryption
|
|
22
|
+
? config.encryption === "ssl"
|
|
23
|
+
: config.port === 465;
|
|
24
|
+
const options = {
|
|
25
|
+
host: config.host,
|
|
26
|
+
port: config.port,
|
|
27
|
+
secure,
|
|
28
|
+
};
|
|
29
|
+
if (config.encryption === "tls")
|
|
30
|
+
options.requireTLS = true;
|
|
31
|
+
if (config.username)
|
|
32
|
+
options.auth = { user: config.username, pass: config.password ?? "" };
|
|
33
|
+
for (const key of Object.keys(options))
|
|
34
|
+
if (options[key] === undefined)
|
|
35
|
+
delete options[key];
|
|
36
|
+
return { ...options, ...config.options };
|
|
37
|
+
}
|
|
38
|
+
/** The message in the shape Nodemailer's `sendMail()` takes. */
|
|
39
|
+
function toNodemailerMessage(message) {
|
|
40
|
+
const out = {
|
|
41
|
+
from: message.from,
|
|
42
|
+
to: message.to,
|
|
43
|
+
subject: message.subject,
|
|
44
|
+
};
|
|
45
|
+
if (message.cc.length)
|
|
46
|
+
out.cc = message.cc;
|
|
47
|
+
if (message.bcc.length)
|
|
48
|
+
out.bcc = message.bcc;
|
|
49
|
+
if (message.replyTo.length)
|
|
50
|
+
out.replyTo = message.replyTo;
|
|
51
|
+
if (message.text !== undefined)
|
|
52
|
+
out.text = message.text;
|
|
53
|
+
if (message.html !== undefined)
|
|
54
|
+
out.html = message.html;
|
|
55
|
+
if (message.attachments.length)
|
|
56
|
+
out.attachments = message.attachments;
|
|
57
|
+
if (Object.keys(message.headers).length)
|
|
58
|
+
out.headers = message.headers;
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
/** Sends through an SMTP server with Nodemailer, connecting on the first send. */
|
|
62
|
+
class SmtpTransport {
|
|
63
|
+
config;
|
|
64
|
+
transporter;
|
|
65
|
+
constructor(config) {
|
|
66
|
+
this.config = config;
|
|
67
|
+
}
|
|
68
|
+
async send(message) {
|
|
69
|
+
this.transporter ??= requireNodemailer().createTransport(smtpTransportOptions(this.config));
|
|
70
|
+
const info = await this.transporter.sendMail(toNodemailerMessage(message));
|
|
71
|
+
return { messageId: info?.messageId, response: info };
|
|
72
|
+
}
|
|
73
|
+
close() {
|
|
74
|
+
this.transporter?.close?.();
|
|
75
|
+
this.transporter = undefined;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
exports.SmtpTransport = SmtpTransport;
|
|
79
|
+
/** Writes each message to the Megh logger (module `mail`) instead of sending it. */
|
|
80
|
+
class LogTransport {
|
|
81
|
+
logger = (0, internal_logger_1.internalLogger)("mail");
|
|
82
|
+
async send(message) {
|
|
83
|
+
const list = (addresses) => addresses.map(formatAddress);
|
|
84
|
+
this.logger.info({
|
|
85
|
+
from: formatAddress(message.from),
|
|
86
|
+
to: list(message.to),
|
|
87
|
+
...(message.cc.length ? { cc: list(message.cc) } : {}),
|
|
88
|
+
...(message.bcc.length ? { bcc: list(message.bcc) } : {}),
|
|
89
|
+
subject: message.subject,
|
|
90
|
+
...(message.attachments.length
|
|
91
|
+
? {
|
|
92
|
+
attachments: message.attachments.map((a) => a.filename ?? a.path ?? "attachment"),
|
|
93
|
+
}
|
|
94
|
+
: {}),
|
|
95
|
+
text: message.text,
|
|
96
|
+
html: message.html,
|
|
97
|
+
}, "Mail not sent (log mailer)");
|
|
98
|
+
return {};
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
exports.LogTransport = LogTransport;
|
|
102
|
+
/**
|
|
103
|
+
* Sends through the first mailer in the list that succeeds, logging each
|
|
104
|
+
* failure. Fails only when every mailer has.
|
|
105
|
+
*/
|
|
106
|
+
class FailoverTransport {
|
|
107
|
+
mailers;
|
|
108
|
+
deliver;
|
|
109
|
+
logger = (0, internal_logger_1.internalLogger)("mail");
|
|
110
|
+
constructor(mailers, deliver) {
|
|
111
|
+
this.mailers = mailers;
|
|
112
|
+
this.deliver = deliver;
|
|
113
|
+
}
|
|
114
|
+
async send(message) {
|
|
115
|
+
const failures = [];
|
|
116
|
+
for (const [i, mailer] of this.mailers.entries()) {
|
|
117
|
+
try {
|
|
118
|
+
const result = await this.deliver(mailer, message);
|
|
119
|
+
if (i > 0)
|
|
120
|
+
this.logger.info({ mailer }, `Mail sent through "${mailer}" after failover`);
|
|
121
|
+
return { ...(result ?? {}) };
|
|
122
|
+
}
|
|
123
|
+
catch (err) {
|
|
124
|
+
const why = err instanceof Error ? err.message : String(err);
|
|
125
|
+
failures.push(`${mailer}: ${why}`);
|
|
126
|
+
const next = this.mailers[i + 1];
|
|
127
|
+
this.logger.warn({ err, mailer, next }, next
|
|
128
|
+
? `Mailer "${mailer}" failed; trying "${next}"`
|
|
129
|
+
: `Mailer "${mailer}" failed; no mailers left to try`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
throw new errors_1.MailError(`Every failover mailer failed. ${failures.join(" | ")}`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
exports.FailoverTransport = FailoverTransport;
|
|
136
|
+
/** Keeps every message in `messages`, for tests. */
|
|
137
|
+
class ArrayTransport {
|
|
138
|
+
messages = [];
|
|
139
|
+
async send(message) {
|
|
140
|
+
this.messages.push(message);
|
|
141
|
+
return {};
|
|
142
|
+
}
|
|
143
|
+
/** Forget the messages kept so far. */
|
|
144
|
+
flush() {
|
|
145
|
+
this.messages.length = 0;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
exports.ArrayTransport = ArrayTransport;
|
|
149
|
+
function formatAddress(a) {
|
|
150
|
+
return a.name ? `${a.name} <${a.address}>` : a.address;
|
|
151
|
+
}
|
|
152
|
+
//# sourceMappingURL=transports.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transports.js","sourceRoot":"","sources":["../../src/mail/transports.ts"],"names":[],"mappings":";;;AAgBA,oDAsBC;AAGD,kDAgBC;AAzDD,sEAAkE;AAElE,qCAAqC;AAGrC,SAAS,iBAAiB;IACxB,IAAI,CAAC;QACH,OAAO,OAAO,CAAC,YAAY,CAAC,CAAC;IAC/B,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,kBAAS,CACjB,wFAAwF,CACzF,CAAC;IACJ,CAAC;AACH,CAAC;AAED,uDAAuD;AACvD,SAAgB,oBAAoB,CAClC,MAAwB;IAExB,IAAI,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpC,MAAM,IAAI,kBAAS,CACjB,sGAAsG,CACvG,CAAC;IACJ,CAAC;IACD,MAAM,MAAM,GAAG,MAAM,CAAC,UAAU;QAC9B,CAAC,CAAC,MAAM,CAAC,UAAU,KAAK,KAAK;QAC7B,CAAC,CAAC,MAAM,CAAC,IAAI,KAAK,GAAG,CAAC;IACxB,MAAM,OAAO,GAA4B;QACvC,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,IAAI,EAAE,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O,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;AACzD,CAAC"}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An email address: `"ann@x.io"`, `"Ann <ann@x.io>"` or
|
|
3
|
+
* `{ name: "Ann", address: "ann@x.io" }`.
|
|
4
|
+
*/
|
|
5
|
+
export type MailAddressLike = string | MailAddress;
|
|
6
|
+
/** An email address with an optional display name. */
|
|
7
|
+
export interface MailAddress {
|
|
8
|
+
name?: string;
|
|
9
|
+
address: string;
|
|
10
|
+
}
|
|
11
|
+
/** A file attached to a message. Give `content` or `path`. */
|
|
12
|
+
export interface MailAttachment {
|
|
13
|
+
/** The file name the recipient sees. */
|
|
14
|
+
filename?: string;
|
|
15
|
+
/** The file's contents. */
|
|
16
|
+
content?: string | Buffer;
|
|
17
|
+
/** A file path or URL to read the contents from. */
|
|
18
|
+
path?: string;
|
|
19
|
+
/** MIME type; worked out from `filename` when left out. */
|
|
20
|
+
contentType?: string;
|
|
21
|
+
/** Content ID, for images referenced as `<img src="cid:...">` in the HTML. */
|
|
22
|
+
cid?: string;
|
|
23
|
+
/** Set to `base64` when `content` is base64 text rather than the file itself. */
|
|
24
|
+
encoding?: "base64";
|
|
25
|
+
}
|
|
26
|
+
/** Who a message is from and to, and its subject. Returned by `Mailable.envelope()`. */
|
|
27
|
+
export interface MailEnvelope {
|
|
28
|
+
/** Defaults to the class name as words: `WelcomeMail` → "Welcome Mail". */
|
|
29
|
+
subject?: string;
|
|
30
|
+
/** Overrides the configured `from` address. */
|
|
31
|
+
from?: MailAddressLike;
|
|
32
|
+
replyTo?: MailAddressLike | MailAddressLike[];
|
|
33
|
+
/** Added to the recipients given with `mailer.to()`. */
|
|
34
|
+
to?: MailAddressLike | MailAddressLike[];
|
|
35
|
+
cc?: MailAddressLike | MailAddressLike[];
|
|
36
|
+
bcc?: MailAddressLike | MailAddressLike[];
|
|
37
|
+
/** Extra message headers. */
|
|
38
|
+
headers?: Record<string, string>;
|
|
39
|
+
}
|
|
40
|
+
/** The message body. Returned by `Mailable.content()`; give `html`, `text` or both. */
|
|
41
|
+
export interface MailContent {
|
|
42
|
+
html?: string;
|
|
43
|
+
text?: string;
|
|
44
|
+
}
|
|
45
|
+
/** A fully built message, as a transport receives it. */
|
|
46
|
+
export interface MailMessage {
|
|
47
|
+
from: MailAddress;
|
|
48
|
+
to: MailAddress[];
|
|
49
|
+
cc: MailAddress[];
|
|
50
|
+
bcc: MailAddress[];
|
|
51
|
+
replyTo: MailAddress[];
|
|
52
|
+
subject: string;
|
|
53
|
+
html?: string;
|
|
54
|
+
text?: string;
|
|
55
|
+
attachments: MailAttachment[];
|
|
56
|
+
headers: Record<string, string>;
|
|
57
|
+
}
|
|
58
|
+
/** What a transport reports back after sending. */
|
|
59
|
+
export interface MailTransportResult {
|
|
60
|
+
/** The provider's ID for the message, when it gives one. */
|
|
61
|
+
messageId?: string;
|
|
62
|
+
/** The provider's raw response. */
|
|
63
|
+
response?: unknown;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Delivers built messages: SMTP, a provider's HTTP API, a log, memory.
|
|
67
|
+
* Implement it to add a provider, and register it in `useMail({ mailers })`.
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* class MyTransport implements MailTransport {
|
|
71
|
+
* async send(message: MailMessage) {
|
|
72
|
+
* const res = await fetch('https://api.example.com/send', { method: 'POST', body: JSON.stringify(message) });
|
|
73
|
+
* return { messageId: (await res.json()).id };
|
|
74
|
+
* }
|
|
75
|
+
* }
|
|
76
|
+
*/
|
|
77
|
+
export interface MailTransport {
|
|
78
|
+
send(message: MailMessage): Promise<MailTransportResult | void>;
|
|
79
|
+
/** Release connections; called by `Mailer.close()` and when the app closes. */
|
|
80
|
+
close?(): void | Promise<void>;
|
|
81
|
+
}
|
|
82
|
+
/** The result of `queue()` and `later()`. */
|
|
83
|
+
export interface QueuedMessage {
|
|
84
|
+
mailer: string;
|
|
85
|
+
message: MailMessage;
|
|
86
|
+
/** The queue job's ID. Not set under `Mailer.fake()`. */
|
|
87
|
+
jobId?: string;
|
|
88
|
+
/** Milliseconds until it is sent; 0 for `queue()`. */
|
|
89
|
+
delay: number;
|
|
90
|
+
}
|
|
91
|
+
/** The result of `send()`: the mailer used, the message and the provider's reply. */
|
|
92
|
+
export interface SentMessage extends MailTransportResult {
|
|
93
|
+
mailer: string;
|
|
94
|
+
message: MailMessage;
|
|
95
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/mail/types.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright 2024
|
|
3
|
+
* @author Tareq Hossain
|
|
4
|
+
* @email xtrinsic96@gmail.com
|
|
5
|
+
* @url https://github.com/xtareq
|
|
6
|
+
*/
|
|
7
|
+
import type { FastifyInstance } from "fastify";
|
|
8
|
+
/** A CSP directive value: one source, a list, `true` for a bare directive, `false` to drop it. */
|
|
9
|
+
export type CspDirectiveValue = string | string[] | boolean;
|
|
10
|
+
export interface ContentSecurityPolicyOptions {
|
|
11
|
+
/**
|
|
12
|
+
* Directives merged over the defaults. Keys are camelCase or kebab-case
|
|
13
|
+
* (`scriptSrc` or `script-src`). `false` removes a default directive.
|
|
14
|
+
*/
|
|
15
|
+
directives?: Record<string, CspDirectiveValue>;
|
|
16
|
+
/** Start from an empty policy instead of the defaults. Defaults to `true`. */
|
|
17
|
+
useDefaults?: boolean;
|
|
18
|
+
/** Send `Content-Security-Policy-Report-Only` instead, to try a policy out. */
|
|
19
|
+
reportOnly?: boolean;
|
|
20
|
+
}
|
|
21
|
+
export interface StrictTransportSecurityOptions {
|
|
22
|
+
/** Seconds browsers keep to HTTPS. Defaults to 31536000 (one year). */
|
|
23
|
+
maxAge?: number;
|
|
24
|
+
/** Apply to subdomains too. Defaults to `true`. */
|
|
25
|
+
includeSubDomains?: boolean;
|
|
26
|
+
/** Ask to be put on the browsers' preload list. Defaults to `false`. */
|
|
27
|
+
preload?: boolean;
|
|
28
|
+
}
|
|
29
|
+
export type ReferrerPolicy = "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
|
|
30
|
+
/**
|
|
31
|
+
* Options for `app.useSecurityHeaders()`. Every header is on by default
|
|
32
|
+
* except `Cross-Origin-Embedder-Policy`; pass `false` to leave one out.
|
|
33
|
+
*/
|
|
34
|
+
export interface SecurityHeadersOptions {
|
|
35
|
+
/** `Content-Security-Policy`. Defaults to a strict same-origin policy. */
|
|
36
|
+
contentSecurityPolicy?: boolean | ContentSecurityPolicyOptions;
|
|
37
|
+
/** `Strict-Transport-Security`. Browsers ignore it over plain HTTP. */
|
|
38
|
+
strictTransportSecurity?: boolean | StrictTransportSecurityOptions;
|
|
39
|
+
/** `X-Frame-Options`. Defaults to `SAMEORIGIN`. */
|
|
40
|
+
frameOptions?: false | "DENY" | "SAMEORIGIN";
|
|
41
|
+
/** `Referrer-Policy`. Defaults to `no-referrer`. */
|
|
42
|
+
referrerPolicy?: false | ReferrerPolicy | ReferrerPolicy[];
|
|
43
|
+
/** `Cross-Origin-Opener-Policy`. Defaults to `same-origin`. */
|
|
44
|
+
crossOriginOpenerPolicy?: false | "same-origin" | "same-origin-allow-popups" | "unsafe-none";
|
|
45
|
+
/** `Cross-Origin-Resource-Policy`. Defaults to `same-origin`. */
|
|
46
|
+
crossOriginResourcePolicy?: false | "same-origin" | "same-site" | "cross-origin";
|
|
47
|
+
/** `Cross-Origin-Embedder-Policy`. Off by default: it blocks cross-origin images and scripts. */
|
|
48
|
+
crossOriginEmbedderPolicy?: false | "require-corp" | "credentialless" | "unsafe-none";
|
|
49
|
+
/**
|
|
50
|
+
* Any other header to set, or a default to remove with `false`, e.g.
|
|
51
|
+
* `{ 'Permissions-Policy': 'camera=()', 'X-DNS-Prefetch-Control': false }`.
|
|
52
|
+
*/
|
|
53
|
+
headers?: Record<string, string | false>;
|
|
54
|
+
}
|
|
55
|
+
/** Turn the options into the final header list, once at startup. */
|
|
56
|
+
export declare function buildSecurityHeaders(options?: SecurityHeadersOptions): [string, string][];
|
|
57
|
+
/**
|
|
58
|
+
* Set the security headers on every response, including errors and 404s.
|
|
59
|
+
* A header the route sets itself wins.
|
|
60
|
+
*
|
|
61
|
+
* `cspExemptPrefix` returns a path (the API docs page) whose responses get
|
|
62
|
+
* no CSP from here: Swagger UI sends its own, and Scalar needs inline script.
|
|
63
|
+
* It is read on each request, since `useOpenApi()` may be called later.
|
|
64
|
+
*/
|
|
65
|
+
export declare function installSecurityHeaders(app: FastifyInstance, options?: SecurityHeadersOptions, cspExemptPrefix?: () => string | undefined): void;
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildSecurityHeaders = buildSecurityHeaders;
|
|
4
|
+
exports.installSecurityHeaders = installSecurityHeaders;
|
|
5
|
+
const DEFAULT_CSP_DIRECTIVES = {
|
|
6
|
+
"default-src": "'self'",
|
|
7
|
+
"base-uri": "'self'",
|
|
8
|
+
"font-src": ["'self'", "https:", "data:"],
|
|
9
|
+
"form-action": "'self'",
|
|
10
|
+
"frame-ancestors": "'self'",
|
|
11
|
+
"img-src": ["'self'", "data:"],
|
|
12
|
+
"object-src": "'none'",
|
|
13
|
+
"script-src": "'self'",
|
|
14
|
+
"script-src-attr": "'none'",
|
|
15
|
+
"style-src": ["'self'", "https:", "'unsafe-inline'"],
|
|
16
|
+
"upgrade-insecure-requests": true,
|
|
17
|
+
};
|
|
18
|
+
/** Headers with no option of their own; turn one off through `headers`. */
|
|
19
|
+
const FIXED_HEADERS = {
|
|
20
|
+
"Origin-Agent-Cluster": "?1",
|
|
21
|
+
"X-Content-Type-Options": "nosniff",
|
|
22
|
+
"X-DNS-Prefetch-Control": "off",
|
|
23
|
+
"X-Download-Options": "noopen",
|
|
24
|
+
"X-Permitted-Cross-Domain-Policies": "none",
|
|
25
|
+
// The legacy XSS auditor caused more holes than it closed; turn it off.
|
|
26
|
+
"X-XSS-Protection": "0",
|
|
27
|
+
};
|
|
28
|
+
/** Turn the options into the final header list, once at startup. */
|
|
29
|
+
function buildSecurityHeaders(options = {}) {
|
|
30
|
+
const headers = new Map();
|
|
31
|
+
const set = (name, value) => headers.set(name.toLowerCase(), [name, value]);
|
|
32
|
+
const csp = options.contentSecurityPolicy ?? true;
|
|
33
|
+
if (csp !== false) {
|
|
34
|
+
const cspOptions = csp === true ? {} : csp;
|
|
35
|
+
set(cspOptions.reportOnly
|
|
36
|
+
? "Content-Security-Policy-Report-Only"
|
|
37
|
+
: "Content-Security-Policy", buildCsp(cspOptions));
|
|
38
|
+
}
|
|
39
|
+
const hsts = options.strictTransportSecurity ?? true;
|
|
40
|
+
if (hsts !== false) {
|
|
41
|
+
const { maxAge = 31_536_000, includeSubDomains = true, preload = false, } = hsts === true ? {} : hsts;
|
|
42
|
+
if (!Number.isInteger(maxAge) || maxAge < 0) {
|
|
43
|
+
throw new TypeError(`[Megh] strictTransportSecurity.maxAge must be a whole number of seconds, got ${maxAge}.`);
|
|
44
|
+
}
|
|
45
|
+
set("Strict-Transport-Security", [
|
|
46
|
+
`max-age=${maxAge}`,
|
|
47
|
+
includeSubDomains && "includeSubDomains",
|
|
48
|
+
preload && "preload",
|
|
49
|
+
]
|
|
50
|
+
.filter(Boolean)
|
|
51
|
+
.join("; "));
|
|
52
|
+
}
|
|
53
|
+
const frame = options.frameOptions ?? "SAMEORIGIN";
|
|
54
|
+
if (frame)
|
|
55
|
+
set("X-Frame-Options", frame);
|
|
56
|
+
const referrer = options.referrerPolicy ?? "no-referrer";
|
|
57
|
+
if (referrer) {
|
|
58
|
+
set("Referrer-Policy", Array.isArray(referrer) ? referrer.join(",") : referrer);
|
|
59
|
+
}
|
|
60
|
+
const coop = options.crossOriginOpenerPolicy ?? "same-origin";
|
|
61
|
+
if (coop)
|
|
62
|
+
set("Cross-Origin-Opener-Policy", coop);
|
|
63
|
+
const corp = options.crossOriginResourcePolicy ?? "same-origin";
|
|
64
|
+
if (corp)
|
|
65
|
+
set("Cross-Origin-Resource-Policy", corp);
|
|
66
|
+
const coep = options.crossOriginEmbedderPolicy ?? false;
|
|
67
|
+
if (coep)
|
|
68
|
+
set("Cross-Origin-Embedder-Policy", coep);
|
|
69
|
+
for (const [name, value] of Object.entries(FIXED_HEADERS))
|
|
70
|
+
set(name, value);
|
|
71
|
+
for (const [name, value] of Object.entries(options.headers ?? {})) {
|
|
72
|
+
if (value === false)
|
|
73
|
+
headers.delete(name.toLowerCase());
|
|
74
|
+
else
|
|
75
|
+
set(name, assertHeaderValue(name, value));
|
|
76
|
+
}
|
|
77
|
+
return [...headers.values()];
|
|
78
|
+
}
|
|
79
|
+
function buildCsp(options) {
|
|
80
|
+
const directives = new Map(options.useDefaults === false ? [] : Object.entries(DEFAULT_CSP_DIRECTIVES));
|
|
81
|
+
for (const [key, value] of Object.entries(options.directives ?? {})) {
|
|
82
|
+
directives.set(kebabCase(key), value);
|
|
83
|
+
}
|
|
84
|
+
const parts = [];
|
|
85
|
+
for (const [name, value] of directives) {
|
|
86
|
+
if (value === false)
|
|
87
|
+
continue;
|
|
88
|
+
if (!/^[a-z-]+$/.test(name)) {
|
|
89
|
+
throw new TypeError(`[Megh] Invalid CSP directive name "${name}".`);
|
|
90
|
+
}
|
|
91
|
+
if (value === true) {
|
|
92
|
+
parts.push(name);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const sources = Array.isArray(value) ? value : [value];
|
|
96
|
+
for (const source of sources) {
|
|
97
|
+
if (/[;,\r\n]/.test(source)) {
|
|
98
|
+
throw new TypeError(`[Megh] CSP directive "${name}" has an invalid source "${source}".`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
parts.push(sources.length ? `${name} ${sources.join(" ")}` : name);
|
|
102
|
+
}
|
|
103
|
+
if (parts.length === 0) {
|
|
104
|
+
throw new TypeError("[Megh] contentSecurityPolicy has no directives. Pass contentSecurityPolicy: false to send none.");
|
|
105
|
+
}
|
|
106
|
+
return parts.join("; ");
|
|
107
|
+
}
|
|
108
|
+
function kebabCase(key) {
|
|
109
|
+
return key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
|
|
110
|
+
}
|
|
111
|
+
function assertHeaderValue(name, value) {
|
|
112
|
+
if (typeof value !== "string" || /[\r\n]/.test(value)) {
|
|
113
|
+
throw new TypeError(`[Megh] Invalid value for security header "${name}".`);
|
|
114
|
+
}
|
|
115
|
+
return value;
|
|
116
|
+
}
|
|
117
|
+
const CSP_HEADERS = new Set([
|
|
118
|
+
"content-security-policy",
|
|
119
|
+
"content-security-policy-report-only",
|
|
120
|
+
]);
|
|
121
|
+
/**
|
|
122
|
+
* Set the security headers on every response, including errors and 404s.
|
|
123
|
+
* A header the route sets itself wins.
|
|
124
|
+
*
|
|
125
|
+
* `cspExemptPrefix` returns a path (the API docs page) whose responses get
|
|
126
|
+
* no CSP from here: Swagger UI sends its own, and Scalar needs inline script.
|
|
127
|
+
* It is read on each request, since `useOpenApi()` may be called later.
|
|
128
|
+
*/
|
|
129
|
+
function installSecurityHeaders(app, options, cspExemptPrefix = () => undefined) {
|
|
130
|
+
const headers = buildSecurityHeaders(options);
|
|
131
|
+
const withoutCsp = headers.filter(([name]) => !CSP_HEADERS.has(name.toLowerCase()));
|
|
132
|
+
app.addHook("onRequest", (request, reply, done) => {
|
|
133
|
+
const prefix = cspExemptPrefix();
|
|
134
|
+
const list = prefix && isUnder(request.url, prefix) ? withoutCsp : headers;
|
|
135
|
+
for (const [name, value] of list)
|
|
136
|
+
reply.header(name, value);
|
|
137
|
+
done();
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
function isUnder(url, prefix) {
|
|
141
|
+
const base = prefix.replace(/\/+$/, "");
|
|
142
|
+
// A docs page at "/" must not take the CSP off the whole app.
|
|
143
|
+
if (base === "" || !url.startsWith(base))
|
|
144
|
+
return false;
|
|
145
|
+
const next = url.charAt(base.length);
|
|
146
|
+
return next === "" || next === "/" || next === "?";
|
|
147
|
+
}
|
|
148
|
+
//# sourceMappingURL=headers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"headers.js","sourceRoot":"","sources":["../../src/security/headers.ts"],"names":[],"mappings":";;AAiGA,oDAsEC;AA8DD,wDAeC;AA7KD,MAAM,sBAAsB,GAAsC;IAChE,aAAa,EAAE,QAAQ;IACvB,UAAU,EAAE,QAAQ;IACpB,UAAU,EAAE,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,CAAC;IACzC,aAAa,EAAE,QAAQ;IACvB,iBAAiB,EAAE,QAAQ;IAC3B,SAAS,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC9B,YAAY,EAAE,QAAQ;IACtB,YAAY,EAAE,QAAQ;IACtB,iBAAiB,EAAE,QAAQ;IAC3B,WAAW,EAAE,CAAC,QAAQ,EAAE,QAAQ,EAAE,iBAAiB,CAAC;IACpD,2BAA2B,EAAE,IAAI;CAClC,CAAC;AAEF,2EAA2E;AAC3E,MAAM,aAAa,GAA2B;IAC5C,sBAAsB,EAAE,IAAI;IAC5B,wBAAwB,EAAE,SAAS;IACnC,wBAAwB,EAAE,KAAK;IAC/B,oBAAoB,EAAE,QAAQ;IAC9B,mCAAmC,EAAE,MAAM;IAC3C,wEAAwE;IACxE,kBAAkB,EAAE,GAAG;CACxB,CAAC;AAEF,oEAAoE;AACpE,SAAgB,oBAAoB,CAClC,UAAkC,EAAE;IAEpC,MAAM,OAAO,GAAG,IAAI,GAAG,EAA4B,CAAC;IACpD,MAAM,GAAG,GAAG,CAAC,IAAY,EAAE,KAAa,EAAE,EAAE,CAC1C,OAAO,CAAC,GAAG,CAAC,IAA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CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC;QAC3E,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,IAAI;YAAE,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC5D,IAAI,EAAE,CAAC;IACT,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,OAAO,CAAC,GAAW,EAAE,MAAc;IAC1C,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IACxC,8DAA8D;IAC9D,IAAI,IAAI,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IACvD,MAAM,IAAI,GAAG,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACrC,OAAO,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,GAAG,CAAC;AACrD,CAAC"}
|
package/dist/security/index.d.ts
CHANGED
|
@@ -1 +1,4 @@
|
|
|
1
1
|
export * from "./authentication";
|
|
2
|
+
export type { SecurityHeadersOptions, ContentSecurityPolicyOptions, CspDirectiveValue, StrictTransportSecurityOptions, ReferrerPolicy, } from "./headers";
|
|
3
|
+
export { RateLimit, MemoryRateLimitStore, RedisRateLimitStore, } from "./rate-limit";
|
|
4
|
+
export type { RateLimitOptions, RouteRateLimitOptions, RateLimitStore, RateLimitHit, RateLimitWindow, RedisEvalClient, } from "./rate-limit";
|
package/dist/security/index.js
CHANGED
|
@@ -14,5 +14,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.RedisRateLimitStore = exports.MemoryRateLimitStore = exports.RateLimit = void 0;
|
|
17
18
|
__exportStar(require("./authentication"), exports);
|
|
19
|
+
var rate_limit_1 = require("./rate-limit");
|
|
20
|
+
Object.defineProperty(exports, "RateLimit", { enumerable: true, get: function () { return rate_limit_1.RateLimit; } });
|
|
21
|
+
Object.defineProperty(exports, "MemoryRateLimitStore", { enumerable: true, get: function () { return rate_limit_1.MemoryRateLimitStore; } });
|
|
22
|
+
Object.defineProperty(exports, "RedisRateLimitStore", { enumerable: true, get: function () { return rate_limit_1.RedisRateLimitStore; } });
|
|
18
23
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/security/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/security/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,mDAAiC;AAQjC,2CAIsB;AAHpB,uGAAA,SAAS,OAAA;AACT,kHAAA,oBAAoB,OAAA;AACpB,iHAAA,mBAAmB,OAAA"}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright 2024
|
|
3
|
+
* @author Tareq Hossain
|
|
4
|
+
* @email xtrinsic96@gmail.com
|
|
5
|
+
* @url https://github.com/xtareq
|
|
6
|
+
*/
|
|
7
|
+
import type { FastifyInstance } from "fastify";
|
|
8
|
+
import type { IRequest } from "../core/types";
|
|
9
|
+
/** The count for one key in the current window. */
|
|
10
|
+
export interface RateLimitHit {
|
|
11
|
+
/** Hits in the current window, including this one. */
|
|
12
|
+
count: number;
|
|
13
|
+
/** Epoch milliseconds when the window ends and the count starts over. */
|
|
14
|
+
resetAt: number;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Where hit counts live. The memory store is per process; use
|
|
18
|
+
* `RedisRateLimitStore`, or your own, to share counts between replicas.
|
|
19
|
+
*/
|
|
20
|
+
export interface RateLimitStore {
|
|
21
|
+
/** Count one hit for `key` in a window of `windowMs` milliseconds. */
|
|
22
|
+
hit(key: string, windowMs: number): RateLimitHit | Promise<RateLimitHit>;
|
|
23
|
+
/** Forget the count for `key`. */
|
|
24
|
+
reset?(key: string): void | Promise<void>;
|
|
25
|
+
/** Release timers or connections. Megh calls it on shutdown for stores it created. */
|
|
26
|
+
close?(): void | Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
/** A window: milliseconds, or a duration such as `'30s'`, `'15m'`, `'1 hour'`. */
|
|
29
|
+
export type RateLimitWindow = number | string;
|
|
30
|
+
/** The limit for one route, set with `@RateLimit()` or `.rateLimit()`. */
|
|
31
|
+
export interface RouteRateLimitOptions {
|
|
32
|
+
/** Requests allowed per window, per client. */
|
|
33
|
+
max?: number;
|
|
34
|
+
/** Window length. Defaults to the app's window, else one minute. */
|
|
35
|
+
window?: RateLimitWindow;
|
|
36
|
+
/** How to tell clients apart. Defaults to the app's key, else `request.ip`. */
|
|
37
|
+
key?: (request: IRequest) => string | Promise<string>;
|
|
38
|
+
}
|
|
39
|
+
/** Options for `app.useRateLimit()`. */
|
|
40
|
+
export interface RateLimitOptions extends RouteRateLimitOptions {
|
|
41
|
+
/** Requests allowed per window, per client. Defaults to 100. */
|
|
42
|
+
max?: number;
|
|
43
|
+
/** Window length. Defaults to one minute. */
|
|
44
|
+
window?: RateLimitWindow;
|
|
45
|
+
/**
|
|
46
|
+
* How to tell clients apart. Defaults to `request.ip`; behind a proxy, set
|
|
47
|
+
* `server.trustProxy` so that is the client's address.
|
|
48
|
+
*/
|
|
49
|
+
key?: (request: IRequest) => string | Promise<string>;
|
|
50
|
+
/** Return `true` to let a request through uncounted, e.g. an internal IP. */
|
|
51
|
+
skip?: (request: IRequest) => boolean | Promise<boolean>;
|
|
52
|
+
/** Where counts live. Defaults to memory. */
|
|
53
|
+
store?: RateLimitStore;
|
|
54
|
+
/** Shortcut for `store: new RedisRateLimitStore(redis)`, with an ioredis client. */
|
|
55
|
+
redis?: RedisEvalClient;
|
|
56
|
+
/** Send `RateLimit-*` headers on every limited response. Defaults to `true`. */
|
|
57
|
+
headers?: boolean;
|
|
58
|
+
/** The 429 message. Defaults to "Too many requests, please try again later." */
|
|
59
|
+
message?: string;
|
|
60
|
+
/**
|
|
61
|
+
* Let requests through when the store fails (Redis is down) instead of
|
|
62
|
+
* answering 500. The error is still logged. Defaults to `false`.
|
|
63
|
+
*/
|
|
64
|
+
failOpen?: boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Limit every route. `false` limits only routes with `@RateLimit()` or
|
|
67
|
+
* `.rateLimit()`. Defaults to `true`.
|
|
68
|
+
*/
|
|
69
|
+
global?: boolean;
|
|
70
|
+
}
|
|
71
|
+
/** Route config key holding a route's own limit, or `false` to skip limiting. */
|
|
72
|
+
export declare const RATE_LIMIT_CONFIG_KEY = "meghRateLimit";
|
|
73
|
+
/** Metadata key for `@RateLimit()`. */
|
|
74
|
+
export declare const RATE_LIMIT_META_KEY = "megh:rate-limit";
|
|
75
|
+
/** Milliseconds in a window given as a number or a duration string. */
|
|
76
|
+
export declare function parseWindow(window: RateLimitWindow): number;
|
|
77
|
+
/**
|
|
78
|
+
* Fixed-window counts in memory. Counts are per process and lost on
|
|
79
|
+
* restart. Expired windows are swept every minute by an `unref`'d timer.
|
|
80
|
+
*/
|
|
81
|
+
export declare class MemoryRateLimitStore implements RateLimitStore {
|
|
82
|
+
private readonly sweepIntervalMs;
|
|
83
|
+
private readonly windows;
|
|
84
|
+
private timer;
|
|
85
|
+
constructor(sweepIntervalMs?: number);
|
|
86
|
+
hit(key: string, windowMs: number): RateLimitHit;
|
|
87
|
+
reset(key: string): void;
|
|
88
|
+
close(): void;
|
|
89
|
+
private startSweep;
|
|
90
|
+
}
|
|
91
|
+
/** The part of an ioredis client the Redis store uses. */
|
|
92
|
+
export interface RedisEvalClient {
|
|
93
|
+
eval(script: string, numKeys: number, ...args: (string | number)[]): Promise<unknown>;
|
|
94
|
+
del(...keys: string[]): Promise<unknown>;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Fixed-window counts in Redis, shared by every replica. Pass an ioredis
|
|
98
|
+
* client; Megh does not close it.
|
|
99
|
+
*/
|
|
100
|
+
export declare class RedisRateLimitStore implements RateLimitStore {
|
|
101
|
+
private readonly redis;
|
|
102
|
+
private readonly prefix;
|
|
103
|
+
constructor(redis: RedisEvalClient, options?: {
|
|
104
|
+
prefix?: string;
|
|
105
|
+
});
|
|
106
|
+
hit(key: string, windowMs: number): Promise<RateLimitHit>;
|
|
107
|
+
reset(key: string): Promise<void>;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Give a controller or route its own limit, in place of the app's, or pass
|
|
111
|
+
* `false` to leave it unlimited. Works without `app.useRateLimit()` too.
|
|
112
|
+
*
|
|
113
|
+
* @Post('/login')
|
|
114
|
+
* @RateLimit({ max: 5, window: '15m' })
|
|
115
|
+
* login() {}
|
|
116
|
+
*/
|
|
117
|
+
export declare function RateLimit(options: RouteRateLimitOptions | false): ClassDecorator & MethodDecorator;
|
|
118
|
+
/** Throw on a bad route limit when it is declared, not on its first request. */
|
|
119
|
+
export declare function assertRouteRateLimit(options: RouteRateLimitOptions | false): void;
|
|
120
|
+
/** The `@RateLimit()` for a route: the method's, else the controller's. */
|
|
121
|
+
export declare function getDeclaredRateLimit(controller: Function, method: string): RouteRateLimitOptions | false | undefined;
|
|
122
|
+
/**
|
|
123
|
+
* Count requests per client and answer 429 over the limit. Returns the
|
|
124
|
+
* store, so the app can close it on shutdown when it created it.
|
|
125
|
+
*/
|
|
126
|
+
export declare function installRateLimit(app: FastifyInstance, options?: RateLimitOptions): {
|
|
127
|
+
store: RateLimitStore;
|
|
128
|
+
ownsStore: boolean;
|
|
129
|
+
};
|