@axiumine/koa-utils 7.1.1 → 8.0.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.
Files changed (72) hide show
  1. package/README.md +39 -14
  2. package/dist/dataSources/MariaDB.mjs +3 -3
  3. package/dist/dataSources/MongoDB.mjs +2 -2
  4. package/dist/dataSources/PostgreSQL.mjs +3 -3
  5. package/dist/dataSources/Redis.mjs +3 -3
  6. package/dist/email/ISocketLabsClient.d.mts +8 -0
  7. package/dist/email/ISocketLabsClient.mjs +2 -0
  8. package/dist/email/ISocketLabsMessage.d.mts +20 -0
  9. package/dist/email/ISocketLabsMessage.mjs +4 -0
  10. package/dist/email/ISocketLabsSendResult.d.mts +12 -0
  11. package/dist/email/ISocketLabsSendResult.mjs +2 -0
  12. package/dist/email/ISocketLabsSenderOptions.d.mts +30 -0
  13. package/dist/email/ISocketLabsSenderOptions.mjs +3 -0
  14. package/dist/email/SocketLabsLib.d.mts +7 -2
  15. package/dist/email/SocketLabsLib.mjs +38 -25
  16. package/dist/email/createSocketLabsSender.d.mts +20 -0
  17. package/dist/email/createSocketLabsSender.mjs +66 -0
  18. package/dist/files/scanVirus.mjs +1 -1
  19. package/dist/files/storeUploadAsTemp.mjs +2 -2
  20. package/dist/graphQL/schema/mutations/login4Ever.mjs +1 -1
  21. package/dist/graphQL/schema/mutations/loginAdmin.mjs +1 -1
  22. package/dist/graphQL/schema/mutations/loginRememberme.mjs +1 -1
  23. package/dist/graphQL/schema/mutations/logout.mjs +3 -3
  24. package/dist/graphQL/schema/mutations/refresh.mjs +3 -3
  25. package/dist/graphQL/schema/mutations/resetPwd.mjs +1 -1
  26. package/dist/graphQL/schema/mutations/updatePassword.mjs +1 -1
  27. package/dist/koa/IKoaErrorHandlerContext.d.mts +11 -0
  28. package/dist/koa/IKoaErrorHandlerContext.mjs +2 -0
  29. package/dist/koa/IKoaErrorHandlerOptions.d.mts +28 -0
  30. package/dist/koa/IKoaErrorHandlerOptions.mjs +3 -0
  31. package/dist/koa/createKoaErrorHandler.d.mts +11 -0
  32. package/dist/koa/createKoaErrorHandler.mjs +37 -0
  33. package/dist/koa/middleware/authenticatedAuthorizationHandler/index.mjs +2 -2
  34. package/dist/koa/middleware/authenticatedLogoutHandler/index.mjs +2 -2
  35. package/dist/koa/middleware/authenticatedResourceHandler/index.mjs +2 -2
  36. package/dist/koa/tdwKoaErrorHandler.mjs +15 -23
  37. package/dist/lib/Constants.d.mts +0 -2
  38. package/dist/lib/Constants.mjs +0 -2
  39. package/dist/lib/MongoDB/throwMongoErrors.mjs +1 -1
  40. package/dist/lib/OBJECTID_0_OBJ.d.mts +6 -0
  41. package/dist/lib/OBJECTID_0_OBJ.mjs +8 -0
  42. package/dist/lib/access/resetPwdMailer.d.mts +3 -0
  43. package/dist/lib/access/resetPwdMailer.mjs +3 -0
  44. package/dist/lib/tokenOptions.mjs +2 -2
  45. package/dist/lib/tokens.mjs +3 -2
  46. package/dist/lib/tryCatchRethrow.mjs +1 -1
  47. package/dist/private/email/accountMessages.mjs +6 -4
  48. package/dist/private/email/messageParts.d.mts +10 -1
  49. package/dist/private/email/messageParts.mjs +36 -2
  50. package/dist/private/email/orFalse.mjs +1 -1
  51. package/dist/private/email/resetMessages.mjs +7 -5
  52. package/dist/private/files/reEncode.mjs +1 -1
  53. package/dist/private/graphQL/schema/mutations/setLastLoginSQL.mjs +1 -1
  54. package/dist/private/graphQL/schema/mutations/setRedisLoginSession.mjs +3 -3
  55. package/dist/private/lib/ISentryClient.d.mts +10 -0
  56. package/dist/private/lib/ISentryClient.mjs +2 -0
  57. package/dist/private/lib/access/assertResetAllowed.mjs +1 -1
  58. package/dist/private/lib/access/db/deleteUserByEmail.mjs +1 -1
  59. package/dist/private/lib/access/db/enableEmailAccess.mjs +7 -1
  60. package/dist/private/lib/access/db/userData4VerifyEmail.mjs +1 -1
  61. package/dist/private/lib/access/handleBadDB.mjs +1 -1
  62. package/dist/private/lib/createSentryClient.d.mts +7 -0
  63. package/dist/private/lib/createSentryClient.mjs +20 -0
  64. package/dist/private/lib/importOptional.d.mts +7 -0
  65. package/dist/private/lib/importOptional.mjs +27 -0
  66. package/dist/private/lib/loadEnv.d.mts +12 -0
  67. package/dist/private/lib/loadEnv.mjs +14 -0
  68. package/dist/private/lib/sentry.d.mts +3 -0
  69. package/dist/private/lib/sentry.mjs +12 -0
  70. package/dist/private/lib/verifyIntrospectionCode.d.mts +4 -0
  71. package/dist/private/lib/verifyIntrospectionCode.mjs +7 -13
  72. package/package.json +71 -12
@@ -6,7 +6,7 @@ import { applyPasswordReset } from "../../../private/lib/access/applyPasswordRes
6
6
  import { getResetPwd } from "../../../private/lib/access/db/getResetPwd.mjs";
7
7
  import removeResetReq from "../../../private/lib/access/db/removeResetReq.mjs";
8
8
  import updatePasswordDb from "../../../private/lib/access/db/updatePasswordDb.mjs";
9
- import * as Sentry from '@sentry/node';
9
+ import * as Sentry from "../../../private/lib/sentry.mjs";
10
10
  import { GraphQLBoolean, GraphQLNonNull, GraphQLString } from 'graphql';
11
11
  import mongoose from 'mongoose';
12
12
  /**
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The part of a Koa context that {@link createKoaErrorHandler} reads and writes. Koa's `ParameterizedContext` and
3
+ * `IContextKoaErrorHandler` both fit it, so the factory needs no `koa` types and no peer at all.
4
+ */
5
+ export interface IKoaErrorHandlerContext {
6
+ status: number;
7
+ body: unknown;
8
+ app: {
9
+ emit(event: string, err: unknown, ctx: unknown): unknown;
10
+ };
11
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=IKoaErrorHandlerContext.mjs.map
@@ -0,0 +1,28 @@
1
+ import { IKoaErrorHandlerContext } from './IKoaErrorHandlerContext.mjs';
2
+ /**
3
+ * Options of {@link createKoaErrorHandler}. Every field is optional; omitted, the handler behaves like
4
+ * `tdwKoaErrorHandler` without GraphQL, Sentry or dotenv. `undefined` is accepted for each field
5
+ * (`exactOptionalPropertyTypes`), so `{ report: maybeReport }` needs no conditional spread.
6
+ */
7
+ export interface IKoaErrorHandlerOptions<TCtx extends IKoaErrorHandlerContext = IKoaErrorHandlerContext> {
8
+ /**
9
+ * HTTP status for a caught value. Default `err?.status || 500`: a missing, `0` or `NaN` status gives 500.
10
+ * A truthy status outside 100-999 makes Koa's own `ctx.status` setter assert.
11
+ */
12
+ statusOf?: ((err: unknown, ctx: TCtx) => number) | undefined;
13
+ /**
14
+ * Response body for a caught value, called after `ctx.status` is set and only when that status may carry a body.
15
+ * Default `{ message: err?.message }`. Returning `undefined` leaves `ctx.body` as it was; `null`, `''` and `0` are assigned.
16
+ */
17
+ bodyOf?: ((err: unknown, ctx: TCtx) => unknown) | undefined;
18
+ /**
19
+ * Side effect for a caught value (logging, Sentry), called after status and body and before `'error'` is emitted.
20
+ * No default. Not wrapped in `try`/`catch`: a throwing `report` rejects the middleware and skips the `emit`.
21
+ */
22
+ report?: ((err: unknown, ctx: TCtx) => void) | undefined;
23
+ /**
24
+ * Statuses that get no body (`bodyOf` is not called). Default `[100, 101, 102, 204, 205, 304]`. Copied into a `Set`
25
+ * when the handler is created, so changing the array afterwards has no effect. `[]` allows a body for every status.
26
+ */
27
+ noBodyStatuses?: readonly number[] | undefined;
28
+ }
@@ -0,0 +1,3 @@
1
+ export {};
2
+ /* eslint-enable sonarjs/no-redundant-optional -- end of the exactOptionalPropertyTypes block above */
3
+ //# sourceMappingURL=IKoaErrorHandlerOptions.mjs.map
@@ -0,0 +1,11 @@
1
+ import { IKoaErrorHandlerContext } from './IKoaErrorHandlerContext.mjs';
2
+ import { IKoaErrorHandlerOptions } from './IKoaErrorHandlerOptions.mjs';
3
+ /**
4
+ * Builds a Koa error middleware: `await next()` in a `try`, and on a throw sets `ctx.status`, sets `ctx.body`, calls
5
+ * `report`, then emits `'error'` on the app, all in one synchronous `catch` block so `emit` listeners see the final
6
+ * context. It never rethrows what `next()` threw.
7
+ *
8
+ * Importing it loads no environment file, no Sentry, no `graphql` and no `koa`: it has no peer dependency.
9
+ * `tdwKoaErrorHandler` is this factory configured for GraphQL errors, Sentry and dotenv.
10
+ */
11
+ export declare function createKoaErrorHandler<TCtx extends IKoaErrorHandlerContext = IKoaErrorHandlerContext>(options?: IKoaErrorHandlerOptions<TCtx>): (ctx: TCtx, next: () => Promise<unknown>) => Promise<void>;
@@ -0,0 +1,37 @@
1
+ /** Statuses that must not carry a body (RFC 9110). Copied into a `Set` per handler, never mutated. */
2
+ const NO_BODY_STATUSES = [100, 101, 102, 204, 205, 304];
3
+ // `||`, not `??`: status 0 and NaN must give 500 too
4
+ const defaultStatusOf = (err) => err?.status || 500;
5
+ const defaultBodyOf = (err) => ({ message: err?.message });
6
+ /**
7
+ * Builds a Koa error middleware: `await next()` in a `try`, and on a throw sets `ctx.status`, sets `ctx.body`, calls
8
+ * `report`, then emits `'error'` on the app, all in one synchronous `catch` block so `emit` listeners see the final
9
+ * context. It never rethrows what `next()` threw.
10
+ *
11
+ * Importing it loads no environment file, no Sentry, no `graphql` and no `koa`: it has no peer dependency.
12
+ * `tdwKoaErrorHandler` is this factory configured for GraphQL errors, Sentry and dotenv.
13
+ */
14
+ export function createKoaErrorHandler(options) {
15
+ const statusOf = options?.statusOf ?? defaultStatusOf;
16
+ const bodyOf = options?.bodyOf ?? defaultBodyOf;
17
+ const report = options?.report;
18
+ const noBodyStatuses = new Set(options?.noBodyStatuses ?? NO_BODY_STATUSES);
19
+ return async function koaErrorHandler(ctx, next) {
20
+ try {
21
+ await next();
22
+ }
23
+ catch (err) {
24
+ ctx.status = statusOf(err, ctx);
25
+ // Read back, not the value just assigned: Koa's setter can store a different number (it drops the body of 204/205/304)
26
+ if (!noBodyStatuses.has(ctx.status)) {
27
+ const body = bodyOf(err, ctx);
28
+ if (body !== undefined) {
29
+ ctx.body = body;
30
+ }
31
+ }
32
+ report?.(err, ctx);
33
+ ctx.app.emit('error', err, ctx);
34
+ }
35
+ };
36
+ }
37
+ //# sourceMappingURL=createKoaErrorHandler.mjs.map
@@ -1,12 +1,12 @@
1
1
  import { redisClient } from "../../../dataSources/Redis.mjs";
2
2
  import { isSessionBlocked } from "../../../lib/isSessionBlocked.mjs";
3
+ import { loadEnv } from "../../../private/lib/loadEnv.mjs";
3
4
  import { verifyIntrospectionCode } from "../../../private/lib/verifyIntrospectionCode.mjs";
4
5
  import { throwForbiddenError } from "../../../graphQL/throw/throwForbiddenError.mjs";
5
6
  import { throwRefreshTokenExpiredOrDeleted } from "../../../graphQL/throw/throwRefreshTokenExpiredOrDeleted.mjs";
6
- import * as dotenv from 'dotenv';
7
7
  import { Types } from 'mongoose';
8
8
  import { verifySignedRefreshToken } from './verifySignedRefreshToken.mjs';
9
- dotenv.config();
9
+ loadEnv();
10
10
  export const authenticatedAuthorizationHandler = (keys) => async (ctx, next) => {
11
11
  /***************************
12
12
  * CLIENT:
@@ -1,12 +1,12 @@
1
1
  import { redisClient } from "../../../dataSources/Redis.mjs";
2
2
  import { isValidUuidV4 } from "../../../lib/isValidUuidV4.mjs";
3
+ import { loadEnv } from "../../../private/lib/loadEnv.mjs";
3
4
  import { verifyIntrospectionCode } from "../../../private/lib/verifyIntrospectionCode.mjs";
4
5
  import { throwAlreadyDone } from "../../../graphQL/throw/throwAlreadyDone.mjs";
5
6
  import { throwPreconditionFailedNoAuthCookie } from "../../../graphQL/throw/throwPreconditionFailedNoAuthCookie.mjs";
6
7
  import { throwPreconditionFailedNoAuthHeader } from "../../../graphQL/throw/throwPreconditionFailedNoAuthHeader.mjs";
7
- import * as dotenv from 'dotenv';
8
8
  import { verifySignedRefreshToken } from '../authenticatedAuthorizationHandler/verifySignedRefreshToken.mjs';
9
- dotenv.config();
9
+ loadEnv();
10
10
  const requireIntrospectionOrThrow = (header, throwOnFail) => {
11
11
  if (typeof header !== 'undefined' && verifyIntrospectionCode(header['x-introspectioncode'])) {
12
12
  return true;
@@ -1,15 +1,15 @@
1
1
  import { redisClient } from "../../../dataSources/Redis.mjs";
2
2
  import { isSessionBlocked } from "../../../lib/isSessionBlocked.mjs";
3
3
  import { isValidUuidV4 } from "../../../lib/isValidUuidV4.mjs";
4
+ import { loadEnv } from "../../../private/lib/loadEnv.mjs";
4
5
  import { verifyIntrospectionCode } from "../../../private/lib/verifyIntrospectionCode.mjs";
5
6
  import { throwAccessTokenExpiredOrDeleted } from "../../../graphQL/throw/throwAccessTokenExpiredOrDeleted.mjs";
6
7
  import { throwAccessTokenRequired } from "../../../graphQL/throw/throwAccessTokenRequired.mjs";
7
8
  import { throwForbiddenError } from "../../../graphQL/throw/throwForbiddenError.mjs";
8
9
  import { throwMissingMalformedInvalidToken } from "../../../graphQL/throw/throwMissingMalformedInvalidToken.mjs";
9
10
  import { throwPreconditionFailedNoAuthHeader } from "../../../graphQL/throw/throwPreconditionFailedNoAuthHeader.mjs";
10
- import * as dotenv from 'dotenv';
11
11
  import { Types } from 'mongoose';
12
- dotenv.config();
12
+ loadEnv();
13
13
  /**
14
14
  * Find out access token in Bearer header
15
15
  */
@@ -1,7 +1,8 @@
1
- import * as Sentry from '@sentry/node';
2
- import * as dotenv from 'dotenv';
1
+ import { loadEnv } from "../private/lib/loadEnv.mjs";
2
+ import * as Sentry from "../private/lib/sentry.mjs";
3
3
  import { GraphQLError } from 'graphql';
4
- dotenv.config();
4
+ import { createKoaErrorHandler } from './createKoaErrorHandler.mjs';
5
+ loadEnv();
5
6
  // check status
6
7
  function resolveErrorStatus(errKoa, isIstanceOfGQL) {
7
8
  if (isIstanceOfGQL) {
@@ -10,13 +11,9 @@ function resolveErrorStatus(errKoa, isIstanceOfGQL) {
10
11
  return errKoa.status || 500;
11
12
  }
12
13
  /**
13
- * do not set body for status codes that do not allow it
14
+ * the factory skips this for status codes that do not allow a body
14
15
  */
15
- function buildErrorBody(errKoa, isIstanceOfGQL, status) {
16
- const allowBody = ![100, 101, 102, 204, 205, 304].includes(status);
17
- if (!allowBody) {
18
- return undefined;
19
- }
16
+ function buildErrorBody(errKoa, isIstanceOfGQL) {
20
17
  const body = {
21
18
  message: errKoa.message
22
19
  };
@@ -33,20 +30,15 @@ function maybeCaptureSentryError(errKoa, isIstanceOfGQL) {
33
30
  }
34
31
  }
35
32
  }
36
- export async function tdwKoaErrorHandler(ctx, next) {
37
- try {
38
- await next();
39
- }
40
- catch (err) {
41
- const errKoa = err;
42
- const isIstanceOfGQL = err instanceof GraphQLError;
43
- ctx.status = resolveErrorStatus(errKoa, isIstanceOfGQL);
44
- const body = buildErrorBody(errKoa, isIstanceOfGQL, ctx.status);
45
- if (body) {
46
- ctx.body = body;
47
- }
48
- maybeCaptureSentryError(errKoa, isIstanceOfGQL);
49
- ctx.app.emit('error', errKoa, ctx);
33
+ const handle = createKoaErrorHandler({
34
+ statusOf: (err) => resolveErrorStatus(err, err instanceof GraphQLError),
35
+ bodyOf: (err) => buildErrorBody(err, err instanceof GraphQLError),
36
+ report: (err) => {
37
+ maybeCaptureSentryError(err, err instanceof GraphQLError);
50
38
  }
39
+ });
40
+ // Not async: returns the factory's promise as is, so there is no extra microtask tick. Name and length (2) stay as before.
41
+ export function tdwKoaErrorHandler(ctx, next) {
42
+ return handle(ctx, next);
51
43
  }
52
44
  //# sourceMappingURL=tdwKoaErrorHandler.mjs.map
@@ -1,6 +1,4 @@
1
- import { Types } from 'mongoose';
2
1
  export declare const OBJECTID_0_STR = "000000000000000000000000";
3
- export declare const OBJECTID_0_OBJ: Types.ObjectId;
4
2
  export declare const EMAIL_MAX_LEN = 255;
5
3
  export declare const MIN_PWD_LENGTH = 10;
6
4
  export declare const MAX_PWD_LENGTH = 72;
@@ -1,6 +1,4 @@
1
- import { Types } from 'mongoose';
2
1
  export const OBJECTID_0_STR = '000000000000000000000000';
3
- export const OBJECTID_0_OBJ = new Types.ObjectId(OBJECTID_0_STR);
4
2
  export const EMAIL_MAX_LEN = 255;
5
3
  export const MIN_PWD_LENGTH = 10;
6
4
  export const MAX_PWD_LENGTH = 72;
@@ -1,5 +1,5 @@
1
1
  import { throwIfMongoErr } from "./throwIfMongoErr.mjs";
2
- import * as Sentry from '@sentry/node';
2
+ import * as Sentry from "../../private/lib/sentry.mjs";
3
3
  import { throwInternalError } from "../../graphQL/throw/throwInternalError.mjs";
4
4
  export const throwMongoDBErrors = (e) => {
5
5
  throwIfMongoErr(e);
@@ -0,0 +1,6 @@
1
+ import { Types } from 'mongoose';
2
+ /**
3
+ * The all-zero sentinel id as a Mongoose `Types.ObjectId`. It has its own subpath so that `lib/Constants` and the
4
+ * helpers that import it do not load `mongoose`.
5
+ */
6
+ export declare const OBJECTID_0_OBJ: Types.ObjectId;
@@ -0,0 +1,8 @@
1
+ import { OBJECTID_0_STR } from "./Constants.mjs";
2
+ import { Types } from 'mongoose';
3
+ /**
4
+ * The all-zero sentinel id as a Mongoose `Types.ObjectId`. It has its own subpath so that `lib/Constants` and the
5
+ * helpers that import it do not load `mongoose`.
6
+ */
7
+ export const OBJECTID_0_OBJ = new Types.ObjectId(OBJECTID_0_STR);
8
+ //# sourceMappingURL=OBJECTID_0_OBJ.mjs.map
@@ -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
- import * as dotenv from 'dotenv';
2
- dotenv.config();
1
+ import { loadEnv } from "../private/lib/loadEnv.mjs";
2
+ loadEnv();
3
3
  const baseOptions = {
4
4
  httpOnly: true,
5
5
  sameSite: 'Strict',
@@ -1,7 +1,8 @@
1
- import { v4 as uuidv4 } from 'uuid';
1
+ import { randomUUID } from 'node:crypto';
2
2
  export const REFRESH_TOKEN_EXPIRY = 90 * 24 * 60 * 60; // 90 days
3
+ // typed `string`, as uuid v4() was: randomUUID() returns a template literal type that would narrow every caller
3
4
  function generateToken() {
4
- return uuidv4();
5
+ return randomUUID();
5
6
  }
6
7
  export function generateAccessToken() {
7
8
  return generateToken();
@@ -1,4 +1,4 @@
1
- import * as Sentry from '@sentry/node';
1
+ import * as Sentry from "../private/lib/sentry.mjs";
2
2
  import { throwGraphQLError } from "../graphQL/throw/throwGraphQLError.mjs";
3
3
  import { throwInternalError } from "../graphQL/throw/throwInternalError.mjs";
4
4
  import { GraphQLError } from 'graphql';
@@ -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,4 +1,4 @@
1
- import * as Sentry from '@sentry/node';
1
+ import * as Sentry from "../lib/sentry.mjs";
2
2
  /** Run a send; a rejection or a throw becomes a Sentry report and `false`, so the caller never sees it. */
3
3
  export async function orFalse(send) {
4
4
  try {
@@ -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) +
@@ -1,4 +1,4 @@
1
- import * as Sentry from '@sentry/node';
1
+ import * as Sentry from "../lib/sentry.mjs";
2
2
  import { throwInternalError } from "../../graphQL/throw/throwInternalError.mjs";
3
3
  import { promises as fs } from 'fs';
4
4
  import sharp from 'sharp';
@@ -1,5 +1,5 @@
1
1
  import { sequelize } from "../../../../dataSources/MariaDB.mjs";
2
- import * as Sentry from '@sentry/node';
2
+ import * as Sentry from "../../../lib/sentry.mjs";
3
3
  import { QueryTypes } from 'sequelize';
4
4
  export async function setLastLoginSQL(id) {
5
5
  // Get the current time in milliseconds since the Unix Epoch
@@ -1,9 +1,9 @@
1
1
  import { redisClient } from "../../../../dataSources/Redis.mjs";
2
2
  import { REFRESH_TOKEN_EXPIRY } from "../../../../lib/tokens.mjs";
3
- import * as Sentry from '@sentry/node';
3
+ import { loadEnv } from "../../../lib/loadEnv.mjs";
4
+ import * as Sentry from "../../../lib/sentry.mjs";
4
5
  import { throwInternalError } from "../../../../graphQL/throw/throwInternalError.mjs";
5
- import * as dotenv from 'dotenv';
6
- dotenv.config();
6
+ loadEnv();
7
7
  export async function setRedisLoginSession(id, accessToken, accTokenExp, refreshToken) {
8
8
  const keyDataAccess = { id: id.toString() };
9
9
  const keyDataRefresh = { ...keyDataAccess, access: accessToken };
@@ -0,0 +1,10 @@
1
+ import type { captureException, captureMessage, Scope } from '@sentry/node';
2
+ /**
3
+ * The three Sentry calls this package makes, with the signatures of `@sentry/node`. The real module satisfies it as is
4
+ * (its `withScope` has a second overload this package never uses); the no-op client in `createSentryClient` too.
5
+ */
6
+ export interface ISentryClient {
7
+ captureException: typeof captureException;
8
+ captureMessage: typeof captureMessage;
9
+ withScope: <T>(callback: (scope: Scope) => T) => T;
10
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ISentryClient.mjs.map
@@ -1,5 +1,5 @@
1
1
  import { DateLib } from "../../../lib/DateLib.mjs";
2
- import * as Sentry from '@sentry/node';
2
+ import * as Sentry from "../sentry.mjs";
3
3
  import { throwForbiddenError } from "../../../graphQL/throw/throwForbiddenError.mjs";
4
4
  import { safeEqualSecret } from './safeEqualSecret.mjs';
5
5
  /** Minutes a reset link stays valid after the request was made. */
@@ -1,6 +1,6 @@
1
1
  import { DEFAULT_VERIFY_EMAIL_PATHS } from "../../../../lib/access/accessPaths.mjs";
2
2
  import { UserBase } from "../../../../graphQL/models/MongoDB/UserBase.mjs";
3
- import * as Sentry from '@sentry/node';
3
+ import * as Sentry from "../../sentry.mjs";
4
4
  /**
5
5
  * Hard delete of an abandoned pending registration, keyed by the login-email path.
6
6
  *
@@ -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.mjs";
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);
@@ -2,7 +2,7 @@ import { DEFAULT_VERIFY_EMAIL_PATHS } from "../../../../lib/access/accessPaths.m
2
2
  import { UserBase } from "../../../../graphQL/models/MongoDB/UserBase.mjs";
3
3
  import { EMAIL_CHECK_LINK } from "../Constants.mjs";
4
4
  import { buildProjection } from "../pathTools.mjs";
5
- import * as Sentry from '@sentry/node';
5
+ import * as Sentry from "../../sentry.mjs";
6
6
  export const createUserData4VerifyEmail = (model, paths) => async function userData4VerifyEmail(uEmail) {
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
@@ -1,4 +1,4 @@
1
- import * as Sentry from '@sentry/node';
1
+ import * as Sentry from "../sentry.mjs";
2
2
  import { EMAIL_CHECK_LINK } from './Constants.mjs';
3
3
  /**
4
4
  * A stored hash without its bookkeeping fields is our bug, not the caller's.
@@ -0,0 +1,7 @@
1
+ import type { ISentryClient } from "./ISentryClient.mjs";
2
+ /**
3
+ * The Sentry client of this package: the SDK itself when it is installed, no-ops when it is not.
4
+ *
5
+ * @param sdk the `@sentry/node` module, or `null` when it is not installed
6
+ */
7
+ export declare function createSentryClient(sdk: ISentryClient | null): ISentryClient;
@@ -0,0 +1,20 @@
1
+ // A scope whose every method is a chainable no-op, like the real setters (`scope.setTag(...).setLevel(...)`).
2
+ // `then` is left undefined: a callback that returns the scope from an async function would otherwise treat it as a
3
+ // thenable and wait forever.
4
+ const noopSetter = () => NOOP_SCOPE;
5
+ const NOOP_SCOPE = new Proxy({}, { get: (_target, property) => (property === 'then' ? undefined : noopSetter) });
6
+ // What the package reports to when `@sentry/node` is not installed: nothing. The event id is '' as no event exists.
7
+ const NOOP_CLIENT = {
8
+ captureException: () => '',
9
+ captureMessage: () => '',
10
+ withScope: (callback) => callback(NOOP_SCOPE)
11
+ };
12
+ /**
13
+ * The Sentry client of this package: the SDK itself when it is installed, no-ops when it is not.
14
+ *
15
+ * @param sdk the `@sentry/node` module, or `null` when it is not installed
16
+ */
17
+ export function createSentryClient(sdk) {
18
+ return sdk ?? NOOP_CLIENT;
19
+ }
20
+ //# sourceMappingURL=createSentryClient.mjs.map
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Load an optional peer dependency. Resolves `null` when `specifier` is not installed, rethrows every other failure.
3
+ *
4
+ * The caller passes its own `() => import('pkg')`, so the specifier stays a string literal at the call site where
5
+ * `tsc` types it and bundlers can see it. `specifier` repeats that name for the error match.
6
+ */
7
+ export declare function importOptional<T>(specifier: string, load: () => Promise<T>): Promise<T | null>;