@axiumine/koa-utils 7.1.0 → 7.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 (84) hide show
  1. package/LICENSE +0 -5
  2. package/README.md +54 -2
  3. package/dist/dataSources/MariaDB.mjs +8 -6
  4. package/dist/dataSources/MongoDB.mjs +1 -1
  5. package/dist/dataSources/PostgreSQL.mjs +12 -12
  6. package/dist/dataSources/Redis.mjs +8 -7
  7. package/dist/email/SocketLabsLib.d.mts +0 -13
  8. package/dist/email/SocketLabsLib.mjs +48 -208
  9. package/dist/files/moveFileStaticDomain.mjs +1 -1
  10. package/dist/files/storeUploadAsTemp.mjs +5 -1
  11. package/dist/files/uploadTempImage.mjs +2 -1
  12. package/dist/files/uploadTempPdf.mjs +2 -1
  13. package/dist/graphQL/models/MongoDB/UserBase.d.mts +3 -1
  14. package/dist/graphQL/models/MongoDB/log/DevStatsGraphQLCalls.d.mts +3 -1
  15. package/dist/graphQL/models/MongoDB/log/LogGlobalError.d.mts +3 -1
  16. package/dist/graphQL/models/MongoDB/log/LogStatsGraphql.d.mts +3 -1
  17. package/dist/graphQL/models/MongoDB/log/LogThrow.d.mts +3 -1
  18. package/dist/graphQL/schema/mutations/emailChangeHashVerify.mjs +8 -76
  19. package/dist/graphQL/schema/mutations/login4Ever.mjs +1 -0
  20. package/dist/graphQL/schema/mutations/loginAdmin.mjs +1 -0
  21. package/dist/graphQL/schema/mutations/loginRememberme.mjs +1 -0
  22. package/dist/graphQL/schema/mutations/logout.mjs +2 -2
  23. package/dist/graphQL/schema/mutations/refresh.mjs +7 -5
  24. package/dist/graphQL/schema/mutations/resetPwd.d.mts +1 -1
  25. package/dist/graphQL/schema/mutations/signUp.mjs +1 -0
  26. package/dist/graphQL/schema/mutations/updatePassword.mjs +1 -48
  27. package/dist/koa/middleware/authenticatedAuthorizationHandler/index.mjs +2 -2
  28. package/dist/koa/middleware/authenticatedAuthorizationHandler/verifySignedRefreshToken.mjs +2 -0
  29. package/dist/koa/middleware/authenticatedLogoutHandler/index.mjs +2 -2
  30. package/dist/koa/middleware/authenticatedResourceHandler/index.mjs +2 -2
  31. package/dist/koa/tdwKoaErrorHandler.mjs +1 -1
  32. package/dist/lib/ArrayLib.mjs +4 -3
  33. package/dist/lib/DateLib.mjs +1 -0
  34. package/dist/lib/StringLib.mjs +56 -4
  35. package/dist/lib/db/log/hitStat.mjs +1 -0
  36. package/dist/lib/isIntrospectionBypassAllowed.mjs +1 -1
  37. package/dist/lib/isSessionBlocked.mjs +1 -1
  38. package/dist/lib/tokens.mjs +2 -1
  39. package/dist/lib/tryCatchRethrow.mjs +1 -1
  40. package/dist/private/dataSources/isRedisTlsRequired.mjs +1 -1
  41. package/dist/private/email/IEmailContent.d.mts +9 -0
  42. package/dist/private/email/IEmailContent.mjs +2 -0
  43. package/dist/private/email/accountMessages.d.mts +11 -0
  44. package/dist/private/email/accountMessages.mjs +55 -0
  45. package/dist/private/email/escapeHtml.d.mts +9 -0
  46. package/dist/private/email/escapeHtml.mjs +17 -0
  47. package/dist/private/email/htmlFrame.d.mts +10 -0
  48. package/dist/private/email/htmlFrame.mjs +25 -0
  49. package/dist/private/email/messageParts.d.mts +12 -0
  50. package/dist/private/email/messageParts.mjs +31 -0
  51. package/dist/private/email/noticeMessages.d.mts +14 -0
  52. package/dist/private/email/noticeMessages.mjs +51 -0
  53. package/dist/private/email/orFalse.d.mts +2 -0
  54. package/dist/private/email/orFalse.mjs +12 -0
  55. package/dist/private/email/resetMessages.d.mts +17 -0
  56. package/dist/private/email/resetMessages.mjs +44 -0
  57. package/dist/private/graphQL/models/MongoDB/private/UserAdminKoaUtils.d.mts +4 -2
  58. package/dist/private/graphQL/schema/mutations/_buildLoginStatsUpdate.mjs +4 -4
  59. package/dist/private/graphQL/schema/mutations/infoUserForLoginSQL.mjs +5 -4
  60. package/dist/private/graphQL/schema/mutations/setRedisLoginSession.mjs +2 -2
  61. package/dist/private/graphQL/schema/mutations/updateLoginStats4ever.mjs +2 -2
  62. package/dist/private/lib/access/applyPasswordReset.d.mts +22 -0
  63. package/dist/private/lib/access/applyPasswordReset.mjs +22 -0
  64. package/dist/private/lib/access/assertResetAllowed.d.mts +14 -0
  65. package/dist/private/lib/access/assertResetAllowed.mjs +51 -0
  66. package/dist/private/lib/access/assertVerifyEmailAllowed.d.mts +6 -1
  67. package/dist/private/lib/access/db/abandonUser.mjs +3 -0
  68. package/dist/private/lib/access/db/confirmNewEmail.mjs +2 -0
  69. package/dist/private/lib/access/db/deleteUserByEmail.mjs +2 -0
  70. package/dist/private/lib/access/db/enableEmailAccess.mjs +2 -0
  71. package/dist/private/lib/access/db/getResetPwd.mjs +2 -0
  72. package/dist/private/lib/access/db/removeResetReq.mjs +2 -0
  73. package/dist/private/lib/access/db/saveResetReq.mjs +2 -0
  74. package/dist/private/lib/access/db/setEmailHash.mjs +2 -0
  75. package/dist/private/lib/access/db/updatePasswordDb.mjs +2 -0
  76. package/dist/private/lib/access/db/userData4VerifyEmail.mjs +2 -0
  77. package/dist/private/lib/access/emailChangeHandlers.d.mts +35 -0
  78. package/dist/private/lib/access/emailChangeHandlers.mjs +87 -0
  79. package/dist/private/lib/access/handleIfHashBad.d.mts +4 -2
  80. package/dist/private/lib/access/handleIfHashBad.mjs +4 -1
  81. package/dist/private/lib/access/safeEqualSecret.d.mts +13 -0
  82. package/dist/private/lib/access/safeEqualSecret.mjs +26 -0
  83. package/dist/private/lib/verifyIntrospectionCode.mjs +1 -1
  84. package/package.json +59 -25
package/LICENSE CHANGED
@@ -1,8 +1,3 @@
1
- koa-utils — Koa utility package
2
- Copyright (C) 2026 Giovanni Manzoni
3
-
4
-
5
-
6
1
  GNU GENERAL PUBLIC LICENSE
7
2
  Version 3, 29 June 2007
8
3
  Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
package/README.md CHANGED
@@ -1,5 +1,8 @@
1
1
  # @axiumine/koa-utils
2
2
 
3
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/Axiumine/koa-utils/badge)](https://scorecard.dev/viewer/?uri=github.com/Axiumine/koa-utils)
4
+ [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/16094/badge)](https://www.bestpractices.dev/projects/16094)
5
+
3
6
  TypeScript utility library for Koa + GraphQL backends. Ships authentication middleware, GraphQL error helpers, data-source connectors (MongoDB, MariaDB, PostgreSQL, Redis), file upload pipeline (ClamAV + sharp re-encode), and transactional email via SocketLabs.
4
7
 
5
8
  - **Module format:** ESM only (`.mjs` + `.d.mts`)
@@ -7,6 +10,7 @@ TypeScript utility library for Koa + GraphQL backends. Ships authentication midd
7
10
  - **TypeScript:** `6.0`
8
11
  - **License:** GPL-3.0-or-later
9
12
  - **Maintainer:** [Giovanni Manzoni](https://www.giovannimanzoni.com)
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)
10
14
 
11
15
  ## Install
12
16
 
@@ -43,6 +47,39 @@ The remaining twelve are declared **optional** in `peerDependenciesMeta`. There
43
47
 
44
48
  Optionality is a promise about the load path, not a way to silence the warning: it holds only while the dependency stays behind a subpath the consumer opts into. Adding a root `"."` barrel, or importing one of these from a module that every subpath reaches, breaks it for every consumer at once.
45
49
 
50
+ ## Quick start
51
+
52
+ A Koa app that refuses every request without a valid access token and answers with the caller's id. It needs a MongoDB and a Redis server you can reach.
53
+
54
+ ```bash
55
+ yarn add @axiumine/koa-utils @node-rs/bcrypt @sentry/node dotenv graphql mongoose redis uuid koa
56
+ printf 'MONGODB_URI=mongodb://localhost:27017/app\nREDIS_URL=redis://localhost:6379\nREDIS_KEY=app:\n' > .env
57
+ ```
58
+
59
+ Save this as `server.mts`:
60
+
61
+ ```ts
62
+ import 'dotenv/config'
63
+ import Koa from 'koa'
64
+ import { MongoDBConnect } from '@axiumine/koa-utils/dataSources/MongoDB'
65
+ import { RedisConnect } from '@axiumine/koa-utils/dataSources/Redis'
66
+ import { tdwKoaErrorHandler } from '@axiumine/koa-utils/koa/tdwKoaErrorHandler'
67
+ import { authenticatedResourceHandler } from '@axiumine/koa-utils/koa/middleware/authenticatedResourceHandler'
68
+
69
+ await MongoDBConnect()
70
+ await RedisConnect()
71
+
72
+ const app = new Koa()
73
+ app.use(tdwKoaErrorHandler)
74
+ app.use(authenticatedResourceHandler())
75
+ app.use(async (ctx) => {
76
+ ctx.body = { userId: String(ctx.state.user.id) }
77
+ })
78
+ app.listen(3000)
79
+ ```
80
+
81
+ Run it with `node server.mts` (an ES module project, `"type": "module"`, Node `^24.14.0`, which strips the types itself). `curl -i localhost:3000` answers `412 Precondition Failed` ("No authorization header."): a request needs `Authorization: Bearer access:<uuid>` with a token that exists in Redis. To obtain one, add the `signUp` and `loginRememberme` mutations from [Usage](#usage) to your GraphQL schema and follow the [Auth flow](#auth-flow).
82
+
46
83
  ## Usage
47
84
 
48
85
  No barrel — import each helper from its explicit subpath.
@@ -69,7 +106,10 @@ import { authenticatedResourceHandler } from '@axiumine/koa-utils/koa/middleware
69
106
  import { authenticatedAuthorizationHandler } from '@axiumine/koa-utils/koa/middleware/authenticatedAuthorizationHandler'
70
107
 
71
108
  const app = new Koa()
72
- const keys = new Keygrip([process.env.COOKIE_KEY!])
109
+ // Keygrip signs with HMAC-SHA1 unless told otherwise: pass 'sha256'.
110
+ // Koa signs the refresh cookie with app.keys, so verify with that same instance.
111
+ const keys = new Keygrip([process.env.COOKIE_KEY!], 'sha256')
112
+ app.keys = keys
73
113
 
74
114
  app.use(tdwKoaErrorHandler)
75
115
  app.use(authenticatedResourceHandler()) // resource endpoints
@@ -126,7 +166,7 @@ const verify = createVerifyEmailFlow({
126
166
  router.get('/check/verify-email/:email/:hash', verify.routerVerifyEmail())
127
167
  ```
128
168
 
129
- Every `paths` key is optional and falls back to the `UserBase` layout, so the package-level exports are exactly these factories with no overrides. See [docs/code/lib-access.md](./docs/code/lib-access.md).
169
+ Every `paths` key is optional and falls back to the `UserBase` layout, so the package-level exports are exactly these factories with no overrides. See [docs/code/lib-access.md](https://github.com/Axiumine/koa-utils/blob/main/docs/code/lib-access.md).
130
170
 
131
171
  `onAbandon` decides what the two disposal guards — the fifth wrong hash and a link older than 3 days — do to a pending registration. The default `'delete'` removes the row; use `'soft-delete'` or `'keep'` when other collections depend on it, since mongo has no cascade, or pass `deleteUserByEmail` to replace the writer outright. The link is rejected either way.
132
172
 
@@ -258,7 +298,11 @@ For the cluster path the `rediss://` scheme on `rootNodes` is not enough on its
258
298
  yarn install
259
299
  yarn build # ESM only — production output
260
300
  yarn build:all # ESM + CJS dual output
301
+ yarn test # build + build:tests + mocha, no coverage gate
302
+ yarn test:coverage # same under c8: fails below 100% on lines, statements, functions or branches of any file
261
303
  yarn lint # eslint --fix + prettier --write
304
+ yarn lint:check # eslint + prettier --check, writes nothing
305
+ yarn check:static # every static gate: caps, lint, typecheck (src, scripts, specs), knip, type-coverage, fta (runs in CI)
262
306
  yarn clean
263
307
  ```
264
308
 
@@ -276,6 +320,14 @@ There is no barrel and no `main` / `module` field.
276
320
 
277
321
  Maintainers who install through a private npm mirror should not commit its host: a git clean/smudge filter rewrites the `resolved` URLs in both directions, keeping the mirror in the working copy and the public registry in history. `yarn install` configures it (via `prepare` → `hooks:install`); point it at your own mirror with `YARN_PROXY_REGISTRY`. A pre-commit check rejects any lockfile that still names a non-public host.
278
322
 
323
+ ## Feedback, contributing and security
324
+
325
+ - **Bugs and feature requests:** open an issue at <https://github.com/Axiumine/koa-utils/issues/new/choose>. Issues are public and searchable.
326
+ - **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).
327
+ - **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.
328
+ - **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).
329
+ - **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.
330
+
279
331
  ## Repository
280
332
 
281
333
  <https://github.com/Axiumine/koa-utils>
@@ -2,8 +2,8 @@ import * as Sentry from '@sentry/node';
2
2
  import * as dotenv from 'dotenv';
3
3
  import { Sequelize } from 'sequelize-typescript';
4
4
  dotenv.config();
5
- export const sequelize = new Sequelize(`${process.env.MARIADB_DBNAME}`, `${process.env.MARIADB_USER}`, `${process.env.MARIADB_PWD}`, {
6
- host: `${process.env.MARIADB_IP}`,
5
+ export const sequelize = new Sequelize(`${process.env['MARIADB_DBNAME']}`, `${process.env['MARIADB_USER']}`, `${process.env['MARIADB_PWD']}`, {
6
+ host: `${process.env['MARIADB_IP']}`,
7
7
  dialect: 'mariadb',
8
8
  query: { raw: true },
9
9
  pool: {
@@ -24,17 +24,19 @@ export const sequelize = new Sequelize(`${process.env.MARIADB_DBNAME}`, `${proce
24
24
  backoffExponent: 1.1,
25
25
  timeout: 3000,
26
26
  backoffJitter: 0.1, // Add this required property
27
- max: parseInt(`${process.env.MARIADB_RETRY}`) || 5
27
+ max: parseInt(`${process.env['MARIADB_RETRY']}`) || 5
28
28
  },
29
29
  dialectOptions: {
30
30
  useUTC: true,
31
31
  skipSetTimezone: true,
32
32
  compress: true,
33
- requestTimeout: parseInt(`${process.env.MARIADB_TIMEOUT}`) || 5000
33
+ requestTimeout: parseInt(`${process.env['MARIADB_TIMEOUT']}`) || 5000
34
34
  },
35
- port: parseInt(`${process.env.MARIADB_PORT}`, 10),
35
+ port: parseInt(`${process.env['MARIADB_PORT']}`, 10),
36
+ // Explicit `undefined` is load-bearing: Sequelize reads the key with hasOwnProperty, so omitting it would switch
37
+ // query logging on. The cast only satisfies exactOptionalPropertyTypes (tsconfig.check.json); runtime is unchanged.
36
38
  /* c8 ignore next -- env-dependent boot config; covered only when MARIADB_LOGGING='false' */
37
- logging: process.env.MARIADB_LOGGING === 'false' ? false : undefined // disable print queries in console
39
+ logging: (process.env['MARIADB_LOGGING'] === 'false' ? false : undefined) // disable print queries in console
38
40
  });
39
41
  // Setting up a connection
40
42
  export const MariaDBConnect = async () => {
@@ -24,7 +24,7 @@ export async function MongoDBConnect() {
24
24
  };
25
25
  mongoose.set('sanitizeFilter', true);
26
26
  mongoose.set('strictQuery', false); // will be done in mongose 7
27
- await mongoose.connect(`${process.env.MONGODB_URI}`, options);
27
+ await mongoose.connect(`${process.env['MONGODB_URI']}`, options);
28
28
  /* c8 ignore next 2 -- success log + closing brace; covered only with live MongoDB */
29
29
  console.info('[MongoDB] OK: MongoDB connection has been established successfully. ');
30
30
  }
@@ -4,20 +4,20 @@ import pg from 'pg';
4
4
  const { Client, Pool } = pg;
5
5
  dotenv.config();
6
6
  export const pgClient = new Client({
7
- user: `${process.env.POSTGRESQL_USER}`,
8
- password: `${process.env.POSTGRESQL_PWD}`,
9
- host: `${process.env.POSTGRESQL_HOST}`,
10
- port: parseInt(`${process.env.POSTGRESQL_PORT}`, 10),
11
- database: `${process.env.POSTGRESQL_DBNAME}`
7
+ user: `${process.env['POSTGRESQL_USER']}`,
8
+ password: `${process.env['POSTGRESQL_PWD']}`,
9
+ host: `${process.env['POSTGRESQL_HOST']}`,
10
+ port: parseInt(`${process.env['POSTGRESQL_PORT']}`, 10),
11
+ database: `${process.env['POSTGRESQL_DBNAME']}`
12
12
  });
13
13
  export const pgPool = new Pool({
14
- user: `${process.env.POSTGRESQL_USER}`,
15
- password: `${process.env.POSTGRESQL_PWD}`,
16
- host: `${process.env.POSTGRESQL_HOST}`,
17
- port: parseInt(`${process.env.POSTGRESQL_PORT}`, 10),
18
- database: `${process.env.POSTGRESQL_DBNAME}`,
19
- max: parseInt(`${process.env.POSTGRESQL_POOL_MAX}`, 10),
20
- idleTimeoutMillis: parseInt(`${process.env.POSTGRESQL_IDLE_TIMEOUT}`, 10)
14
+ user: `${process.env['POSTGRESQL_USER']}`,
15
+ password: `${process.env['POSTGRESQL_PWD']}`,
16
+ host: `${process.env['POSTGRESQL_HOST']}`,
17
+ port: parseInt(`${process.env['POSTGRESQL_PORT']}`, 10),
18
+ database: `${process.env['POSTGRESQL_DBNAME']}`,
19
+ max: parseInt(`${process.env['POSTGRESQL_POOL_MAX']}`, 10),
20
+ idleTimeoutMillis: parseInt(`${process.env['POSTGRESQL_IDLE_TIMEOUT']}`, 10)
21
21
  });
22
22
  // the pool will emit an error on behalf of any idle clients
23
23
  // it contains if a backend error or network partition happens
@@ -5,17 +5,18 @@ import * as Sentry from '@sentry/node';
5
5
  import * as dotenv from 'dotenv';
6
6
  import { createClient, createCluster } from 'redis';
7
7
  dotenv.config();
8
- export const redisClient = process.env.REDIS_IS_CLUSTER === '1'
8
+ export const redisClient = process.env['REDIS_IS_CLUSTER'] === '1'
9
9
  ? /* c8 ignore start -- cluster branch: requires REDIS_IS_CLUSTER=1 + 3 redis nodes, not in unit env */
10
10
  createCluster({
11
11
  rootNodes: [
12
- { url: redisNodeUrl(process.env.REDIS_DB1_HOST, process.env.REDIS_DB1_PORT) },
13
- { url: redisNodeUrl(process.env.REDIS_DB2_HOST, process.env.REDIS_DB2_PORT) },
14
- { url: redisNodeUrl(process.env.REDIS_DB3_HOST, process.env.REDIS_DB3_PORT) }
12
+ { url: redisNodeUrl(process.env['REDIS_DB1_HOST'], process.env['REDIS_DB1_PORT']) },
13
+ { url: redisNodeUrl(process.env['REDIS_DB2_HOST'], process.env['REDIS_DB2_PORT']) },
14
+ { url: redisNodeUrl(process.env['REDIS_DB3_HOST'], process.env['REDIS_DB3_PORT']) }
15
15
  ],
16
16
  defaults: {
17
- username: process.env.REDIS_USERNAME,
18
- password: process.env.REDIS_PASSWORD,
17
+ // casts only satisfy exactOptionalPropertyTypes (tsconfig.check.json); an unset var still reaches node-redis as undefined
18
+ username: process.env['REDIS_USERNAME'],
19
+ password: process.env['REDIS_PASSWORD'],
19
20
  // rootNodes only carry the topology-discovery connections; node-redis does not inherit their
20
21
  // TLS setting for the connections it then opens to the discovered nodes. Without this the
21
22
  // rediss:// scheme above would be a no-op and every real cluster connection would stay
@@ -24,7 +25,7 @@ export const redisClient = process.env.REDIS_IS_CLUSTER === '1'
24
25
  }
25
26
  })
26
27
  : /* c8 ignore stop */
27
- createClient({ url: resolveRedisUrl(process.env.REDIS_URL) });
28
+ createClient({ url: resolveRedisUrl(process.env['REDIS_URL']) }); // cast: see the cluster branch above
28
29
  export const RedisConnect = async () => {
29
30
  console.info('[Redis] Try connect to database... ');
30
31
  redisClient.on('error', (e) => {
@@ -6,7 +6,6 @@ interface IUserInfo {
6
6
  };
7
7
  }
8
8
  export declare class SocketLabsLib {
9
- private StringObj;
10
9
  private readonly platformName;
11
10
  private readonly linkBase;
12
11
  private readonly emailFrom;
@@ -134,17 +133,5 @@ SendResponse {
134
133
  getHtmlHeader(title: string): string;
135
134
  getHtmlFooter(): string;
136
135
  private sendTemplate;
137
- private sendEmail;
138
- /**
139
- * fallback header
140
- * @private
141
- */
142
- private htmlHeader1;
143
- /**
144
- * fallback header
145
- * @private
146
- */
147
- private htmlHeader2;
148
- private fixName;
149
136
  }
150
137
  export {};
@@ -1,15 +1,19 @@
1
- import { StringLib } from "../lib/StringLib.mjs";
1
+ import * as account from "../private/email/accountMessages.mjs";
2
+ import { escapeHtml } from "../private/email/escapeHtml.mjs";
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";
5
+ import * as notice from "../private/email/noticeMessages.mjs";
6
+ import { orFalse } from "../private/email/orFalse.mjs";
7
+ import * as reset from "../private/email/resetMessages.mjs";
2
8
  import * as Sentry from '@sentry/node';
3
9
  import { BasicMessage, SocketLabsClient } from '@socketlabs/email';
4
- import { throwInternalError } from "../graphQL/throw/throwInternalError.mjs";
5
10
  import * as dotenv from 'dotenv';
6
11
  dotenv.config();
7
12
  export class SocketLabsLib {
8
- StringObj;
9
13
  platformName;
10
14
  linkBase;
11
15
  emailFrom;
12
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
16
+ // 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
13
17
  client;
14
18
  emailHtmlHeader1;
15
19
  emailHtmlHeader2;
@@ -17,14 +21,13 @@ export class SocketLabsLib {
17
21
  constructor(htmlHeader1 = '', htmlHeader2 = '', htmlFooter = '') {
18
22
  this.client = new SocketLabsClient(
19
23
  /* c8 ignore next -- env fallback '0' covered only when SOCKETLABS_SERVER_ID is unset */
20
- parseInt(process.env.SOCKETLABS_SERVER_ID || '0'), `${process.env.SOCKETLABS_SERVER_APIKEY}`, { requestTimeout: 120, numberOfRetries: 3 });
21
- this.StringObj = new StringLib();
22
- this.platformName = `${process.env.PLATFORM_NAME}`;
23
- this.linkBase = `${process.env.APP_DOMAIN}`;
24
- this.emailFrom = `${process.env.EMAIL_FROM}`;
25
- this.emailHtmlHeader1 = htmlHeader1 === '' ? this.htmlHeader1() : htmlHeader1;
26
- this.emailHtmlHeader2 = htmlHeader2 === '' ? this.htmlHeader2() : htmlHeader2;
27
- this.emailHtmlFooter = htmlFooter === '' ? this.htmlFooter() : htmlFooter;
24
+ parseInt(process.env['SOCKETLABS_SERVER_ID'] || '0'), `${process.env['SOCKETLABS_SERVER_APIKEY']}`, { requestTimeout: 120, numberOfRetries: 3 });
25
+ this.platformName = `${process.env['PLATFORM_NAME']}`;
26
+ this.linkBase = `${process.env['APP_DOMAIN']}`;
27
+ this.emailFrom = `${process.env['EMAIL_FROM']}`;
28
+ this.emailHtmlHeader1 = orFallback(htmlHeader1, FALLBACK_HEADER_1);
29
+ this.emailHtmlHeader2 = orFallback(htmlHeader2, FALLBACK_HEADER_2);
30
+ this.emailHtmlFooter = orFallback(htmlFooter, FALLBACK_FOOTER);
28
31
  }
29
32
  /**
30
33
  * Send the registration confirmation link.
@@ -47,20 +50,10 @@ export class SocketLabsLib {
47
50
  * @param linkBase scheme + host the link points at; defaults to `APP_DOMAIN`
48
51
  * @param linkPath route prefix the receiving service listens on; defaults to `/check/verify-email`
49
52
  */
53
+ // eslint-disable-next-line max-params -- public signature, an options object would break consumers
50
54
  async sendEmailVerify(emailTo, hash, name = '', linkBase = this.linkBase, linkPath = '/check/verify-email') {
51
- const subject = `Confirm your email for ${this.platformName}`;
52
- const encodedEmail = encodeURI(emailTo);
53
- const nameFixed = this.fixName(name);
54
- const base = linkBase.replace(/\/+$/, '');
55
- const path = `/${linkPath.replace(/^\/+/, '')}`;
56
- const link = `${base}${path}/${encodedEmail}/${hash}`;
57
- const linkHtml = this.StringObj.makeLink(link);
58
- const messageTxt = `Hi${nameFixed}, you or someone else is registering you on ${this.platformName}.
59
- You can confirm the registration by copying this link ${link} into your browser. The Team`;
60
- const messageHtml = `Hi${nameFixed},<br>you or someone else is registering you on ${this.platformName}.<br><br>
61
- You can confirm the registration by visiting this link ${linkHtml}<br><br>
62
- <br><br>The Team`;
63
- return await this.sendTemplate(emailTo, subject, messageTxt, messageHtml);
55
+ const link = confirmationLink(linkBase, linkPath, emailTo, hash);
56
+ return await this.sendTemplate(emailTo, account.verifyMessage(this.platformName, link, name));
64
57
  }
65
58
  /*
66
59
  async sendEmailPostReported(userInfo, idPost) {
@@ -118,53 +111,32 @@ SendResponse {
118
111
  }
119
112
  */
120
113
  async sendEmailChangeVerify(emailTo, hash, name = '') {
121
- const encodedEmail = encodeURI(emailTo);
122
- const subject = `Confirm your email for ${this.platformName}`;
123
- const nameFixed = this.fixName(name);
124
- const link = `${this.linkBase}/check/verify-change-email/${encodedEmail}/${hash}`;
125
- const linkHtml = this.StringObj.makeLink(link);
126
- const messageTxt = `Hi${nameFixed}, you or someone else has changed the email you sign in with.
127
- You can confirm by copying this link ${link} into your browser. The Team.`;
128
- const messageHtml = `Hi${nameFixed},<br>you or someone else has changed the email you sign in with.<br><br>
129
- You can confirm the registration by visiting this link ${linkHtml}
130
- <br><br>The Team.`;
131
- return await this.sendTemplate(emailTo, subject, messageTxt, messageHtml);
114
+ const link = `${this.linkBase}/check/verify-change-email/${encodeURI(emailTo)}/${hash}`;
115
+ return await this.sendTemplate(emailTo, account.changeVerifyMessage(this.platformName, link, name));
132
116
  }
133
117
  async sendWelcome(emailTo) {
134
- const subject = `Welcome to ${this.platformName}`;
135
- const linkHtml = this.StringObj.makeLink(this.linkBase, this.platformName);
136
- const messageTxt = `Welcome to ${this.platformName}`;
137
- const messageHtml = `Welcome to ${linkHtml}`;
138
- return await this.sendTemplate(emailTo, subject, messageTxt, messageHtml);
118
+ return await this.sendTemplate(emailTo, account.welcomeMessage(this.platformName, this.linkBase));
139
119
  }
140
120
  /**
141
121
  * Send account disabled notification
142
122
  * @param emailTo
143
123
  */
144
124
  async accountDisabled(emailTo) {
145
- const subject = 'Your account has been disabled';
146
- const textBody = 'Hi, we are sorry but your account has been disabled. Contact us for more information.';
147
- const htmlBody = `<p>${textBody}</p>`;
148
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
125
+ return await this.sendTemplate(emailTo, notice.ACCOUNT_DISABLED);
149
126
  }
150
127
  /**
151
128
  * Send account disabled notification
152
129
  * @param emailTo
153
130
  */
154
131
  async accountBanned(emailTo) {
155
- const subject = 'Your account has been banned';
156
- const textBody = 'Hi, we are sorry but your account has been banned. Contact us for more information.';
157
- const htmlBody = `<p>${textBody}</p>`;
158
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
132
+ return await this.sendTemplate(emailTo, notice.ACCOUNT_BANNED);
159
133
  }
160
134
  /**
161
135
  * alertDevTeam
162
136
  * @param err
163
137
  */
164
138
  async alertDevTeam(err) {
165
- const textBody = 'error 500 ' + err;
166
- const htmlBody = '<p>error 500 <br><br>' + err + '</p>';
167
- return await this.sendTemplate(`${process.env.DEV_TEAM_EMAIL}`, `${this.platformName} error 500`, textBody, htmlBody);
139
+ return await this.sendTemplate(`${process.env['DEV_TEAM_EMAIL']}`, notice.alertDevMessage(this.platformName, err));
168
140
  }
169
141
  /**
170
142
  *
@@ -172,13 +144,7 @@ SendResponse {
172
144
  * @param times
173
145
  */
174
146
  async wrongHash(emailTo, times) {
175
- if (times > 5)
176
- throwInternalError();
177
- const remainingTimes = 5 - times;
178
- const subject = 'Wrong activation link';
179
- const textBody = `Hi, you or someone else is trying to verify your email with a wrong link. You have ${remainingTimes} attempts remaining.`;
180
- const htmlBody = `<p>${textBody}</p>`;
181
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
147
+ return await this.sendTemplate(emailTo, notice.wrongHashMessage(times));
182
148
  }
183
149
  /*****************
184
150
  * Too much verify requests
@@ -186,30 +152,21 @@ SendResponse {
186
152
  * @returns {Promise<string|null>}
187
153
  */
188
154
  async tooMuchVerifyRequests(emailTo) {
189
- const subject = 'Too many attempts to verify your email';
190
- const textBody = 'Hi, you have made more than 5 attempts to verify your email. You need to repeat the registration request.';
191
- const htmlBody = '<p>Hi, you have made 5 or more attempts to verify your email. You need to repeat the registration request.</p>';
192
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
155
+ return await this.sendTemplate(emailTo, notice.TOO_MUCH_VERIFY_REQUESTS);
193
156
  }
194
157
  /*****************
195
158
  * @param emailTo
196
159
  * @returns {Promise<string|null>}
197
160
  */
198
161
  async hashReqTooOld(emailTo) {
199
- const subject = 'Activation link expired';
200
- const textBody = 'Hi, the activation link you are trying to use is older than 3 days and has expired. You need to repeat the registration request.';
201
- const htmlBody = '<p>Hi, the activation link you are trying to use is older than 3 days and has expired. You need to repeat the registration request.</p>';
202
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
162
+ return await this.sendTemplate(emailTo, notice.HASH_REQ_TOO_OLD);
203
163
  }
204
164
  /*****************
205
165
  * @param emailTo
206
166
  * @returns {Promise<string|null>}
207
167
  */
208
168
  async emailAlreadyValid(emailTo) {
209
- const subject = 'Account already valid';
210
- const textBody = 'Hi, your account is already valid, you can log in.';
211
- const htmlBody = `<p>${textBody}</p>`;
212
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
169
+ return await this.sendTemplate(emailTo, notice.EMAIL_ALREADY_VALID);
213
170
  }
214
171
  /**
215
172
  * Send subscription email
@@ -217,44 +174,14 @@ SendResponse {
217
174
  * @param otp
218
175
  */
219
176
  async sendSubscriptionEmail(emailTo, otp) {
220
- const subject = `Activate your ${this.platformName} account`;
221
- const url = `${this.linkBase}/x/emailVerify`;
222
- const urlHtml = this.StringObj.makeLink(url);
223
- const linkHomeHtml = this.StringObj.makeLink(this.linkBase, this.platformName);
224
- const textBody = `To confirm your subscription on ${this.platformName}, open the following link in your browser
225
- ${url} and enter the following activation code: ${otp}`;
226
- const htmlBody = `<p>To confirm your subscription on ${linkHomeHtml}, open the following link in your browser
227
- ${urlHtml} and enter the following activation code: ${otp}</p>`;
228
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
177
+ return await this.sendTemplate(emailTo, account.subscriptionMessage(this.platformName, this.linkBase, otp));
229
178
  }
230
179
  async sendResetPwdConfirmation(emailTo, name = '') {
231
- const subject = `Password reset for ${this.platformName}`;
232
- const link = this.linkBase;
233
- const linkHtml = this.StringObj.makeLink(link, this.platformName);
234
- const nameFixed = this.fixName(name);
235
- const textBody = `Hi${nameFixed}, you have confirmed your new password. You can now log in at: ${link}. The Team.`;
236
- const htmlBody = `Hi${nameFixed},<br>you have confirmed your new password.<br><br>You can now log in at:<br>${linkHtml}<br><br>The Team.`;
237
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
180
+ return await this.sendTemplate(emailTo, reset.resetConfirmationMessage(this.platformName, this.linkBase, name));
238
181
  }
239
182
  async sendResetPwdConfirmationHash(email, name, hash) {
240
- const encodedEmail = encodeURI(email);
241
- const subject = `Password change confirmation for ${this.platformName}`;
242
- const linkReset = this.linkBase + '/index.php?q=reset&hash=' + hash + '&email=' + encodedEmail;
243
- const textBody = 'Hi ' + name + ', you have confirmed your new password. You can now log in at: ' + this.linkBase + ' . ';
244
- const htmlBody = this.getHtmlHeader(subject) +
245
- 'Hi ' +
246
- name +
247
- ',<br>you have confirmed your new password.<br><br>You can now log in at:<br> ' +
248
- this.StringObj.makeLink(linkReset) +
249
- '<br><br>The Team' +
250
- this.getHtmlFooter();
251
- try {
252
- return await this.sendTemplate(email, subject, textBody, htmlBody);
253
- }
254
- catch (e) {
255
- Sentry.captureException(e);
256
- return false;
257
- }
183
+ const content = reset.resetConfirmationHashMessage(this.platformName, this.linkBase, { email, name, hash });
184
+ return await orFalse(() => this.sendTemplate(email, content));
258
185
  }
259
186
  /**
260
187
  * Send the password-reset link.
@@ -275,26 +202,16 @@ SendResponse {
275
202
  * @param linkBase scheme + host the link points at; defaults to `APP_DOMAIN`
276
203
  * @param linkPath front-end route prefix that renders the new-password form; defaults to `/x/reset`
277
204
  */
205
+ // eslint-disable-next-line max-params -- public signature, an options object would break consumers
278
206
  async sendEmailReset(emailTo, hash, name = '', linkBase = this.linkBase, linkPath = '/x/reset') {
279
- const subject = `Password reset for ${this.platformName}`;
280
- const encodedEmail = encodeURI(emailTo);
281
- const base = linkBase.replace(/\/+$/, '');
282
- const path = `/${linkPath.replace(/^\/+/, '')}`;
283
- const link = `${base}${path}/${encodedEmail}/${hash}`;
284
- const linkHtml = this.StringObj.makeLink(link);
285
- const nameFixed = this.fixName(name);
286
- const textBody = `Hi${nameFixed}, you or someone else has requested a password reset. You can change your login password
287
- by copying this link ${link} into your browser. The Team.`;
288
- const htmlBody = `Hi${nameFixed},<br>you or someone else has requested a password reset.<br><br>
289
- You can change your password by clicking the link:<br>${linkHtml}
290
- <br><br>The Team.`;
291
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
207
+ const link = confirmationLink(linkBase, linkPath, emailTo, hash);
208
+ return await this.sendTemplate(emailTo, reset.resetMessage(this.platformName, link, name));
292
209
  }
293
210
  /**
294
211
  * fallback footer
295
212
  */
296
213
  htmlFooter() {
297
- return '</p></td>' + ' </tr>' + ' </table>' + '</body>';
214
+ return FALLBACK_FOOTER;
298
215
  }
299
216
  /**
300
217
  * send OTP
@@ -302,77 +219,28 @@ SendResponse {
302
219
  * @param otp
303
220
  */
304
221
  async sendOTP(emailTo, otp) {
305
- const subject = `OTP code for ${this.platformName}`;
306
- const textBody = `To confirm your subscription on ${this.platformName}, enter the following OTP code: ${otp}`;
307
- const htmlBody = `<p>To confirm your subscription on ${this.platformName}, enter the following OTP code: ${otp}</p>`;
308
- try {
309
- return await this.sendTemplate(emailTo, subject, textBody, htmlBody);
310
- }
311
- catch (e) {
312
- Sentry.captureException(e);
313
- return false;
314
- }
222
+ const content = account.otpMessage(this.platformName, otp);
223
+ return await orFalse(() => this.sendTemplate(emailTo, content));
315
224
  }
316
225
  async sendEmailPostReported(userInfo, idPost) {
317
- const subject = 'Post ' + idPost + ' reported';
318
- const messageTxt = 'Hi, post ' +
319
- idPost +
320
- ' has been reported by ' +
321
- userInfo.personalData.name +
322
- ' ' +
323
- userInfo.personalData.surname +
324
- ' (id: ' +
325
- userInfo._id +
326
- ').';
327
- const messageHtml = this.getHtmlHeader(subject) +
328
- 'Hi, post ' +
329
- idPost +
330
- ' has been reported by ' +
331
- userInfo.personalData.name +
332
- ' ' +
333
- userInfo.personalData.surname +
334
- ' (id: ' +
335
- userInfo._id +
336
- ').' +
337
- this.getHtmlFooter();
338
- return await this.sendTemplate(`${process.env.DEV_TEAM_EMAIL}`, subject, messageTxt, messageHtml);
226
+ const { name, surname } = userInfo.personalData;
227
+ const content = notice.postReportedMessage(idPost, name, surname, userInfo._id);
228
+ return await this.sendTemplate(`${process.env['DEV_TEAM_EMAIL']}`, content);
339
229
  }
340
230
  getHtmlHeader(title) {
341
- return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' +
342
- '<html xmlns="http://www.w3.org/1999/xhtml">' +
343
- ' <head>' +
344
- ' <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
345
- ' <title>' +
346
- title +
347
- '</title>' +
348
- ' <meta name="viewport" content="width=device-width, initial-scale=1.0"/>' +
349
- '</head>' +
350
- '</html>' +
351
- '<body style="margin: 0; padding: 0;">' +
352
- ' <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">' +
353
- ' <tr>' +
354
- ' <td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;"><p style="color: #000000; font-family: Verdana, sans-serif; font-size: 12pt;">');
231
+ return standaloneHeader(title);
355
232
  }
356
233
  getHtmlFooter() {
357
- return '</p></td>' + ' </tr>' + ' </table>' + '</body>';
358
- }
359
- async sendTemplate(emailTo, subject, textBody, htmlBody) {
360
- return await this.sendEmail({
361
- emailFrom: this.emailFrom,
362
- emailFromName: this.platformName,
363
- emailTo,
364
- subject,
365
- textBody,
366
- htmlBody
367
- });
234
+ return FALLBACK_FOOTER;
368
235
  }
369
- async sendEmail(args) {
370
- const { emailFrom, emailFromName, emailTo, subject, textBody, htmlBody } = args;
236
+ async sendTemplate(emailTo, content) {
237
+ const { subject, textBody, htmlBody } = content;
371
238
  const basicMessage = new BasicMessage();
372
- basicMessage.setFromAddress(emailFrom, emailFromName);
239
+ basicMessage.setFromAddress(this.emailFrom, this.platformName);
373
240
  basicMessage.setSubject(subject);
374
241
  basicMessage.setTextBody(textBody);
375
- basicMessage.setHtmlBody(this.emailHtmlHeader1 + subject + this.emailHtmlHeader2 + htmlBody + this.emailHtmlFooter);
242
+ // The subject is plain text for the subject line and the text part, so only its copy placed in the HTML is escaped.
243
+ basicMessage.setHtmlBody(this.emailHtmlHeader1 + escapeHtml(subject) + this.emailHtmlHeader2 + htmlBody + this.emailHtmlFooter);
376
244
  basicMessage.setTo(emailTo);
377
245
  return this.client.send(basicMessage).then(() => {
378
246
  //Handle successful API call
@@ -384,33 +252,5 @@ SendResponse {
384
252
  return false;
385
253
  });
386
254
  }
387
- /**
388
- * fallback header
389
- * @private
390
- */
391
- htmlHeader1() {
392
- return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' +
393
- '<html lang="en" xmlns="http://www.w3.org/1999/xhtml">' +
394
- ' <head>' +
395
- ' <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' +
396
- ' <title>');
397
- }
398
- /**
399
- * fallback header
400
- * @private
401
- */
402
- htmlHeader2() {
403
- return ('</title>' +
404
- ' <meta name="viewport" content="width=device-width, initial-scale=1.0"/>' +
405
- '</head>' +
406
- '</html>' +
407
- '<body style="margin: 0; padding: 0;">' +
408
- ' <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">' +
409
- ' <tr>' +
410
- ' <td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;"><p style="color: #000000; font-family: Verdana, sans-serif; font-size: 12pt;">');
411
- }
412
- fixName(name) {
413
- return name !== '' ? ` ${name}` : '';
414
- }
415
255
  }
416
256
  //# sourceMappingURL=SocketLabsLib.mjs.map