@axiumine/koa-utils 7.1.1 → 7.2.0

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 CHANGED
@@ -297,7 +297,7 @@ For the cluster path the `rediss://` scheme on `rootNodes` is not enough on its
297
297
  ```bash
298
298
  yarn install
299
299
  yarn build # ESM only — production output
300
- yarn build:all # ESM + CJS dual output
300
+ yarn build:all # not usable today: the CJS half emits nothing, the package is ESM-only (use yarn build)
301
301
  yarn test # build + build:tests + mocha, no coverage gate
302
302
  yarn test:coverage # same under c8: fails below 100% on lines, statements, functions or branches of any file
303
303
  yarn lint # eslint --fix + prettier --write
@@ -29,10 +29,14 @@ export declare class SocketLabsLib {
29
29
  * normalised away — the caller supplies configuration, not a pre-joined URL, and `//check` or
30
30
  * `example.comcheck` are not errors worth surfacing to a user mid-registration.
31
31
  *
32
+ * The base, whether passed or taken from `APP_DOMAIN`, must parse as an absolute `http:` / `https:` URL
33
+ * with no user name, password, control character or whitespace; any other value (`javascript:`, `data:`,
34
+ * `//host`, a host with no scheme) makes the call reject with `throwInternalError()` and sends nothing.
35
+ *
32
36
  * @param emailTo recipient, also embedded in the link (URI-encoded)
33
37
  * @param hash the activation hash stored on the account
34
38
  * @param name optional greeting name
35
- * @param linkBase scheme + host the link points at; defaults to `APP_DOMAIN`
39
+ * @param linkBase scheme + host the link points at; defaults to `APP_DOMAIN`. An absolute `http:` / `https:` URL, else the call rejects with a 500
36
40
  * @param linkPath route prefix the receiving service listens on; defaults to `/check/verify-email`
37
41
  */
38
42
  sendEmailVerify(emailTo: string, hash: string, name?: string, linkBase?: string, linkPath?: string): Promise<boolean>;
@@ -115,7 +119,7 @@ SendResponse {
115
119
  * @param emailTo recipient, also embedded in the link (URI-encoded)
116
120
  * @param hash the reset hash stored on the account
117
121
  * @param name optional greeting name
118
- * @param linkBase scheme + host the link points at; defaults to `APP_DOMAIN`
122
+ * @param linkBase scheme + host the link points at; defaults to `APP_DOMAIN`. An absolute `http:` / `https:` URL, else the call rejects with a 500
119
123
  * @param linkPath front-end route prefix that renders the new-password form; defaults to `/x/reset`
120
124
  */
121
125
  sendEmailReset(emailTo: string, hash: string, name?: string, linkBase?: string, linkPath?: string): Promise<boolean>;
@@ -1,7 +1,7 @@
1
1
  import * as account from "../private/email/accountMessages.mjs";
2
2
  import { escapeHtml } from "../private/email/escapeHtml.mjs";
3
3
  import { FALLBACK_FOOTER, FALLBACK_HEADER_1, FALLBACK_HEADER_2, orFallback, standaloneHeader } from "../private/email/htmlFrame.mjs";
4
- import { confirmationLink } from "../private/email/messageParts.mjs";
4
+ import { confirmationLink, httpLinkBase } from "../private/email/messageParts.mjs";
5
5
  import * as notice from "../private/email/noticeMessages.mjs";
6
6
  import { orFalse } from "../private/email/orFalse.mjs";
7
7
  import * as reset from "../private/email/resetMessages.mjs";
@@ -44,10 +44,14 @@ export class SocketLabsLib {
44
44
  * normalised away — the caller supplies configuration, not a pre-joined URL, and `//check` or
45
45
  * `example.comcheck` are not errors worth surfacing to a user mid-registration.
46
46
  *
47
+ * The base, whether passed or taken from `APP_DOMAIN`, must parse as an absolute `http:` / `https:` URL
48
+ * with no user name, password, control character or whitespace; any other value (`javascript:`, `data:`,
49
+ * `//host`, a host with no scheme) makes the call reject with `throwInternalError()` and sends nothing.
50
+ *
47
51
  * @param emailTo recipient, also embedded in the link (URI-encoded)
48
52
  * @param hash the activation hash stored on the account
49
53
  * @param name optional greeting name
50
- * @param linkBase scheme + host the link points at; defaults to `APP_DOMAIN`
54
+ * @param linkBase scheme + host the link points at; defaults to `APP_DOMAIN`. An absolute `http:` / `https:` URL, else the call rejects with a 500
51
55
  * @param linkPath route prefix the receiving service listens on; defaults to `/check/verify-email`
52
56
  */
53
57
  // eslint-disable-next-line max-params -- public signature, an options object would break consumers
@@ -111,7 +115,7 @@ SendResponse {
111
115
  }
112
116
  */
113
117
  async sendEmailChangeVerify(emailTo, hash, name = '') {
114
- const link = `${this.linkBase}/check/verify-change-email/${encodeURI(emailTo)}/${hash}`;
118
+ const link = `${httpLinkBase(this.linkBase)}/check/verify-change-email/${encodeURI(emailTo)}/${hash}`;
115
119
  return await this.sendTemplate(emailTo, account.changeVerifyMessage(this.platformName, link, name));
116
120
  }
117
121
  async sendWelcome(emailTo) {
@@ -199,7 +203,7 @@ SendResponse {
199
203
  * @param emailTo recipient, also embedded in the link (URI-encoded)
200
204
  * @param hash the reset hash stored on the account
201
205
  * @param name optional greeting name
202
- * @param linkBase scheme + host the link points at; defaults to `APP_DOMAIN`
206
+ * @param linkBase scheme + host the link points at; defaults to `APP_DOMAIN`. An absolute `http:` / `https:` URL, else the call rejects with a 500
203
207
  * @param linkPath front-end route prefix that renders the new-password form; defaults to `/x/reset`
204
208
  */
205
209
  // eslint-disable-next-line max-params -- public signature, an options object would break consumers
@@ -37,6 +37,9 @@ export declare const socketLabsResetPwdMailer: IResetPwdMailer;
37
37
  * arrives as `undefined` and the default takes over — `APP_DOMAIN` for the base, `/x/reset` for the path.
38
38
  * Normalising that to `''` at the call site instead would produce a link with no host at all.
39
39
  *
40
+ * `linkBase` must be an absolute `http:` / `https:` URL. Anything else (`javascript:`, `//host`, a host with no
41
+ * scheme, `''`) makes `sendEmailReset` reject with a 500 and send nothing.
42
+ *
40
43
  * ⚠️ `linkPath` names a **front-end route**, not a backend mount. It has to match the route that renders
41
44
  * the new-password form in the app `linkBase` serves; there is nothing on the server side that would fail
42
45
  * loudly if it does not, because the link is only ever followed by a person.
@@ -21,6 +21,9 @@ export const socketLabsResetPwdMailer = {
21
21
  * arrives as `undefined` and the default takes over — `APP_DOMAIN` for the base, `/x/reset` for the path.
22
22
  * Normalising that to `''` at the call site instead would produce a link with no host at all.
23
23
  *
24
+ * `linkBase` must be an absolute `http:` / `https:` URL. Anything else (`javascript:`, `//host`, a host with no
25
+ * scheme, `''`) makes `sendEmailReset` reject with a 500 and send nothing.
26
+ *
24
27
  * ⚠️ `linkPath` names a **front-end route**, not a backend mount. It has to match the route that renders
25
28
  * the new-password form in the app `linkBase` serves; there is nothing on the server side that would fail
26
29
  * loudly if it does not, because the link is only ever followed by a person.
@@ -1,5 +1,5 @@
1
1
  import { escapeHtml } from './escapeHtml.mjs';
2
- import { fixName, htmlLink } from './messageParts.mjs';
2
+ import { fixName, htmlLink, httpLinkBase } from './messageParts.mjs';
3
3
  /** Registration confirmation. `link` is the finished confirmation URL. */
4
4
  export function verifyMessage(platformName, link, name) {
5
5
  const nameFixed = fixName(name);
@@ -27,20 +27,22 @@ export function changeVerifyMessage(platformName, link, name) {
27
27
  }
28
28
  /** Welcome mail linking to the platform home. */
29
29
  export function welcomeMessage(platformName, linkBase) {
30
+ const base = httpLinkBase(linkBase);
30
31
  return {
31
32
  subject: `Welcome to ${platformName}`,
32
33
  textBody: `Welcome to ${platformName}`,
33
- htmlBody: `Welcome to ${htmlLink(linkBase, platformName)}`
34
+ htmlBody: `Welcome to ${htmlLink(base, platformName)}`
34
35
  };
35
36
  }
36
37
  /** Subscription confirmation with the activation code. */
37
38
  export function subscriptionMessage(platformName, linkBase, otp) {
38
- const url = `${linkBase}/x/emailVerify`;
39
+ const base = httpLinkBase(linkBase);
40
+ const url = `${base}/x/emailVerify`;
39
41
  return {
40
42
  subject: `Activate your ${platformName} account`,
41
43
  textBody: `To confirm your subscription on ${platformName}, open the following link in your browser
42
44
  ${url} and enter the following activation code: ${otp}`,
43
- htmlBody: `<p>To confirm your subscription on ${htmlLink(linkBase, platformName)}, open the following link in your browser
45
+ htmlBody: `<p>To confirm your subscription on ${htmlLink(base, platformName)}, open the following link in your browser
44
46
  ${htmlLink(url)} and enter the following activation code: ${escapeHtml(otp)}</p>`
45
47
  };
46
48
  }
@@ -5,8 +5,17 @@ export declare function fixName(name: string): string;
5
5
  * pass through {@link escapeHtml}; the plain-text part keeps the unescaped URL.
6
6
  */
7
7
  export declare function htmlLink(link: string, linkText?: string): string;
8
+ /**
9
+ * The scheme + host every link in a mail is built on, checked before it is placed in a link or an `href`.
10
+ * Returns `linkBase` exactly as given when it is an absolute `http:` / `https:` URL; otherwise throws
11
+ * `throwInternalError()` (500 `Internal Server Error`, `Error reported to Dev Team.`), as `wrongHashMessage`
12
+ * does: a base that is not one is a configuration or caller mistake, never something the recipient can fix,
13
+ * and the mail is not sent. Escaping alone does not cover this: a `javascript:` base survives `escapeHtml`
14
+ * and becomes a link target.
15
+ */
16
+ export declare function httpLinkBase(linkBase: string): string;
8
17
  /**
9
18
  * Confirmation or reset link: `<base><path>/<encodeURI(email)>/<hash>`. A trailing slash on `linkBase` and a
10
- * missing leading slash on `linkPath` are normalised away.
19
+ * missing leading slash on `linkPath` are normalised away. `linkBase` goes through {@link httpLinkBase} first.
11
20
  */
12
21
  export declare function confirmationLink(linkBase: string, linkPath: string, emailTo: string, hash: string): string;
@@ -1,4 +1,5 @@
1
1
  import { StringLib } from "../../lib/StringLib.mjs";
2
+ import { throwInternalError } from "../../graphQL/throw/throwInternalError.mjs";
2
3
  import { escapeHtml } from './escapeHtml.mjs';
3
4
  const strings = new StringLib();
4
5
  /** Greeting suffix: a leading space plus the name, or nothing when there is no name. */
@@ -19,12 +20,45 @@ function stripTrailingSlashes(value) {
19
20
  end -= 1;
20
21
  return value.slice(0, end);
21
22
  }
23
+ /**
24
+ * Control characters, whitespace and backslash. The URL parser drops or rewrites them (it strips leading and
25
+ * trailing control characters and spaces, removes tab and newline anywhere, turns `\` into `/`), so a string
26
+ * that holds one parses as something other than what is written. The base is emitted as written, so it must be
27
+ * a string the parser reads as it stands.
28
+ */
29
+ const NOT_PARSED_AS_WRITTEN = /[\p{Cc}\s\\]/u;
30
+ /**
31
+ * Judge a link base on the parsed URL, never on its prefix: `JaVaScRiPt:`, ` javascript:` and `java\tscript:`
32
+ * all parse to the `javascript:` scheme, `//evil.example` has no scheme and does not parse at all, and
33
+ * `https://good@evil` is an `https:` URL whose host is `evil`. Only an absolute `http:` or `https:` URL passes,
34
+ * and one with no user name and no password, since a base never needs them and `user@host` is how a link is
35
+ * made to read as a host it does not go to.
36
+ */
37
+ function isHttpLinkBase(value) {
38
+ if (NOT_PARSED_AS_WRITTEN.test(value))
39
+ return false;
40
+ const url = URL.parse(value);
41
+ return url !== null && (url.protocol === 'http:' || url.protocol === 'https:') && url.username === '' && url.password === '';
42
+ }
43
+ /**
44
+ * The scheme + host every link in a mail is built on, checked before it is placed in a link or an `href`.
45
+ * Returns `linkBase` exactly as given when it is an absolute `http:` / `https:` URL; otherwise throws
46
+ * `throwInternalError()` (500 `Internal Server Error`, `Error reported to Dev Team.`), as `wrongHashMessage`
47
+ * does: a base that is not one is a configuration or caller mistake, never something the recipient can fix,
48
+ * and the mail is not sent. Escaping alone does not cover this: a `javascript:` base survives `escapeHtml`
49
+ * and becomes a link target.
50
+ */
51
+ export function httpLinkBase(linkBase) {
52
+ if (!isHttpLinkBase(linkBase))
53
+ throwInternalError();
54
+ return linkBase;
55
+ }
22
56
  /**
23
57
  * Confirmation or reset link: `<base><path>/<encodeURI(email)>/<hash>`. A trailing slash on `linkBase` and a
24
- * missing leading slash on `linkPath` are normalised away.
58
+ * missing leading slash on `linkPath` are normalised away. `linkBase` goes through {@link httpLinkBase} first.
25
59
  */
26
60
  export function confirmationLink(linkBase, linkPath, emailTo, hash) {
27
- const base = stripTrailingSlashes(linkBase);
61
+ const base = stripTrailingSlashes(httpLinkBase(linkBase));
28
62
  const path = `/${linkPath.replace(/^\/+/, '')}`;
29
63
  return `${base}${path}/${encodeURI(emailTo)}/${hash}`;
30
64
  }
@@ -1,6 +1,6 @@
1
1
  import { escapeHtml } from './escapeHtml.mjs';
2
2
  import { FALLBACK_FOOTER, standaloneHeader } from './htmlFrame.mjs';
3
- import { fixName, htmlLink } from './messageParts.mjs';
3
+ import { fixName, htmlLink, httpLinkBase } from './messageParts.mjs';
4
4
  /** Password-reset request. `link` is the finished reset URL. */
5
5
  export function resetMessage(platformName, link, name) {
6
6
  const nameFixed = fixName(name);
@@ -15,11 +15,12 @@ export function resetMessage(platformName, link, name) {
15
15
  }
16
16
  /** Confirmation that the new password is set, linking to the platform home. */
17
17
  export function resetConfirmationMessage(platformName, linkBase, name) {
18
+ const base = httpLinkBase(linkBase);
18
19
  const nameFixed = fixName(name);
19
20
  return {
20
21
  subject: `Password reset for ${platformName}`,
21
- textBody: `Hi${nameFixed}, you have confirmed your new password. You can now log in at: ${linkBase}. The Team.`,
22
- htmlBody: `Hi${escapeHtml(nameFixed)},<br>you have confirmed your new password.<br><br>You can now log in at:<br>${htmlLink(linkBase, platformName)}<br><br>The Team.`
22
+ textBody: `Hi${nameFixed}, you have confirmed your new password. You can now log in at: ${base}. The Team.`,
23
+ htmlBody: `Hi${escapeHtml(nameFixed)},<br>you have confirmed your new password.<br><br>You can now log in at:<br>${htmlLink(base, platformName)}<br><br>The Team.`
23
24
  };
24
25
  }
25
26
  /**
@@ -27,11 +28,12 @@ export function resetConfirmationMessage(platformName, linkBase, name) {
27
28
  * the `encodeURI`d address in its query string; it only appears in the HTML part, so it is escaped there.
28
29
  */
29
30
  export function resetConfirmationHashMessage(platformName, linkBase, to) {
31
+ const base = httpLinkBase(linkBase);
30
32
  const subject = `Password change confirmation for ${platformName}`;
31
- const linkReset = linkBase + '/index.php?q=reset&hash=' + to.hash + '&email=' + encodeURI(to.email);
33
+ const linkReset = base + '/index.php?q=reset&hash=' + to.hash + '&email=' + encodeURI(to.email);
32
34
  return {
33
35
  subject,
34
- textBody: 'Hi ' + to.name + ', you have confirmed your new password. You can now log in at: ' + linkBase + ' . ',
36
+ textBody: 'Hi ' + to.name + ', you have confirmed your new password. You can now log in at: ' + base + ' . ',
35
37
  htmlBody: standaloneHeader(subject) +
36
38
  'Hi ' +
37
39
  escapeHtml(to.name) +
@@ -2,6 +2,7 @@ import { DEFAULT_VERIFY_EMAIL_PATHS } from "../../../../lib/access/accessPaths.m
2
2
  import { defaultVerifyEmailMailer } from "../../../../lib/access/verifyEmailMailer.mjs";
3
3
  import { UserBase } from "../../../../graphQL/models/MongoDB/UserBase.mjs";
4
4
  import { buildUnset } from "../pathTools.mjs";
5
+ import * as Sentry from '@sentry/node';
5
6
  /**
6
7
  * Mark the address verified, clear the pending-verification fields, welcome the user.
7
8
  *
@@ -18,7 +19,12 @@ export const createEnableEmailAccess = (model, paths, mailer) => async function
18
19
  }, {
19
20
  runValidators: true
20
21
  });
21
- await mailer.sendWelcome(email);
22
+ try {
23
+ await mailer.sendWelcome(email);
24
+ }
25
+ catch (e) {
26
+ Sentry.captureException(e);
27
+ }
22
28
  };
23
29
  /** `UserBase`-bound default — the behaviour every existing consumer already imports. */
24
30
  export const enableEmailAccess = createEnableEmailAccess(UserBase, DEFAULT_VERIFY_EMAIL_PATHS, defaultVerifyEmailMailer);
@@ -10,6 +10,10 @@
10
10
  * The gate lives in this function rather than in the three middlewares that call it, so a direct
11
11
  * caller of the primitive cannot reach an ungated comparison.
12
12
  *
13
+ * The comparison is `safeEqualSecret`: both sides are hashed to 32 bytes first, so the compare takes the
14
+ * same time whether the header is shorter, longer or the same length as the secret. A length check before
15
+ * the compare would tell a caller how long INTROSPECTION_CODE is. For two strings the result is exactly `===`.
16
+ *
13
17
  * Fails closed on the secret too: an unset or empty INTROSPECTION_CODE never matches, whatever the
14
18
  * caller sends. The call sites previously compared against `${process.env.INTROSPECTION_CODE}`,
15
19
  * which coerces an unset variable to the literal string 'undefined' — a client sending that exact
@@ -1,6 +1,5 @@
1
- import { Buffer } from 'node:buffer';
2
- import { timingSafeEqual } from 'node:crypto';
3
1
  import { isIntrospectionBypassAllowed } from "../../lib/isIntrospectionBypassAllowed.mjs";
2
+ import { safeEqualSecret } from "./access/safeEqualSecret.mjs";
4
3
  /**
5
4
  * Constant-time check of the `x-introspectioncode` header against INTROSPECTION_CODE.
6
5
  *
@@ -13,6 +12,10 @@ import { isIntrospectionBypassAllowed } from "../../lib/isIntrospectionBypassAll
13
12
  * The gate lives in this function rather than in the three middlewares that call it, so a direct
14
13
  * caller of the primitive cannot reach an ungated comparison.
15
14
  *
15
+ * The comparison is `safeEqualSecret`: both sides are hashed to 32 bytes first, so the compare takes the
16
+ * same time whether the header is shorter, longer or the same length as the secret. A length check before
17
+ * the compare would tell a caller how long INTROSPECTION_CODE is. For two strings the result is exactly `===`.
18
+ *
16
19
  * Fails closed on the secret too: an unset or empty INTROSPECTION_CODE never matches, whatever the
17
20
  * caller sends. The call sites previously compared against `${process.env.INTROSPECTION_CODE}`,
18
21
  * which coerces an unset variable to the literal string 'undefined' — a client sending that exact
@@ -26,16 +29,7 @@ export const verifyIntrospectionCode = (headerValue) => {
26
29
  if (typeof code !== 'string' || code.length === 0) {
27
30
  return false;
28
31
  }
29
- if (typeof headerValue !== 'string') {
30
- return false;
31
- }
32
- // byte length, not character length: timingSafeEqual throws on unequal-length buffers, and a
33
- // multi-byte header value can match code.length while encoding to a different number of bytes
34
- const headerBuffer = Buffer.from(headerValue);
35
- const codeBuffer = Buffer.from(code);
36
- if (headerBuffer.length !== codeBuffer.length) {
37
- return false;
38
- }
39
- return timingSafeEqual(headerBuffer, codeBuffer);
32
+ // an absent header (undefined) is not a string either, and safeEqualSecret answers false for it
33
+ return safeEqualSecret(headerValue, code);
40
34
  };
41
35
  //# sourceMappingURL=verifyIntrospectionCode.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@axiumine/koa-utils",
3
- "version": "7.1.1",
3
+ "version": "7.2.0",
4
4
  "description": "Koa Utils",
5
5
  "type": "module",
6
6
  "repository": {
@@ -756,8 +756,8 @@
756
756
  "@types/node": "^26.6.5",
757
757
  "@types/pg": "^8.23.1",
758
758
  "@types/sinon": "^22.0.2",
759
- "@typescript-eslint/eslint-plugin": "^8.72.0",
760
- "@typescript-eslint/parser": "^8.72.0",
759
+ "@typescript-eslint/eslint-plugin": "^8.72.1",
760
+ "@typescript-eslint/parser": "^8.72.1",
761
761
  "c8": "^12.0.0",
762
762
  "chai": "^6.3.0",
763
763
  "clamscan": "^2.4.0",
@@ -780,7 +780,7 @@
780
780
  "mariadb": "^3.5.3",
781
781
  "mocha": "^12.0.3",
782
782
  "mongodb-memory-server": "^11.3.0",
783
- "mongoose": "^9.11.3",
783
+ "mongoose": "^9.11.4",
784
784
  "patch-package": "8.0.1",
785
785
  "pg": "^8.23.1",
786
786
  "prettier": "^3.9.10",
@@ -794,12 +794,15 @@
794
794
  "ts-patch": "^4.0.1",
795
795
  "type-coverage": "^2.30.4",
796
796
  "typescript": "^6.0.3",
797
- "typescript-eslint": "8.72.0",
797
+ "typescript-eslint": "8.72.1",
798
798
  "typescript-transform-paths": "^4.0.0",
799
799
  "uuid": "^14.0.3"
800
800
  },
801
801
  "resolutions": {
802
802
  "@socketlabs/email/axios": "^1.21.0",
803
- "sequelize/uuid": "^11.1.1"
803
+ "sequelize/uuid": "^11.1.1",
804
+ "**/typed-rest-client/qs": "^6.16.1",
805
+ "**/glob": "^14.0.2",
806
+ "**/minimatch": "^11.0.3"
804
807
  }
805
808
  }