@axiumine/koa-utils 8.1.0 → 9.1.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.
Files changed (41) hide show
  1. package/LICENSE +658 -228
  2. package/README.md +12 -11
  3. package/dist/dataSources/PostgreSQL.mjs +5 -5
  4. package/dist/email/SocketLabsLib.d.mts +2 -1
  5. package/dist/email/SocketLabsLib.mjs +5 -3
  6. package/dist/files/storeUploadAsTemp.mjs +2 -0
  7. package/dist/graphQL/schema/mutations/emailChangeHashVerify.mjs +2 -1
  8. package/dist/graphQL/schema/mutations/logout.mjs +1 -1
  9. package/dist/graphQL/schema/mutations/resetPwd.mjs +3 -1
  10. package/dist/koa/middleware/authenticatedAuthorizationHandler/index.d.mts +1 -1
  11. package/dist/koa/middleware/authenticatedAuthorizationHandler/verifySignedRefreshToken.mjs +12 -9
  12. package/dist/koa/middleware/authenticatedLogoutHandler/index.d.mts +1 -1
  13. package/dist/koa/middleware/authenticatedResourceHandler/index.d.mts +1 -1
  14. package/dist/koa/middleware/debug/index.d.mts +1 -1
  15. package/dist/lib/ArrayLib.d.mts +0 -1
  16. package/dist/lib/ArrayLib.mjs +0 -1
  17. package/dist/lib/DateLib.mjs +1 -1
  18. package/dist/lib/MariaDB/throwSqlErrors.mjs +3 -1
  19. package/dist/lib/MongoDB/IMongoDBError.d.mts +2 -3
  20. package/dist/lib/MongoDB/throwIfMongoErr.mjs +4 -2
  21. package/dist/lib/NumLib.d.mts +0 -1
  22. package/dist/lib/NumLib.mjs +1 -1
  23. package/dist/lib/StringLib.d.mts +0 -1
  24. package/dist/lib/StringLib.mjs +0 -1
  25. package/dist/lib/db/log/logGraphql.d.mts +8 -6
  26. package/dist/lib/db/log/logGraphql.mjs +9 -23
  27. package/dist/lib/db/log/logThrow.d.mts +9 -0
  28. package/dist/lib/db/log/logThrow.mjs +11 -11
  29. package/dist/lib/hash.mjs +1 -6
  30. package/dist/lib/isSessionBlocked.d.mts +1 -1
  31. package/dist/lib/throwIfNotValidEnumValue.mjs +1 -0
  32. package/dist/lib/tryCatchRethrow.mjs +5 -3
  33. package/dist/private/files/reEncode.mjs +2 -0
  34. package/dist/private/lib/access/db/abandonUser.mjs +2 -3
  35. package/dist/private/lib/access/db/getResetPwd.mjs +4 -2
  36. package/dist/private/lib/access/db/setEmailHash.mjs +3 -1
  37. package/dist/private/lib/access/db/userData4VerifyEmail.d.mts +1 -1
  38. package/dist/private/lib/access/db/userData4VerifyEmail.mjs +4 -2
  39. package/dist/private/lib/access/handleIfHashBad.mjs +1 -0
  40. package/dist/private/lib/access/pathTools.mjs +2 -5
  41. package/package.json +18 -22
package/README.md CHANGED
@@ -8,9 +8,9 @@ TypeScript utility library for Koa + GraphQL backends. Ships authentication midd
8
8
  - **Module format:** ESM only (`.mjs` + `.d.mts`)
9
9
  - **Node:** `^24.14.0 || ^26.13.0` (24 and 26 are the LTS lines; the suite runs on both)
10
10
  - **TypeScript:** `6.0`
11
- - **License:** GPL-3.0-or-later
11
+ - **License:** AGPL-3.0-or-later (versions up to 8.1.0: GPL-3.0-or-later)
12
12
  - **Maintainers:** [Giovanni Manzoni](https://www.giovannimanzoni.com) and [Vincenzo Favara](https://github.com/vivi7)
13
- - **Project:** [Contributing](https://github.com/Axiumine/koa-utils/blob/main/CONTRIBUTING.md) · [Governance](https://github.com/Axiumine/koa-utils/blob/main/GOVERNANCE.md) · [Roadmap](https://github.com/Axiumine/koa-utils/blob/main/ROADMAP.md) · [Security policy](https://github.com/Axiumine/koa-utils/blob/main/SECURITY.md) · [Code of Conduct](https://github.com/Axiumine/koa-utils/blob/main/CODE_OF_CONDUCT.md) · [Changelog](https://github.com/Axiumine/koa-utils/blob/main/CHANGELOG.md)
13
+ - **Project:** [Contributing](https://github.com/Axiumine/koa-utils/blob/main/CONTRIBUTING.md) · [Contributor License Agreement](https://github.com/Axiumine/koa-utils/blob/main/CLA.md) · [Governance](https://github.com/Axiumine/koa-utils/blob/main/GOVERNANCE.md) · [Roadmap](https://github.com/Axiumine/koa-utils/blob/main/ROADMAP.md) · [Security policy](https://github.com/Axiumine/koa-utils/blob/main/SECURITY.md) · [Code of Conduct](https://github.com/Axiumine/koa-utils/blob/main/CODE_OF_CONDUCT.md) · [Changelog](https://github.com/Axiumine/koa-utils/blob/main/CHANGELOG.md)
14
14
 
15
15
  ## Install
16
16
 
@@ -312,7 +312,9 @@ For the cluster path the `rediss://` scheme on `rootNodes` is not enough on its
312
312
  ## Build (contributors only)
313
313
 
314
314
  ```bash
315
+ corepack enable # once: Yarn 4 comes from the packageManager field
315
316
  yarn install
317
+ yarn hooks:install # maintainers: points git at .githooks (Yarn 4 does not run the prepare script)
316
318
  yarn build # ESM only — production output
317
319
  yarn build:all # not usable today: the CJS half emits nothing, the package is ESM-only (use yarn build)
318
320
  yarn test # build + build:tests + mocha, no coverage gate
@@ -333,24 +335,21 @@ There is no barrel and no `main` / `module` field.
333
335
 
334
336
  ### Registry
335
337
 
336
- `yarn.lock` always resolves against `https://registry.npmjs.org/`, so a plain clone installs with no extra setup.
338
+ `yarn.lock` is in the Yarn 4 format, which records no registry host, so a plain clone installs with no extra setup (`corepack enable`, then `yarn install`). `.yarnrc.yml` points Yarn at `https://registry.npmjs.org`.
337
339
 
338
- If you install through a private npm mirror, do not commit its host. Yarn 1 downloads tarballs from the absolute `resolved` URL in the lockfile and ignores the configured registry for them, so a lockfile written through a mirror breaks every clone that cannot reach it. Nothing is rewritten unless you ask for it:
340
+ If you install through a private npm mirror, set an environment variable instead of editing any file. It overrides `.yarnrc.yml` for your shell only:
339
341
 
340
342
  ```sh
341
- export REGISTRY_MIRROR=http://host:4873
342
- yarn registry:mirror # public registry -> mirror, before install
343
+ export YARN_NPM_REGISTRY_SERVER=http://host:4873
343
344
  yarn install
344
- yarn registry:canonical # mirror -> public registry, before commit
345
- yarn registry:check # exit 1 if yarn.lock names any other host
346
345
  ```
347
346
 
348
- `registry:check` needs no `REGISTRY_MIRROR`. A pre-commit check also rejects any staged lockfile that names a non-public host.
347
+ Credentials belong in `~/.yarnrc.yml`, never in the repository. A pre-commit check rejects a Yarn 1 lockfile, a lockfile that resolves a package from a URL or git source, and a tracked `.yarnrc.yml` that sets credentials or another registry.
349
348
 
350
349
  ## Feedback, contributing and security
351
350
 
352
351
  - **Bugs and feature requests:** open an issue at <https://github.com/Axiumine/koa-utils/issues/new/choose>. Issues are public and searchable.
353
- - **Contributing code:** fork, branch from `main` and open a pull request; larger changes start with an issue. [CONTRIBUTING.md](https://github.com/Axiumine/koa-utils/blob/main/CONTRIBUTING.md) lists the requirements (tests at 100% coverage, docs in the same change, Conventional Commits, GPL-3.0-or-later). How decisions are made is in [GOVERNANCE.md](https://github.com/Axiumine/koa-utils/blob/main/GOVERNANCE.md); the direction is in [ROADMAP.md](https://github.com/Axiumine/koa-utils/blob/main/ROADMAP.md).
352
+ - **Contributing code:** fork, branch from `main` and open a pull request; larger changes start with an issue. [CONTRIBUTING.md](https://github.com/Axiumine/koa-utils/blob/main/CONTRIBUTING.md) lists the requirements (tests at 100% coverage, docs in the same change, Conventional Commits, acceptance of the [CLA](https://github.com/Axiumine/koa-utils/blob/main/CLA.md), AGPL-3.0-or-later). How decisions are made is in [GOVERNANCE.md](https://github.com/Axiumine/koa-utils/blob/main/GOVERNANCE.md); the direction is in [ROADMAP.md](https://github.com/Axiumine/koa-utils/blob/main/ROADMAP.md).
354
353
  - **Security vulnerabilities:** never in a public issue. Use GitHub private vulnerability reporting or the email in [SECURITY.md](https://github.com/Axiumine/koa-utils/blob/main/SECURITY.md), which also states the supported versions and response times.
355
354
  - **Security model and design:** what the library does and does not protect against is in [docs/security.md](https://github.com/Axiumine/koa-utils/blob/main/docs/security.md); the structure is in [docs/architecture.md](https://github.com/Axiumine/koa-utils/blob/main/docs/architecture.md). How to check a release (signed tag, rebuild, attestation) is in [docs/verify-release.md](https://github.com/Axiumine/koa-utils/blob/main/docs/verify-release.md).
356
355
  - **Release notes:** [CHANGELOG.md](https://github.com/Axiumine/koa-utils/blob/main/CHANGELOG.md), one entry per release, with a `Security` section whenever a release fixes a vulnerability.
@@ -361,4 +360,6 @@ yarn registry:check # exit 1 if yarn.lock names any other host
361
360
 
362
361
  ## License
363
362
 
364
- GPL-3.0-or-later © Giovanni Manzoni
363
+ AGPL-3.0-or-later © Giovanni Manzoni
364
+
365
+ Versions up to 8.1.0 were published under GPL-3.0-or-later and stay available under it. From 9.0.0 the package is under the GNU Affero General Public License: if you modify it and let users interact with your modified version over a network, you must offer them its source, and your own application may count as a combined work that the license covers. Read `LICENSE` against how you use the package before you upgrade. For other licensing terms, write to dev@giovannimanzoni.com.
@@ -49,7 +49,7 @@ export const PostgreSQLClientConnect = async () => {
49
49
  pgClient.on('notification', (msg) => {
50
50
  console.info('[PostgreSQL Client]', msg.channel);
51
51
  console.info('[PostgreSQL Client]', msg.payload);
52
- Sentry.captureMessage(`[PostgreSQL Client] notification: ${msg}`, {
52
+ Sentry.captureMessage(`[PostgreSQL Client] notification: ${msg.channel}`, {
53
53
  level: 'warning',
54
54
  extra: {
55
55
  channel: msg.channel,
@@ -61,14 +61,14 @@ export const PostgreSQLClientConnect = async () => {
61
61
  // https://www.postgresql.org/docs/9.6/static/plpgsql-errors-and-messages.html
62
62
  if (!pgClient.listenerCount('notice')) {
63
63
  pgClient.on('notice', (msg) => {
64
- Sentry.captureMessage(`[PostgreSQL Client] notice: ${msg}`, 'warning');
64
+ Sentry.captureMessage(`[PostgreSQL Client] notice: ${msg.message}`, 'warning');
65
65
  });
66
66
  }
67
67
  console.info('[PostgreSQL Client] OK: PostgreSQL connection has been established successfully.');
68
68
  }
69
69
  catch (error) {
70
70
  throw {
71
- message: '[PostgreSQL Client] FAIL: Unable to connect to the database: ' + error,
71
+ message: '[PostgreSQL Client] FAIL: Unable to connect to the database: ' + String(error),
72
72
  shutdown: true
73
73
  };
74
74
  }
@@ -81,7 +81,7 @@ export const PostgreSQLClientDisconnect = async () => {
81
81
  }
82
82
  catch (error) {
83
83
  throw {
84
- message: '[PostgreSQL Client] FAIL: Unable to close the database connection: ' + error,
84
+ message: '[PostgreSQL Client] FAIL: Unable to close the database connection: ' + String(error),
85
85
  shutdown: true
86
86
  };
87
87
  }
@@ -103,7 +103,7 @@ export const PostgreSQLPoolDisconnect = async () => {
103
103
  }
104
104
  catch (error) {
105
105
  throw {
106
- message: '[PostgreSQL Pool] FAIL: Unable to close the database connection: ' + error,
106
+ message: '[PostgreSQL Pool] FAIL: Unable to close the database connection: ' + String(error),
107
107
  shutdown: true
108
108
  };
109
109
  }
@@ -42,7 +42,8 @@ export declare class SocketLabsLib {
42
42
  */
43
43
  sendEmailVerify(emailTo: string, hash: string, name?: string, linkBase?: string, linkPath?: string): Promise<boolean>;
44
44
  /**
45
- * @fixme handle retry
45
+ * A timed-out send is reported as failed and is not retried by this class. The client is built with
46
+ * `numberOfRetries: 3`; whether the SDK retries a timeout has not been verified.
46
47
  *
47
48
  statusCode: ECONNABORTED
48
49
  Error in sending the email
@@ -14,7 +14,6 @@ export class SocketLabsLib {
14
14
  platformName;
15
15
  linkBase;
16
16
  emailFrom;
17
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- @socketlabs/email ships no types (untyped module in src/types/socketlabs-email.d.ts), so the client is untyped
18
17
  client;
19
18
  // Only so a send can hand the sender its required options; the sender ignores them because `client` is injected
20
19
  credentials;
@@ -25,7 +24,9 @@ export class SocketLabsLib {
25
24
  /* c8 ignore next -- env fallback '0' covered only when SOCKETLABS_SERVER_ID is unset */
26
25
  const serverId = parseInt(process.env['SOCKETLABS_SERVER_ID'] || '0');
27
26
  const apiKey = `${process.env['SOCKETLABS_SERVER_APIKEY']}`;
28
- this.client = new SocketLabsClient(serverId, apiKey, { requestTimeout: 120, numberOfRetries: 3 });
27
+ // The import is `any` (src/types/socketlabs-email.d.ts): one assertion gives the constructor the shape used here
28
+ const Client = SocketLabsClient;
29
+ this.client = new Client(serverId, apiKey, { requestTimeout: 120, numberOfRetries: 3 });
29
30
  this.credentials = { serverId, apiKey };
30
31
  this.platformName = `${process.env['PLATFORM_NAME']}`;
31
32
  this.linkBase = `${process.env['APP_DOMAIN']}`;
@@ -104,7 +105,8 @@ export class SocketLabsLib {
104
105
  }
105
106
  */
106
107
  /**
107
- * @fixme handle retry
108
+ * A timed-out send is reported as failed and is not retried by this class. The client is built with
109
+ * `numberOfRetries: 3`; whether the SDK retries a timeout has not been verified.
108
110
  *
109
111
  statusCode: ECONNABORTED
110
112
  Error in sending the email
@@ -16,6 +16,7 @@ export async function storeUploadAsTemp(upload, maxFileSize = MAX_FILE_SIZE) {
16
16
  // Store the file in the filesystem.
17
17
  await new Promise((resolve, reject) => {
18
18
  // Create a stream to which the upload will be written.
19
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the name is a server-side UUID inside UPLOAD_TEMP_DIRECTORY_URL; only the extension comes from the client, and path.extname never returns a path separator
19
20
  const writeStream = createWriteStream(storedFileUrl);
20
21
  // Check file size during streaming.
21
22
  // Only flags and stops the stream — the rejection is issued from the 'close'
@@ -34,6 +35,7 @@ export async function storeUploadAsTemp(upload, maxFileSize = MAX_FILE_SIZE) {
34
35
  // Best-effort cleanup, then reject. Cleanup is fire-and-forget by design: the
35
36
  // upload has already failed, and an unlink error must not mask the real cause.
36
37
  const removeThenReject = (reason) => {
38
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- same server-built path as the write stream above
37
39
  unlink(storedFileUrl, () => {
38
40
  reject(reason);
39
41
  });
@@ -28,7 +28,8 @@ export const createEmailChangeHashVerifyMutation = (deps) => {
28
28
  const ctx = await loadVerifyContext(deps, mailer, args.email.toLowerCase());
29
29
  // if email not found, return (do not tell the user the real problem !)
30
30
  if (ctx === null) {
31
- return false; // @fixme throw
31
+ // `false` is deliberate, not a missing throw: an error here would tell the caller the address is unknown.
32
+ return false;
32
33
  }
33
34
  if (safeEqualSecret(args.hash, readPath(ctx.user, deps.paths.hash))) {
34
35
  return handleValidHash(ctx);
@@ -16,7 +16,7 @@ export const logout = {
16
16
  // comes from authenticatedLogoutHandler, so re-adding the prefix here would delete
17
17
  // 'refresh:refresh:<uuid>' — a key that was never written — and leave the session alive
18
18
  await redisClient.del(`${process.env['REDIS_KEY']}${buildPrefixedRedisKey('refresh:', ctx.state.user.refreshToken)}`);
19
- const accessToken = ctx.state.user?.accessToken || '';
19
+ const accessToken = ctx.state.user.accessToken || '';
20
20
  if (accessToken !== '') {
21
21
  await redisClient.del(`${process.env['REDIS_KEY']}${buildPrefixedRedisKey('access:', accessToken)}`);
22
22
  }
@@ -1,3 +1,4 @@
1
+ /* eslint-disable sonarjs/no-redundant-optional -- under exactOptionalPropertyTypes `?: T` rejects an explicit `undefined`, so `| undefined` is what lets a caller pass `{ mailer: maybeMailer }` */
1
2
  import { socketLabsResetPwdMailer } from "../../../lib/access/resetPwdMailer.mjs";
2
3
  import { checkEmailLen } from "../../../lib/checkEmailLen.mjs";
3
4
  import { EMAIL_HASH_LEN } from "../../../lib/Constants.mjs";
@@ -43,7 +44,7 @@ export const createResetPwdMutation = (deps) => ({
43
44
  // ok, email exists
44
45
  // -> wait 10 minutes from the last password reset request
45
46
  // if a password request already exists, read the date in seconds.
46
- const lastReq = typeof resetPwdVal.resetDateReq !== 'undefined' ? new Date('' + resetPwdVal.resetDateReq) : null;
47
+ const lastReq = typeof resetPwdVal.resetDateReq !== 'undefined' ? new Date(String(resetPwdVal.resetDateReq)) : null;
47
48
  // request already made previously?
48
49
  // send a new email with the recovery link only if the last one is at least 10 minutes old
49
50
  const nowDt = new Date();
@@ -92,6 +93,7 @@ export const createResetPwdMutation = (deps) => ({
92
93
  // SocketLabs accepted the message would kill a link already sitting in the user's inbox.
93
94
  const mail = pendingMail;
94
95
  if (mail !== null) {
96
+ // eslint-disable-next-line sonarjs/no-try-promise -- the try is for a synchronous throw: `deps.mailer` is consumer code and can throw before it returns a promise, which `.catch()` never sees
95
97
  try {
96
98
  const mailer = deps.mailer ?? socketLabsResetPwdMailer;
97
99
  void mailer.sendEmailReset(uEmail, mail.hash, mail.name).catch((e) => {
@@ -1,4 +1,4 @@
1
1
  import { IContextRefresh } from "../../../graphQL/schema/context/IContextRefresh.mjs";
2
2
  import Keygrip from 'keygrip';
3
3
  import { Next } from 'koa';
4
- export declare const authenticatedAuthorizationHandler: (keys: Keygrip) => (ctx: IContextRefresh, next: Next) => Promise<any>;
4
+ export declare const authenticatedAuthorizationHandler: (keys: Keygrip) => (ctx: IContextRefresh, next: Next) => Promise<unknown>;
@@ -8,22 +8,25 @@ export function verifySignedRefreshToken(ctx, keys) {
8
8
  if (cookieHeader === undefined) {
9
9
  throw throwPreconditionFailedNoAuthCookie();
10
10
  }
11
- const cookies = {};
12
- cookieHeader.split(';').forEach((cookie) => {
11
+ // Only the two cookies this check needs are read, each into its own variable. Copying every pair into one
12
+ // object under its client-chosen name let the request pick the property written, `constructor` included.
13
+ let refreshToken;
14
+ let signature;
15
+ for (const cookie of cookieHeader.split(';')) {
13
16
  const [key, value] = cookie.trim().split('=');
14
- // @ts-expect-error ignore wrong keys
15
- cookies[key] = value;
16
- });
17
+ if (key === 'refresh_token') {
18
+ refreshToken = value;
19
+ }
20
+ else if (key === 'refresh_token.sig') {
21
+ signature = value;
22
+ }
23
+ }
17
24
  /**
18
25
  * 'refresh_token=27119032-9043-4a9f-bd4c-9d06fd576290; refresh_token.sig=P1gZO6-49xVEMkiMqkOjJ2Cxaf3mQb18GaflDsjibuv4fFWYIOzcW26didnVJ1aridyY40CFzDtufzI6zI8jkQ'
19
26
  */
20
- // Stryker disable next-line OptionalChaining: cookies is a local object literal assigned above and never null, so ?. never short-circuits
21
- const refreshToken = cookies?.refresh_token;
22
27
  if (!refreshToken) {
23
28
  throw throwRefreshTokenRequired();
24
29
  }
25
- // Stryker disable next-line OptionalChaining: cookies is a local object literal assigned above and never null, so ?. never short-circuits
26
- const signature = cookies?.['refresh_token.sig'];
27
30
  if (!signature) {
28
31
  throw throwRefreshTokenSignatureRequired();
29
32
  }
@@ -1,4 +1,4 @@
1
1
  import { IContextLogout } from "../../../graphQL/schema/context/IContextLogout.mjs";
2
2
  import Keygrip from 'keygrip';
3
3
  import { Next } from 'koa';
4
- export declare const authenticatedLogoutHandler: (keys: Keygrip) => (ctx: IContextLogout, next: Next) => Promise<any>;
4
+ export declare const authenticatedLogoutHandler: (keys: Keygrip) => (ctx: IContextLogout, next: Next) => Promise<unknown>;
@@ -3,4 +3,4 @@ import { Next } from 'koa';
3
3
  /**
4
4
  * Find out access token in Bearer header
5
5
  */
6
- export declare const authenticatedResourceHandler: () => (ctx: IContextAuthenticatedResource, next: Next) => Promise<any>;
6
+ export declare const authenticatedResourceHandler: () => (ctx: IContextAuthenticatedResource, next: Next) => Promise<unknown>;
@@ -1,3 +1,3 @@
1
1
  import { IContextRefresh } from "../../../graphQL/schema/context/IContextRefresh.mjs";
2
2
  import { Next } from 'koa';
3
- export declare const debugHandler: () => (ctx: IContextRefresh, next: Next) => Promise<any>;
3
+ export declare const debugHandler: () => (ctx: IContextRefresh, next: Next) => Promise<unknown>;
@@ -1,4 +1,3 @@
1
1
  export declare class ArrayLib {
2
- constructor();
3
2
  arrDiff(arr1: string[], arr2: string[]): string[];
4
3
  }
@@ -1,5 +1,4 @@
1
1
  export class ArrayLib {
2
- constructor() { }
3
2
  arrDiff(arr1, arr2) {
4
3
  const pair = [arr1, arr2];
5
4
  const [smaller, larger] = pair.sort((a, b) => a.length - b.length);
@@ -1,5 +1,5 @@
1
+ // eslint-disable-next-line @typescript-eslint/no-extraneous-class -- public API: consumers import the class and call `DateLib.getDate()`; replacing it with plain functions is a breaking change
1
2
  export const DateLib = class DateLib {
2
- constructor() { }
3
3
  static getDate(dateNum) {
4
4
  const dateStr = dateNum.toString();
5
5
  const year = parseInt(dateStr.substring(0, 4));
@@ -1,8 +1,10 @@
1
1
  import { throwErrorWrongUserInput } from "../../graphQL/throw/throwErrorWrongUserInput.mjs";
2
2
  import { throwInternalError } from "../../graphQL/throw/throwInternalError.mjs";
3
3
  import { MariaDBErrType } from './MariaDBErrType.mjs';
4
+ // The driver reports `code` as an open string: widening the catalogue entry keeps this a string-to-string comparison.
5
+ const DATA_TOO_LONG = MariaDBErrType.ER_DATA_TOO_LONG;
4
6
  export function throwSqlErrors(e) {
5
- if (e.parent && e.parent.sqlMessage && e.parent.code === MariaDBErrType.ER_DATA_TOO_LONG) {
7
+ if (e.parent && e.parent.sqlMessage && e.parent.code === DATA_TOO_LONG) {
6
8
  const err = e.parent.sqlMessage.replace(' column', '');
7
9
  // Find the index of the first occurrence of the single quote
8
10
  const firstQuoteIndex = err.indexOf("'");
@@ -1,11 +1,10 @@
1
- import { MongoDBErrType } from "./MongoDBErrType.mjs";
2
1
  export interface IMongoDBError {
3
2
  errorResponse?: {
4
- code: MongoDBErrType;
3
+ code: number;
5
4
  };
6
5
  parent?: {
7
6
  errorResponse?: {
8
- code: MongoDBErrType;
7
+ code: number;
9
8
  };
10
9
  };
11
10
  message: string;
@@ -1,9 +1,11 @@
1
1
  import { MongoDBErrType } from "./MongoDBErrType.mjs";
2
2
  import { throwConflictError } from "../../graphQL/throw/throwConflictError.mjs";
3
3
  import { throwErrorWrongUserInput } from "../../graphQL/throw/throwErrorWrongUserInput.mjs";
4
+ // The driver reports `code` as an open number: widening the catalogue entry keeps this a number-to-number comparison.
5
+ const DUPLICATE_KEY = MongoDBErrType.DuplicateKeyError;
4
6
  export function throwIfMongoErr(e) {
5
- if ((e.errorResponse && e.errorResponse.code === MongoDBErrType.DuplicateKeyError) ||
6
- (e.parent && e.parent.errorResponse && e.parent.errorResponse.code === MongoDBErrType.DuplicateKeyError)) {
7
+ if ((e.errorResponse && e.errorResponse.code === DUPLICATE_KEY) ||
8
+ (e.parent && e.parent.errorResponse && e.parent.errorResponse.code === DUPLICATE_KEY)) {
7
9
  throw throwConflictError();
8
10
  }
9
11
  else if (e.message.startsWith('[Validator]')) {
@@ -1,5 +1,4 @@
1
1
  export declare class NumLib {
2
- constructor();
3
2
  /************
4
3
  * parseFloat wants '.' as the decimal separator !!
5
4
  *
@@ -1,5 +1,5 @@
1
+ // eslint-disable-next-line @typescript-eslint/no-extraneous-class -- public API: consumers import the class and call `NumLib.parseFloatFixed()`; replacing it with plain functions is a breaking change
1
2
  export class NumLib {
2
- constructor() { }
3
3
  /************
4
4
  * parseFloat wants '.' as the decimal separator !!
5
5
  *
@@ -1,5 +1,4 @@
1
1
  export declare class StringLib {
2
- constructor();
3
2
  cleanHtml(str: string): string;
4
3
  cleanHtmlUndefined(str: string | undefined): string | undefined;
5
4
  /**
@@ -55,7 +55,6 @@ function stripTags(input) {
55
55
  }
56
56
  export class StringLib {
57
57
  // implements IStringLib
58
- constructor() { }
59
58
  cleanHtml(str) {
60
59
  return stripTags(str);
61
60
  }
@@ -1,9 +1,11 @@
1
- import { Types } from 'mongoose';
1
+ import type { Types } from 'mongoose';
2
2
  /**
3
- * Logs operations performed by users
4
- * @param owner
5
- * @param nome
6
- * @param status
7
- * @param msTot
3
+ * Kept for backwards compatibility only: this function writes nothing.
4
+ *
5
+ * It used to build a `LogStatsGraphql` document and discard it. The `.save()` call was commented out, so
6
+ * nothing reached MongoDB. The arguments are still accepted, and ignored, so that existing call sites keep
7
+ * compiling.
8
+ *
9
+ * @deprecated No-op. Nothing is logged: remove the call, or write the document yourself through the `LogStatsGraphql` model.
8
10
  */
9
11
  export declare const logGraphql: (owner: Types.ObjectId, nome: string, status: number, msTot: number) => void;
@@ -1,27 +1,13 @@
1
- import { LogStatsGraphql } from "../../../graphQL/models/MongoDB/log/LogStatsGraphql.mjs";
2
1
  /**
3
- * Logs operations performed by users
4
- * @param owner
5
- * @param nome
6
- * @param status
7
- * @param msTot
2
+ * Kept for backwards compatibility only: this function writes nothing.
3
+ *
4
+ * It used to build a `LogStatsGraphql` document and discard it. The `.save()` call was commented out, so
5
+ * nothing reached MongoDB. The arguments are still accepted, and ignored, so that existing call sites keep
6
+ * compiling.
7
+ *
8
+ * @deprecated No-op. Nothing is logged: remove the call, or write the document yourself through the `LogStatsGraphql` model.
8
9
  */
9
- export const logGraphql = function (owner, nome, status, msTot) {
10
- new LogStatsGraphql({
11
- owner,
12
- nome,
13
- status,
14
- msTot
15
- });
16
- /*
17
- return new Promise((resolve, reject) => {
18
- newStatsGraphql.save((err: any, res: any) => {
19
- if (err) {
20
- reject('Log error.' + err)
21
- } else {
22
- resolve(res)
23
- }
24
- })
25
- }) */
10
+ export const logGraphql = function () {
11
+ // Deliberately empty, see the doc above.
26
12
  };
27
13
  //# sourceMappingURL=logGraphql.mjs.map
@@ -1 +1,10 @@
1
+ /**
2
+ * Kept for backwards compatibility only: this function writes nothing.
3
+ *
4
+ * It used to build a `LogThrow` document and discard it. The `.save()` call was commented out, so nothing
5
+ * reached MongoDB, and the mail-on-error idea noted in the body was never implemented. The arguments are
6
+ * still accepted, and ignored, so that existing call sites keep compiling.
7
+ *
8
+ * @deprecated No-op. Nothing is logged: remove the call, or write the document yourself through the `LogThrow` model.
9
+ */
1
10
  export declare const logThrow: (log: string, errLevel: number) => void;
@@ -1,15 +1,15 @@
1
- import { LogThrow } from "../../../graphQL/models/MongoDB/log/LogThrow.mjs";
2
- import { Types } from 'mongoose';
3
- // const lastSendEmail = new Date();
4
- export const logThrow = function (log, errLevel) {
5
- new LogThrow({
6
- _id: new Types.ObjectId(),
7
- message: log,
8
- errLevel,
9
- inserted: new Date()
10
- });
1
+ /**
2
+ * Kept for backwards compatibility only: this function writes nothing.
3
+ *
4
+ * It used to build a `LogThrow` document and discard it. The `.save()` call was commented out, so nothing
5
+ * reached MongoDB, and the mail-on-error idea noted in the body was never implemented. The arguments are
6
+ * still accepted, and ignored, so that existing call sites keep compiling.
7
+ *
8
+ * @deprecated No-op. Nothing is logged: remove the call, or write the document yourself through the `LogThrow` model.
9
+ */
10
+ export const logThrow = function () {
11
+ // Deliberately empty, see the doc above. The original intent, never implemented:
11
12
  // send email, check last send email to avoid flooding (check last send email in collection with TTL / create a variable that stays available on every call to this function (lastSendEmail ?))
12
13
  // check db with config, e.g.: admin sets block on sending email because they're fixing the problem
13
- // return newThrowError.save()
14
14
  };
15
15
  //# sourceMappingURL=logThrow.mjs.map
package/dist/lib/hash.mjs CHANGED
@@ -5,11 +5,6 @@ import bcrypt from '@node-rs/bcrypt';
5
5
  * @param hash password hash
6
6
  */
7
7
  export async function compareHashAsync(clear, hash) {
8
- try {
9
- return await bcrypt.compare(clear, hash);
10
- }
11
- catch (err) {
12
- throw err;
13
- }
8
+ return await bcrypt.compare(clear, hash);
14
9
  }
15
10
  //# sourceMappingURL=hash.mjs.map
@@ -4,4 +4,4 @@
4
4
  * 'true' and 'false' alike — any non-empty value blocks.
5
5
  * Use this instead of deleting the token to block user access; set the flag from the control panel.
6
6
  */
7
- export declare function isSessionBlocked(redData: Record<string, string>): boolean;
7
+ export declare function isSessionBlocked(redData: Record<string, string> | null | undefined): boolean;
@@ -1,4 +1,5 @@
1
1
  import { throwErrorWrongUserInput } from "../graphQL/throw/throwErrorWrongUserInput.mjs";
2
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- published signature: removing `T` would break a consumer that passes an explicit type argument, `throwIfNotValidEnumValue<typeof MyEnum>(...)`
2
3
  export function throwIfNotValidEnumValue(enumObj, value) {
3
4
  const ret = Object.values(enumObj).includes(value);
4
5
  if (!ret) {
@@ -7,9 +7,11 @@ export function tryCatchRethrow(e) {
7
7
  throwIfMongoErr(e);
8
8
  // else throw here
9
9
  if (e instanceof GraphQLError) {
10
- // @ts-expect-error status do not exist
11
- const status = e.extensions?.http?.status || 500;
12
- const desc = e.extensions?.['description'] || '';
10
+ // The installed graphql types declare `extensions` as always present. Older majors left it undefined and the
11
+ // peer range has no floor, so it is read as optional, through the shape this function relies on.
12
+ const extensions = e.extensions;
13
+ const status = extensions?.http?.status || 500;
14
+ const desc = extensions?.description || '';
13
15
  throw throwGraphQLError(status, e.message, desc);
14
16
  }
15
17
  else {
@@ -13,6 +13,7 @@ export async function reEncode(filePath, ext, quality = 100) {
13
13
  try {
14
14
  // Read the bytes up front: sharp refuses to use one file as both input and output, which is
15
15
  // exactly what happens when the source already carries the target extension.
16
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- the path is this helper's input by design: the caller names a file it stored itself, nothing here builds it from request data
16
17
  const input = await fs.readFile(filePath);
17
18
  if (ext === 'jpeg') {
18
19
  await sharp(input).jpeg({ quality, progressive: true }).withMetadata({}).withExif({}).toFile(finalFilepath);
@@ -35,6 +36,7 @@ export async function reEncode(filePath, ext, quality = 100) {
35
36
  // extensions instead would delete the file just written whenever the two paths coincide
36
37
  if (finalFilepath !== filePath) {
37
38
  try {
39
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- same caller-supplied path as the read above
38
40
  await fs.unlink(filePath);
39
41
  }
40
42
  catch (e) {
@@ -8,10 +8,9 @@ import { createDeleteUserByEmail } from './deleteUserByEmail.mjs';
8
8
  */
9
9
  export const createAbandonUser = ({ model, paths, mode, deletedValue = true }) => {
10
10
  if (mode === 'keep') {
11
- // Stryker disable next-line BlockStatement: the body is only `return undefined`, and an empty async function body also resolves undefined.
12
- return async function keepUser() {
11
+ return function keepUser() {
13
12
  // Nothing to do: the caller disposes of abandoned registrations themselves.
14
- return undefined;
13
+ return Promise.resolve();
15
14
  };
16
15
  }
17
16
  if (mode === 'soft-delete') {
@@ -3,13 +3,15 @@ import { UserBase } from "../../../../graphQL/models/MongoDB/UserBase.mjs";
3
3
  import { buildProjection, readPath } from "../pathTools.mjs";
4
4
  export const createGetResetPwd = (model, paths) => async function getResetPwd(session, email) {
5
5
  let ret = null;
6
+ // `TAccessModel` is `Model<any>`, so the query result is `any`. Only `_id` is read by name; every other field goes
7
+ // through `readPath`.
6
8
  // Field name comes from the factory `paths` argument the consuming developer supplies at startup, never from request data.
7
9
  // nosemgrep: koa-utils.nosql-injection.dynamic-filter-key
8
- const queryRet = await model
10
+ const queryRet = (await model
9
11
  .findOne({ [paths.email]: email })
10
12
  .select(buildProjection([paths.name, paths.resetDateReq, paths.resetHash, paths.deleted, paths.disabled]))
11
13
  .session(session)
12
- .lean();
14
+ .lean());
13
15
  // if a reset request is found
14
16
  if (queryRet !== null) {
15
17
  // A tombstoned or locked-out account is not a reset target: without this, resetPwd mailed a
@@ -14,7 +14,9 @@ export const createSetEmailHash = (model, paths) => async function setEmailHash(
14
14
  [paths.dateLastReq]: dtNow
15
15
  }
16
16
  }, { session, runValidators: true });
17
- return hash; // else it goes into exception @fixme check
17
+ // `updateOne` rejects on a driver or validator error, so reaching this line means the write was accepted.
18
+ // A `userId` that matches no document is not an error: the hash is still returned.
19
+ return hash;
18
20
  };
19
21
  /** `UserBase`-bound default — the behaviour every existing consumer already imports. */
20
22
  export const setEmailHash = createSetEmailHash(UserBase, DEFAULT_VERIFY_EMAIL_PATHS);
@@ -1,5 +1,5 @@
1
1
  import { IVerifyEmailPaths, TAccessModel } from "../../../../lib/access/accessPaths.mjs";
2
- export declare const createUserData4VerifyEmail: (model: TAccessModel, paths: IVerifyEmailPaths) => (uEmail: string) => Promise<any>;
2
+ export declare const createUserData4VerifyEmail: (model: TAccessModel, paths: IVerifyEmailPaths) => (uEmail: string) => Promise<object>;
3
3
  /** Signature of the bound reader, for the modules that take it as a dependency. */
4
4
  export type TUserData4VerifyEmail = ReturnType<typeof createUserData4VerifyEmail>;
5
5
  /** `UserBase`-bound default — the behaviour every existing consumer already imports. */
@@ -7,12 +7,14 @@ export const createUserData4VerifyEmail = (model, paths) => async function userD
7
7
  // Every field the guard chain reads must be listed. This is a .lean() read, so a field left out
8
8
  // of the projection is simply absent on the returned object, with no error — which is how a
9
9
  // missing requestTimes turned every wrong-hash attempt into a 500 under a green coverage gate.
10
+ // `TAccessModel` is `Model<any>`, so the query result is `any`. A lean read is a plain object or null, and the
11
+ // guard chain only ever walks it by path, so `object` is all that is promised to the callers.
10
12
  // Field name comes from the factory `paths` argument the consuming developer supplies at startup, never from request data.
11
13
  // nosemgrep: koa-utils.nosql-injection.dynamic-filter-key
12
- const user = await model
14
+ const user = (await model
13
15
  .findOne({ [paths.email]: uEmail })
14
16
  .select(buildProjection([paths.hash, paths.valid, paths.dateLastReq, paths.requestTimes, paths.deleted, paths.disabled]))
15
- .lean();
17
+ .lean());
16
18
  // if email not found, return stNotFoundNotMatch
17
19
  if (user === null) {
18
20
  Sentry.captureMessage(`User ${uEmail} not exist`);
@@ -1,3 +1,4 @@
1
+ /* eslint-disable sonarjs/no-redundant-optional -- under exactOptionalPropertyTypes `?: T` rejects an explicit `undefined`, so `| undefined` is what lets a caller pass `{ dbHash: maybeHash }` */
1
2
  import { defaultVerifyEmailMailer } from "../../../lib/access/verifyEmailMailer.mjs";
2
3
  import { EMAIL_CHECK_LINK } from './Constants.mjs';
3
4
  import { incReqTimes } from './db/incReqTimes.mjs';