@venizia/ignis-helpers 0.4.8 → 0.5.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 (87) hide show
  1. package/dist/esm/common/constants/http.d.ts +3 -0
  2. package/dist/esm/common/constants/http.js +3 -0
  3. package/dist/esm/common/constants/http.js.map +1 -1
  4. package/dist/esm/common/redact.js +2 -0
  5. package/dist/esm/common/redact.js.map +1 -1
  6. package/dist/esm/core.d.ts +5 -2
  7. package/dist/esm/core.js +5 -2
  8. package/dist/esm/core.js.map +1 -1
  9. package/dist/esm/modules/network/http-request/base-network-request.helper.d.ts +5 -0
  10. package/dist/esm/modules/network/http-request/base-network-request.helper.js +14 -17
  11. package/dist/esm/modules/network/http-request/base-network-request.helper.js.map +1 -1
  12. package/dist/esm/modules/network/http-request/common/constants.d.ts +2 -1
  13. package/dist/esm/modules/network/http-request/common/constants.js +2 -1
  14. package/dist/esm/modules/network/http-request/common/constants.js.map +1 -1
  15. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.d.ts +37 -11
  16. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js +181 -38
  17. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
  18. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +204 -18
  19. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js +433 -13
  20. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
  21. package/dist/esm/modules/network/http-request/fetcher/common/body-limit.d.ts +36 -0
  22. package/dist/esm/modules/network/http-request/fetcher/common/body-limit.js +119 -0
  23. package/dist/esm/modules/network/http-request/fetcher/common/body-limit.js.map +1 -0
  24. package/dist/esm/modules/network/http-request/fetcher/common/errors.d.ts +40 -0
  25. package/dist/esm/modules/network/http-request/fetcher/common/errors.js +37 -0
  26. package/dist/esm/modules/network/http-request/fetcher/common/errors.js.map +1 -0
  27. package/dist/esm/modules/network/http-request/fetcher/common/guard.d.ts +27 -0
  28. package/dist/esm/modules/network/http-request/fetcher/common/guard.js +2 -0
  29. package/dist/esm/modules/network/http-request/fetcher/common/guard.js.map +1 -0
  30. package/dist/esm/modules/network/http-request/fetcher/common/index.d.ts +6 -0
  31. package/dist/esm/modules/network/http-request/fetcher/common/index.js +6 -0
  32. package/dist/esm/modules/network/http-request/fetcher/common/index.js.map +1 -1
  33. package/dist/esm/modules/network/http-request/fetcher/common/request-context.d.ts +15 -0
  34. package/dist/esm/modules/network/http-request/fetcher/common/request-context.js +11 -0
  35. package/dist/esm/modules/network/http-request/fetcher/common/request-context.js.map +1 -0
  36. package/dist/esm/modules/network/http-request/fetcher/common/response-reader.d.ts +9 -0
  37. package/dist/esm/modules/network/http-request/fetcher/common/response-reader.js +14 -0
  38. package/dist/esm/modules/network/http-request/fetcher/common/response-reader.js.map +1 -0
  39. package/dist/esm/modules/network/http-request/fetcher/common/types.d.ts +65 -1
  40. package/dist/esm/modules/network/http-request/fetcher/common/types.js.map +1 -1
  41. package/dist/esm/modules/network/http-request/fetcher/common/utilities.d.ts +68 -0
  42. package/dist/esm/modules/network/http-request/fetcher/common/utilities.js +143 -0
  43. package/dist/esm/modules/network/http-request/fetcher/common/utilities.js.map +1 -0
  44. package/dist/esm/modules/network/http-request/fetcher/index.d.ts +2 -1
  45. package/dist/esm/modules/network/http-request/fetcher/index.js +2 -1
  46. package/dist/esm/modules/network/http-request/fetcher/index.js.map +1 -1
  47. package/dist/esm/modules/network/http-request/fetcher/native-fetcher.d.ts +83 -0
  48. package/dist/esm/modules/network/http-request/fetcher/native-fetcher.js +221 -0
  49. package/dist/esm/modules/network/http-request/fetcher/native-fetcher.js.map +1 -0
  50. package/dist/esm/modules/network/utilities/index.d.ts +1 -0
  51. package/dist/esm/modules/network/utilities/index.js +1 -0
  52. package/dist/esm/modules/network/utilities/index.js.map +1 -1
  53. package/dist/esm/modules/network/utilities/query-string.d.ts +6 -23
  54. package/dist/esm/modules/network/utilities/query-string.js +3 -17
  55. package/dist/esm/modules/network/utilities/query-string.js.map +1 -1
  56. package/dist/esm/modules/network/utilities/url-builder.d.ts +39 -0
  57. package/dist/esm/modules/network/utilities/url-builder.js +102 -0
  58. package/dist/esm/modules/network/utilities/url-builder.js.map +1 -0
  59. package/dist/esm/modules/network/utilities/url-safety/common/constants.d.ts +0 -3
  60. package/dist/esm/modules/network/utilities/url-safety/common/constants.js.map +1 -1
  61. package/dist/esm/modules/network/utilities/url-safety/common/errors.d.ts +38 -0
  62. package/dist/esm/modules/network/utilities/url-safety/common/errors.js +33 -1
  63. package/dist/esm/modules/network/utilities/url-safety/common/errors.js.map +1 -1
  64. package/dist/esm/modules/network/utilities/url-safety/common/types.d.ts +26 -3
  65. package/dist/esm/modules/network/utilities/url-safety/common/types.js.map +1 -1
  66. package/dist/esm/modules/network/utilities/url-safety/guard.d.ts +46 -0
  67. package/dist/esm/modules/network/utilities/url-safety/guard.js +145 -0
  68. package/dist/esm/modules/network/utilities/url-safety/guard.js.map +1 -0
  69. package/dist/esm/modules/network/utilities/url-safety/index.d.ts +1 -1
  70. package/dist/esm/modules/network/utilities/url-safety/index.js +1 -1
  71. package/dist/esm/modules/network/utilities/url-safety/index.js.map +1 -1
  72. package/dist/esm/modules/network/utilities/url-safety/policy.d.ts +52 -2
  73. package/dist/esm/modules/network/utilities/url-safety/policy.js +161 -14
  74. package/dist/esm/modules/network/utilities/url-safety/policy.js.map +1 -1
  75. package/dist/esm/modules/queue/bullmq/helper.d.ts +43 -7
  76. package/dist/esm/modules/queue/bullmq/helper.js +70 -2
  77. package/dist/esm/modules/queue/bullmq/helper.js.map +1 -1
  78. package/dist/esm/modules/retry/helper.d.ts +3 -1
  79. package/dist/esm/modules/retry/helper.js +8 -4
  80. package/dist/esm/modules/retry/helper.js.map +1 -1
  81. package/package.json +3 -3
  82. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts +0 -41
  83. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js +0 -111
  84. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js.map +0 -1
  85. package/dist/esm/modules/network/utilities/url-safety/ingest.d.ts +0 -95
  86. package/dist/esm/modules/network/utilities/url-safety/ingest.js +0 -328
  87. package/dist/esm/modules/network/utilities/url-safety/ingest.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guard.js","sourceRoot":"","sources":["../../../../../../src/modules/network/utilities/url-safety/guard.ts"],"names":[],"mappings":"AAAA,uHAAuH;AACvH,wFAAwF;AAExF,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAErC,kJAAkJ;AAClJ,MAAM,aAAa;IAKjB,YACmB,MAAwB;IACzC,sFAAsF;IACrE,OAA+C;QAF/C,WAAM,GAAN,MAAM,CAAkB;QAExB,YAAO,GAAP,OAAO,CAAwC;QAN1D,mBAAc,GAAG,IAAI,CAAC;QACtB,eAAU,GAAG,IAAI,CAAC;QAOxB,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,OAAO;YAC7B,CAAC,CAAC,CAAC,mBAAmB,CAAC,cAAc,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,SAAS,CAAC;YACnE,CAAC,CAAC,SAAS,CAAC;IAChB,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,IAA2C;QACnD,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAC7B,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAExB,IAAI,MAAW,CAAC;QAEhB,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YAC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C,QAAQ,EAAE,MAAM,EAAE,EAAE;YACtD,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACtC,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QAC5D,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;YAEpD,OAAO,OAAO,CAAC;QACjB,CAAC;gBAAS,CAAC;YACT,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,OAAqB,CAAC,CAAC;YAC3D,mHAAmH;YACnH,kEAAkE;YAClE,+GAA+G;YAC/G,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC9B,CAAC;IACH,CAAC;CACF","sourcesContent":["// The server half of the url guard: resolving a hostname needs `node:dns`, so nothing here may be re-exported from the\n// `./core` subpath. A fetcher (browser-pure) is handed `UrlGuard` as its `guardEngine`.\n\nimport { DurationMultipliers } from '@/common/constants/duration';\nimport { getError } from '@/modules/error';\nimport { lookup } from 'node:dns/promises';\nimport type { IFetchGuardHop, IFetchGuardRoute } from '../../http-request/fetcher/common/guard';\nimport { UrlSafetyDefaults } from './common/constants';\nimport { UrlSafetyErrors } from './common/errors';\nimport type { IUrlSafetyPolicy } from './common/types';\nimport { UrlPolicy } from './policy';\n\n/** One guarded call: it carries the trust of the redirect chain so far, so a hop after an untrusted one never enters a trusted private origin. */\nclass UrlGuardRoute implements IFetchGuardRoute {\n readonly timeoutMs: number | undefined;\n private isChainTrusted = true;\n private isFirstHop = true;\n\n constructor(\n private readonly policy: IUrlSafetyPolicy,\n // Passed in because this class is defined before `UrlGuard`, which owns the resolver.\n private readonly resolve: typeof UrlGuard.resolvePublicAddresses,\n ) {\n this.timeoutMs = policy.timeout\n ? (DurationMultipliers.toMilliseconds(policy.timeout) ?? undefined)\n : undefined;\n }\n\n async vet(opts: { url: string; signal?: AbortSignal }): Promise<IFetchGuardHop> {\n const { url, signal } = opts;\n const { policy } = this;\n\n let target: URL;\n\n if (this.isFirstHop) {\n // The first url: its shape, then its origin decides whether the chain starts trusted.\n target = UrlPolicy.assertSafeUrl({ url, policy });\n this.isChainTrusted = UrlPolicy.isTrustedOrigin({ origin: target.origin, policy });\n this.isFirstHop = false;\n } else {\n // Trust is entered only through a trusted hop: once a hop is not trusted, every later hop gets the full guard.\n const parsed = new URL(url);\n\n this.isChainTrusted =\n this.isChainTrusted && UrlPolicy.isTrustedOrigin({ origin: parsed.origin, policy });\n target = UrlPolicy.assertSafeUrl({ url, policy, isTrustedAllowed: this.isChainTrusted });\n }\n\n const addresses = await this.resolve({\n hostname: target.hostname,\n trusted: this.isChainTrusted,\n policy,\n signal,\n });\n\n // A proxy resolves the name itself, so there is nothing to pin: the caller chose it (`policy.proxy`).\n // A pinned https connection names the host for the certificate; a literal address has no name to verify.\n const tlsServerName =\n target.protocol === 'https:' && !UrlPolicy.isLiteralHost({ hostname: target.hostname })\n ? target.hostname\n : undefined;\n\n return { url: target, addresses: policy.proxy ? [] : addresses, tlsServerName };\n }\n}\n\n/**\n * The server half of the url guard, the one name for it. As a fetcher's engine: `new NativeFetcher({ ..., guardEngine: UrlGuard })`, then `guard: {}` (or a policy)\n * on a call. Per hop the host is resolved ONCE, every answer is checked, and the request connects to those addresses and\n * to no other, so a DNS answer that changes after the check (DNS rebinding) is never looked up again.\n */\nexport class UrlGuard {\n static createRoute(opts: { policy: IUrlSafetyPolicy }): IFetchGuardRoute {\n return new UrlGuardRoute(opts.policy, (resolveOpts) =>\n UrlGuard.resolvePublicAddresses(resolveOpts),\n );\n }\n\n /**\n * Resolves `hostname` once and returns every address it answered, refusing the host when ANY of them is non-public.\n * Checking only the first walks straight into a host that publishes one public A record beside an internal one.\n * An IP literal answers itself. `allowPrivateAddress` skips the check and returns an empty list: nothing to pin to.\n *\n * With `trusted` (the caller has judged the origin trusted AND every hop before it was trusted too) a private answer\n * is accepted, and the addresses are still returned to pin to. A cloud metadata address is accepted only when the trusted origin's host IS\n * that literal; a trusted host NAME that resolves to one is refused.\n */\n static async resolvePublicAddresses(opts: {\n hostname: string;\n trusted?: boolean;\n policy?: IUrlSafetyPolicy;\n signal?: AbortSignal;\n }): Promise<string[]> {\n const { hostname, trusted, policy, signal } = opts;\n\n if (policy?.allowPrivateAddress ?? UrlSafetyDefaults.ALLOW_PRIVATE_ADDRESS) {\n return [];\n }\n\n // `URL.hostname` keeps the brackets on an IPv6 literal; `lookup` does not accept them, and the\n // ENOTFOUND that follows reads as a transient DNS failure rather than the refusal it should be.\n const address = UrlPolicy.readHostAddress({ hostname });\n const addresses = await UrlGuard.withDeadline({\n work: lookup(address, { all: true }),\n signal,\n });\n\n if (!addresses.length) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertPublicHost] Host resolves to nothing | host: ${hostname}`,\n });\n }\n\n const isLiteral = UrlPolicy.isLiteralHost({ hostname });\n const offender = addresses.find((entry) =>\n trusted\n ? !isLiteral && UrlPolicy.isMetadataAddress({ address: entry.address })\n : UrlPolicy.isNonPublicAddress({ address: entry.address }),\n );\n\n if (offender) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertPublicHost] Host resolves to a non-public address | host: ${hostname} | address: ${offender.address}`,\n });\n }\n\n return addresses.map((entry) => entry.address);\n }\n\n /**\n * Rejects when ANY resolved address is non-public.\n *\n * A rebinding window remains when this is called on its own: the address can change between this check and a\n * later connect. a fetcher call with a `guard` closes it by connecting to the address it vetted.\n */\n static async assertPublicHost(opts: {\n hostname: string;\n trusted?: boolean;\n policy?: IUrlSafetyPolicy;\n }): Promise<void> {\n await UrlGuard.resolvePublicAddresses(opts);\n }\n\n /** Both halves, in the order they must run: shape first, then the network. */\n static async assertReachableUrl(opts: { url: string; policy?: IUrlSafetyPolicy }): Promise<URL> {\n const parsed = UrlPolicy.assertSafeUrl(opts);\n await UrlGuard.assertPublicHost({\n hostname: parsed.hostname,\n trusted: UrlPolicy.isTrustedOrigin({ origin: parsed.origin, policy: opts.policy }),\n policy: opts.policy,\n });\n\n return parsed;\n }\n\n /** Settles with `work`, or rejects with the signal's reason when the deadline passes first: a slow resolver must not outlive it. */\n private static async withDeadline<T>(opts: {\n work: Promise<T>;\n signal?: AbortSignal;\n }): Promise<T> {\n const { work, signal } = opts;\n\n if (!signal) {\n return work;\n }\n\n signal.throwIfAborted();\n\n let onAbort: (() => void) | undefined;\n const aborted = new Promise<never>((_resolve, reject) => {\n onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\n try {\n const settled = await Promise.race([work, aborted]);\n\n return settled;\n } finally {\n signal.removeEventListener('abort', onAbort as () => void);\n // The lookup that lost keeps running; its late answer or error must not surface as an unhandled rejection. Nothing\n // is left to report: the caller already got the deadline's error.\n // eslint-disable-next-line venizia/no-silent-catch -- the work lost the race; its outcome is irrelevant by now\n work.catch(() => undefined);\n }\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
1
  export * from './common/index.js';
2
+ export * from './guard.js';
2
3
  export * from './policy.js';
3
- export * from './ingest.js';
4
4
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,4 @@
1
1
  export * from './common/index.js';
2
+ export * from './guard.js';
2
3
  export * from './policy.js';
3
- export * from './ingest.js';
4
4
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/modules/network/utilities/url-safety/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC","sourcesContent":["export * from './common';\nexport * from './policy';\nexport * from './ingest';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/modules/network/utilities/url-safety/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC","sourcesContent":["export * from './common';\nexport * from './guard';\nexport * from './policy';\n"]}
@@ -30,21 +30,71 @@ export declare class UrlPolicy {
30
30
  static isNonPublicAddress(opts: {
31
31
  address: string;
32
32
  }): boolean;
33
+ /** `127.0.0.0/8`, as the URL parser writes an IPv4 host. */
34
+ private static readonly LOOPBACK_IPV4_PATTERN;
35
+ private static readonly LOOPBACK_HOSTS;
36
+ /** The addresses that mean "any local address", not a host: as the URL parser writes them. */
37
+ private static readonly UNSPECIFIED_HOSTS;
38
+ /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */
39
+ static isLoopbackHost(opts: {
40
+ hostname: string;
41
+ }): boolean;
42
+ /** Whether the URL parser's hostname is an IP literal (a dotted quad or a bracketed IPv6), not a name. */
43
+ static isLiteralHost(opts: {
44
+ hostname: string;
45
+ }): boolean;
46
+ /** The IPv4 metadata services: the link-local block (AWS, GCP, Azure, ...) and Alibaba's address. */
47
+ private static isMetadataIPv4;
48
+ /**
49
+ * An address a cloud metadata service answers on: `169.254.0.0/16` (`169.254.169.254` among them), `100.100.100.200`,
50
+ * `fd00:ec2::254`, the IPv6 link-local block `fe80::/10`, and each IPv4 one written inside an IPv6 address
51
+ * (v4-mapped, v4-compatible, NAT64, 6to4). A trusted host name never opens one of these; only a trusted origin whose
52
+ * host IS the literal does. Anything unparseable answers `true`.
53
+ */
54
+ static isMetadataAddress(opts: {
55
+ address: string;
56
+ }): boolean;
57
+ /**
58
+ * Validates the trusted origins and answers them as a set. An entry is valid only when the URL parser writes the same
59
+ * origin back, so a path, a query, credentials, upper case, a trailing slash, a default port, an odd IP spelling
60
+ * (`http://2130706433`, `http://[::ffff:10.0.0.5]`) and a scheme other than http or https are refused, never
61
+ * corrected or ignored. `0.0.0.0` and `[::]` are not hosts and are refused too.
62
+ */
63
+ static resolveTrustedOrigins(opts: {
64
+ scope: string;
65
+ trusted?: unknown;
66
+ /** The config key the list came from, named in a refusal. */
67
+ label?: string;
68
+ }): ReadonlySet<string>;
69
+ /** Whether `entry` is exactly an http or https origin as the URL parser writes it. */
70
+ private static isOriginText;
71
+ /**
72
+ * Reads `policy.hosts`: its trusted origins, validated, and `strict`. A policy still carrying `allowedHosts` is refused:
73
+ * ignoring it would widen "only these hosts" to "any public host".
74
+ */
75
+ private static readHosts;
76
+ /** Whether `origin` (as `new URL(...).origin` writes it) is one the policy trusts. */
77
+ static isTrustedOrigin(opts: {
78
+ origin: string;
79
+ policy?: IUrlSafetyPolicy;
80
+ }): boolean;
33
81
  /** A bracketed IPv6 literal arrives as `[::1]`; the brackets are not part of the address. */
34
82
  static readHostAddress(opts: {
35
83
  hostname: string;
36
84
  }): string;
37
85
  /**
38
- * A hostname that RESOLVES to a private address passes here on purpose - `UrlIngest` catches that,
86
+ * A hostname that RESOLVES to a private address passes here on purpose - `UrlGuard` catches that,
39
87
  * and this half runs where `node:dns` does not exist.
40
88
  */
41
89
  static assertSafeUrl(opts: {
42
90
  url: string;
43
91
  policy?: IUrlSafetyPolicy;
92
+ /** `false` judges a trusted origin like any other (a guarded fetcher call passes it once a hop of the chain was untrusted). @default true */
93
+ isTrustedAllowed?: boolean;
44
94
  }): URL;
45
95
  /**
46
96
  * True when the url will never be allowed, whatever happens next: a bad scheme, a non-public
47
- * address, a host outside the allow-list, a malformed url, or too many hops. Retrying any of those
97
+ * address, an origin outside a strict trusted list, a malformed url, or too many hops. Retrying any of those
48
98
  * repeats the same rejection - drop the work instead.
49
99
  *
50
100
  * A timeout, a DNS failure or a 5xx answers `false`: those are worth another attempt.
@@ -1,10 +1,11 @@
1
1
  // The browser-pure half of the guard: a url and a literal address are decided with string and
2
- // number work alone. Resolving a hostname needs `node:dns` and lives in `ingest.ts`, which this
2
+ // number work alone. Resolving a hostname needs `node:dns` and lives in `guard.ts`, which this
3
3
  // file must never import - `policy.ts` is re-exported from the `./core` subpath and is gated by
4
4
  // `make purity`.
5
+ import { HTTP } from '../../../../common/constants/index.js';
5
6
  import { getError } from '../../../error/index.js';
6
7
  import { UrlSafetyDefaults, UrlSchemes } from './common/constants.js';
7
- import { UrlSafetyErrors } from './common/errors.js';
8
+ import { UrlSafetyErrors, UrlSafetyRefusals } from './common/errors.js';
8
9
  /** Everything about a url that can be decided without touching the network. */
9
10
  export class UrlPolicy {
10
11
  /** A dotted-quad that is not routable on the public internet. An unparseable input counts as non-public. */
@@ -137,13 +138,151 @@ export class UrlPolicy {
137
138
  (g0 === 0x3fff && (g1 & 0xf000) === 0) || // documentation 3fff::/20
138
139
  (g0 === 0x2001 && (g1 < 0x200 || g1 === 0xdb8)); // IETF protocol assignments 2001::/23 (Teredo, ORCHID, AMT, AS112, ...) and documentation
139
140
  }
141
+ /** `127.0.0.0/8`, as the URL parser writes an IPv4 host. */
142
+ static { this.LOOPBACK_IPV4_PATTERN = /^127(?:\.\d{1,3}){3}$/; }
143
+ static { this.LOOPBACK_HOSTS = new Set(['localhost', '[::1]']); }
144
+ /** The addresses that mean "any local address", not a host: as the URL parser writes them. */
145
+ static { this.UNSPECIFIED_HOSTS = new Set(['0.0.0.0', '[::]']); }
146
+ /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */
147
+ static isLoopbackHost(opts) {
148
+ const { hostname } = opts;
149
+ return UrlPolicy.LOOPBACK_HOSTS.has(hostname) || UrlPolicy.LOOPBACK_IPV4_PATTERN.test(hostname);
150
+ }
151
+ /** Whether the URL parser's hostname is an IP literal (a dotted quad or a bracketed IPv6), not a name. */
152
+ static isLiteralHost(opts) {
153
+ const address = UrlPolicy.readHostAddress(opts);
154
+ return /^[\d.]+$/.test(address) || address.includes(':');
155
+ }
156
+ /** The IPv4 metadata services: the link-local block (AWS, GCP, Azure, ...) and Alibaba's address. */
157
+ static isMetadataIPv4(opts) {
158
+ const { address } = opts;
159
+ return address.startsWith('169.254.') || address === '100.100.100.200';
160
+ }
161
+ /**
162
+ * An address a cloud metadata service answers on: `169.254.0.0/16` (`169.254.169.254` among them), `100.100.100.200`,
163
+ * `fd00:ec2::254`, the IPv6 link-local block `fe80::/10`, and each IPv4 one written inside an IPv6 address
164
+ * (v4-mapped, v4-compatible, NAT64, 6to4). A trusted host name never opens one of these; only a trusted origin whose
165
+ * host IS the literal does. Anything unparseable answers `true`.
166
+ */
167
+ static isMetadataAddress(opts) {
168
+ const normalized = opts.address.toLowerCase().split('%')[0];
169
+ if (!normalized.includes(':')) {
170
+ return (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(normalized) ||
171
+ UrlPolicy.isMetadataIPv4({ address: normalized }));
172
+ }
173
+ const groups = normalized.length > 45 ? null : UrlPolicy.expandIPv6({ address: normalized });
174
+ if (!groups) {
175
+ return true;
176
+ }
177
+ const [g0, g1, g2, g3, g4, g5, g6, g7] = groups;
178
+ const embedded = (high, low) => UrlPolicy.isMetadataIPv4({
179
+ address: [high >> 8, high & 0xff, low >> 8, low & 0xff].join('.'),
180
+ });
181
+ if ([g0, g1, g2, g3, g4].every((group) => group === 0) && (g5 === 0xffff || g5 === 0)) {
182
+ return embedded(g6, g7);
183
+ }
184
+ // v4-translated `::ffff:0:a.b.c.d`
185
+ if ([g0, g1, g2, g3].every((group) => group === 0) && g4 === 0xffff && g5 === 0) {
186
+ return embedded(g6, g7);
187
+ }
188
+ // NAT64: the well-known /96 carries an IPv4 address; the rest of 64:ff9b::/32 is not a translation prefix.
189
+ if (g0 === 0x64 && g1 === 0xff9b) {
190
+ return g2 === 0 && g3 === 0 && g4 === 0 && g5 === 0 ? embedded(g6, g7) : true;
191
+ }
192
+ if (g0 === 0x2002) {
193
+ return embedded(g1, g2);
194
+ }
195
+ const isAwsIPv6 = g0 === 0xfd00 &&
196
+ g1 === 0x0ec2 &&
197
+ [g2, g3, g4, g5, g6].every((group) => group === 0) &&
198
+ g7 === 0x254;
199
+ return (g0 & 0xffc0) === 0xfe80 || isAwsIPv6;
200
+ }
201
+ /**
202
+ * Validates the trusted origins and answers them as a set. An entry is valid only when the URL parser writes the same
203
+ * origin back, so a path, a query, credentials, upper case, a trailing slash, a default port, an odd IP spelling
204
+ * (`http://2130706433`, `http://[::ffff:10.0.0.5]`) and a scheme other than http or https are refused, never
205
+ * corrected or ignored. `0.0.0.0` and `[::]` are not hosts and are refused too.
206
+ */
207
+ static resolveTrustedOrigins(opts) {
208
+ const { scope, trusted } = opts;
209
+ const label = opts.label ?? 'policy.hosts.trusted';
210
+ if (trusted === undefined) {
211
+ return new Set();
212
+ }
213
+ if (!Array.isArray(trusted)) {
214
+ throw getError({
215
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
216
+ message: `[${scope}] ${label} must be a list of origins`,
217
+ });
218
+ }
219
+ const resolved = new Set();
220
+ for (const entry of trusted) {
221
+ if (typeof entry !== 'string' || !UrlPolicy.isOriginText({ entry })) {
222
+ throw getError({
223
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
224
+ message: `[${scope}] ${label} holds ${JSON.stringify(entry)} | list exact origins only, written as the URL parser writes them: 'https://cdn.example.com', 'http://10.0.0.5:8080' or 'http://[fd00::1]' - no path, query, credentials, trailing slash, upper case, default port or wildcard`,
225
+ });
226
+ }
227
+ resolved.add(entry);
228
+ }
229
+ return resolved;
230
+ }
231
+ /** Whether `entry` is exactly an http or https origin as the URL parser writes it. */
232
+ static isOriginText(opts) {
233
+ const { entry } = opts;
234
+ let parsed;
235
+ try {
236
+ parsed = new URL(entry);
237
+ // eslint-disable-next-line venizia/no-silent-catch -- an entry the parser refuses is not an origin: the caller refuses it
238
+ }
239
+ catch {
240
+ return false;
241
+ }
242
+ const isHttp = parsed.protocol === UrlSchemes.HTTP || parsed.protocol === UrlSchemes.HTTPS;
243
+ // The parser lets `*` and other odd characters through a host; an origin names a host, never a pattern.
244
+ const isPlainHost = /^(?:\[[0-9a-f:.]+\]|[a-z0-9][a-z0-9.-]*)$/.test(parsed.hostname);
245
+ return (isHttp &&
246
+ isPlainHost &&
247
+ parsed.origin === entry &&
248
+ !UrlPolicy.UNSPECIFIED_HOSTS.has(parsed.hostname) &&
249
+ parsed.port !== '0');
250
+ }
251
+ /**
252
+ * Reads `policy.hosts`: its trusted origins, validated, and `strict`. A policy still carrying `allowedHosts` is refused:
253
+ * ignoring it would widen "only these hosts" to "any public host".
254
+ */
255
+ static readHosts(opts) {
256
+ const { policy } = opts;
257
+ const scope = opts.scope ?? 'readHosts';
258
+ if (policy && 'allowedHosts' in policy) {
259
+ throw getError({
260
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
261
+ message: `[${scope}] policy.allowedHosts was removed | use policy.hosts: { trusted: ['https://cdn.example.com'], strict: true }`,
262
+ });
263
+ }
264
+ const hosts = policy?.hosts;
265
+ const trusted = UrlPolicy.resolveTrustedOrigins({ scope, trusted: hosts?.trusted });
266
+ const strict = hosts?.strict ?? false;
267
+ if (strict && trusted.size === 0) {
268
+ throw getError({
269
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
270
+ message: `[${scope}] policy.hosts.strict needs at least one trusted origin | nothing would pass`,
271
+ });
272
+ }
273
+ return { trusted, strict };
274
+ }
275
+ /** Whether `origin` (as `new URL(...).origin` writes it) is one the policy trusts. */
276
+ static isTrustedOrigin(opts) {
277
+ return UrlPolicy.readHosts({ policy: opts.policy }).trusted.has(opts.origin);
278
+ }
140
279
  /** A bracketed IPv6 literal arrives as `[::1]`; the brackets are not part of the address. */
141
280
  static readHostAddress(opts) {
142
281
  const { hostname } = opts;
143
282
  return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;
144
283
  }
145
284
  /**
146
- * A hostname that RESOLVES to a private address passes here on purpose - `UrlIngest` catches that,
285
+ * A hostname that RESOLVES to a private address passes here on purpose - `UrlGuard` catches that,
147
286
  * and this half runs where `node:dns` does not exist.
148
287
  */
149
288
  static assertSafeUrl(opts) {
@@ -160,27 +299,36 @@ export class UrlPolicy {
160
299
  message: `[assertSafeUrl] Malformed url | url: ${url}`,
161
300
  });
162
301
  }
163
- if (!allowedSchemes.includes(parsed.protocol)) {
302
+ // Before the trusted check: an origin carries no credentials, so `http://user:pw@vault` has a trusted origin.
303
+ if (parsed.username !== '' || parsed.password !== '') {
164
304
  throw getError({
165
305
  error: UrlSafetyErrors.URL_REFUSED,
166
- message: `[assertSafeUrl] Disallowed scheme | scheme: ${parsed.protocol} | allowed: ${allowedSchemes.join(', ')}`,
306
+ message: '[assertSafeUrl] Url carries a username or a password | credentials do not belong in a url',
167
307
  });
168
308
  }
169
- if (parsed.username !== '' || parsed.password !== '') {
309
+ const { trusted, strict } = UrlPolicy.readHosts({ policy, scope: 'assertSafeUrl' });
310
+ // A trusted origin carries its own scheme and may be private: it skips the scheme and address checks below.
311
+ if (trusted.has(parsed.origin)) {
312
+ if (opts.isTrustedAllowed ?? true) {
313
+ return parsed;
314
+ }
315
+ }
316
+ else if (strict) {
170
317
  throw getError({
171
318
  error: UrlSafetyErrors.URL_REFUSED,
172
- message: '[assertSafeUrl] Url carries a username or a password | credentials do not belong in a url',
319
+ message: `[assertSafeUrl] Origin is not trusted | origin: ${parsed.origin}`,
173
320
  });
174
321
  }
175
- if (policy?.allowedHosts && !policy.allowedHosts.includes(parsed.hostname)) {
322
+ if (!allowedSchemes.includes(parsed.protocol)) {
176
323
  throw getError({
177
324
  error: UrlSafetyErrors.URL_REFUSED,
178
- message: `[assertSafeUrl] Host is not in the allow-list | host: ${parsed.hostname}`,
325
+ message: `[assertSafeUrl] Disallowed scheme | scheme: ${parsed.protocol} | allowed: ${allowedSchemes.join(', ')}`,
179
326
  });
180
327
  }
181
328
  const address = UrlPolicy.readHostAddress({ hostname: parsed.hostname });
182
- const isLiteralAddress = /^[\d.]+$/.test(address) || address.includes(':');
183
- if (!allowPrivateAddress && isLiteralAddress && UrlPolicy.isNonPublicAddress({ address })) {
329
+ if (!allowPrivateAddress &&
330
+ UrlPolicy.isLiteralHost({ hostname: parsed.hostname }) &&
331
+ UrlPolicy.isNonPublicAddress({ address })) {
184
332
  throw getError({
185
333
  error: UrlSafetyErrors.URL_REFUSED,
186
334
  message: `[assertSafeUrl] Url points at a non-public address | address: ${address}`,
@@ -190,14 +338,13 @@ export class UrlPolicy {
190
338
  }
191
339
  /**
192
340
  * True when the url will never be allowed, whatever happens next: a bad scheme, a non-public
193
- * address, a host outside the allow-list, a malformed url, or too many hops. Retrying any of those
341
+ * address, an origin outside a strict trusted list, a malformed url, or too many hops. Retrying any of those
194
342
  * repeats the same rejection - drop the work instead.
195
343
  *
196
344
  * A timeout, a DNS failure or a 5xx answers `false`: those are worth another attempt.
197
345
  */
198
346
  static isRefusedError(opts) {
199
- const source = opts.error;
200
- return source?.normalized?.code === UrlSafetyErrors.URL_REFUSED.message.code;
347
+ return UrlSafetyRefusals.is(opts);
201
348
  }
202
349
  }
203
350
  export { UrlSafetyDefaults, UrlSchemes };
@@ -1 +1 @@
1
- {"version":3,"file":"policy.js","sourceRoot":"","sources":["../../../../../../src/modules/network/utilities/url-safety/policy.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,gGAAgG;AAChG,gGAAgG;AAChG,iBAAiB;AAEjB,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAGlD,+EAA+E;AAC/E,MAAM,OAAO,SAAS;IACpB,4GAA4G;IACpG,MAAM,CAAC,eAAe,CAAC,IAAyB;QACtD,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAEtC,iHAAiH;QACjH,sGAAsG;QACtG,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,C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EAAE,iBAAiB,EAAE,UAAU,EAAE,CAAC","sourcesContent":["// The browser-pure half of the guard: a url and a literal address are decided with string and\n// number work alone. Resolving a hostname needs `node:dns` and lives in `ingest.ts`, which this\n// file must never import - `policy.ts` is re-exported from the `./core` subpath and is gated by\n// `make purity`.\n\nimport { getError } from '@/modules/error';\nimport { UrlSafetyDefaults, UrlSchemes } from './common/constants';\nimport { UrlSafetyErrors } from './common/errors';\nimport type { IUrlSafetyPolicy } from './common/types';\n\n/** Everything about a url that can be decided without touching the network. */\nexport class UrlPolicy {\n /** A dotted-quad that is not routable on the public internet. An unparseable input counts as non-public. */\n private static isNonPublicIPv4(opts: { address: string }): boolean {\n const texts = opts.address.split('.');\n\n // Canonical dotted decimal only: an octet with a leading zero (`0177`, which inet_aton reads as octal 127) or an\n // exponent (`1e2`) is read differently by different parsers, so it is refused rather than guessed at.\n if (texts.length !== 4 || !texts.every((text) => /^(0|[1-9]\\d{0,2})$/.test(text))) {\n return true;\n }\n\n const parts = texts.map(Number);\n\n if (parts.some((part) => part > 255)) {\n return true;\n }\n\n const [first, second] = parts;\n\n return (\n first === 0 || // this host\n first === 10 || // private\n first === 127 || // loopback\n (first === 100 && second >= 64 && second <= 127) || // carrier-grade NAT\n (first === 169 && second === 254) || // link-local, and the cloud metadata address\n (first === 172 && second >= 16 && second <= 31) || // private\n (first === 192 && second === 0) || // IETF protocol assignments\n (first === 192 && second === 168) || // private\n (first === 198 && (second === 18 || second === 19)) || // benchmarking\n first >= 224 // multicast and reserved\n );\n }\n\n /** The four octets of a dotted quad as two IPv6 groups, or `null` when it is not one. */\n private static dottedToGroups(opts: { dotted: string }): number[] | null {\n const octets = opts.dotted.split('.');\n\n if (octets.length !== 4 || !octets.every((octet) => /^(0|[1-9]\\d{0,2})$/.test(octet))) {\n return null;\n }\n\n const [first, second, third, fourth] = octets.map(Number);\n\n if ([first, second, third, fourth].some((octet) => octet > 255)) {\n return null;\n }\n\n return [(first << 8) | second, (third << 8) | fourth];\n }\n\n /**\n * The eight 16-bit groups of an IPv6 literal, whatever its spelling: `::` compression, leading zeros,\n * upper case and a trailing dotted quad (`::127.0.0.1`) all expand to the same groups. `null` for a\n * string that is not an IPv6 literal.\n */\n private static expandIPv6(opts: { address: string }): number[] | null {\n let text = opts.address;\n const dotted = /(\\d+\\.\\d+\\.\\d+\\.\\d+)$/.exec(text)?.[1];\n\n if (dotted) {\n const groups = UrlPolicy.dottedToGroups({ dotted });\n\n if (!groups) {\n return null;\n }\n\n text = `${text.slice(0, -dotted.length)}${groups[0].toString(16)}:${groups[1].toString(16)}`;\n }\n\n const halves = text.split('::');\n\n if (halves.length > 2) {\n return null;\n }\n\n const head = halves[0] === '' ? [] : halves[0].split(':');\n const tail = halves.length === 2 && halves[1] !== '' ? halves[1].split(':') : [];\n const missing = 8 - head.length - tail.length;\n\n if (halves.length === 1 ? missing !== 0 : missing < 1) {\n return null;\n }\n\n const groups = [\n ...head,\n ...new Array<string>(halves.length === 2 ? missing : 0).fill('0'),\n ...tail,\n ];\n\n return groups.every((group) => /^[\\da-f]{1,4}$/.test(group))\n ? groups.map((group) => Number.parseInt(group, 16))\n : null;\n }\n\n /** The IPv4 rules applied to the address carried in two IPv6 groups. */\n private static isNonPublicEmbedded(opts: { high: number; low: number }): boolean {\n const { high, low } = opts;\n\n return UrlPolicy.isNonPublicIPv4({\n address: [high >> 8, high & 0xff, low >> 8, low & 0xff].join('.'),\n });\n }\n\n /**\n * An address that must never be reached with an untrusted url. Anything unrecognised answers\n * `true`: a guard that fails open on a string it cannot parse is not a guard. Takes an IP literal\n * only, in canonical text (dotted decimal without leading zeros; any IPv6 spelling): a domain name or a non-canonical IPv4\n * such as `0177.0.0.1` answers `true`.\n *\n * An IPv6 literal is expanded to its eight groups before it is classified, so every spelling of an\n * address gets the same answer. An address that carries an IPv4 one is judged by the IPv4 rules: v4-mapped\n * (`::ffff:0:0/96`), v4-compatible (`::a.b.c.d`), NAT64 (`64:ff9b::/96`) and 6to4 (`2002::/16`); a\n * `64:ff9b::` address reaches 169.254.169.254 through a NAT64 gateway just as the dotted form does.\n * Unspecified, loopback, unique local (`fc00::/7`), link-local (`fe80::/10`), multicast (`ff00::/8`),\n * site-local (`fec0::/10`), documentation (`2001:db8::/32`, `3fff::/20`), the IETF protocol assignments `2001::/23` (Teredo among them), discard (`100::/64`), SRv6 (`5f00::/16`), the rest of `64:ff9b::/32` and the reserved `::/8` are non-public.\n */\n static isNonPublicAddress(opts: { address: string }): boolean {\n const normalized = opts.address.toLowerCase().split('%')[0];\n\n if (!normalized.includes(':')) {\n return UrlPolicy.isNonPublicIPv4({ address: normalized });\n }\n\n // The longest IPv6 text is 45 characters; a longer string is not an address, and the cap bounds the work below.\n if (normalized.length > 45) {\n return true;\n }\n\n const groups = UrlPolicy.expandIPv6({ address: normalized });\n\n if (!groups) {\n return true;\n }\n\n const [g0, g1, g2, g3, g4, g5, g6, g7] = groups;\n const leadingZeros = [g0, g1, g2, g3, g4].every((group) => group === 0);\n\n // The v4-mapped `::ffff:a.b.c.d` (new URL writes it as `::ffff:a9fe:a9fe`) and the v4-compatible `::a.b.c.d`\n // start with five zero groups. `::` and `::1` are the same shape, and their IPv4 reading (0.0.0.0, 0.0.0.1) is non-public.\n if (leadingZeros && (g5 === 0xffff || g5 === 0)) {\n return UrlPolicy.isNonPublicEmbedded({ high: g6, low: g7 });\n }\n\n // NAT64: the well-known /96 carries an IPv4 address; the rest of 64:ff9b::/32 (local-use /48 included) is not a\n // translation prefix a public host sits behind.\n if (g0 === 0x64 && g1 === 0xff9b) {\n return g2 === 0 && g3 === 0 && g4 === 0 && g5 === 0\n ? UrlPolicy.isNonPublicEmbedded({ high: g6, low: g7 })\n : true;\n }\n\n return g0 === 0x2002 // 6to4: the IPv4 address is groups 1 and 2\n ? UrlPolicy.isNonPublicEmbedded({ high: g1, low: g2 })\n : (g0 & 0xff00) === 0 || // 0000::/8, reserved by IETF: nothing a public host sits on\n (g0 === 0x100 && g1 === 0 && g2 === 0 && g3 === 0) || // discard-only 100::/64\n (g0 & 0xfe00) === 0xfc00 || // unique local\n (g0 & 0xffc0) === 0xfe80 || // link-local\n (g0 & 0xffc0) === 0xfec0 || // site-local, deprecated\n (g0 & 0xff00) === 0xff00 || // multicast\n g0 === 0x5f00 || // SRv6 segment identifiers\n (g0 === 0x3fff && (g1 & 0xf000) === 0) || // documentation 3fff::/20\n (g0 === 0x2001 && (g1 < 0x200 || g1 === 0xdb8)); // IETF protocol assignments 2001::/23 (Teredo, ORCHID, AMT, AS112, ...) and documentation\n }\n\n /** A bracketed IPv6 literal arrives as `[::1]`; the brackets are not part of the address. */\n static readHostAddress(opts: { hostname: string }): string {\n const { hostname } = opts;\n\n return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n }\n\n /**\n * A hostname that RESOLVES to a private address passes here on purpose - `UrlIngest` catches that,\n * and this half runs where `node:dns` does not exist.\n */\n static assertSafeUrl(opts: { url: string; policy?: IUrlSafetyPolicy }): URL {\n const { url, policy } = opts;\n const allowedSchemes = policy?.allowedSchemes ?? UrlSafetyDefaults.ALLOWED_SCHEMES;\n const allowPrivateAddress =\n policy?.allowPrivateAddress ?? UrlSafetyDefaults.ALLOW_PRIVATE_ADDRESS;\n\n let parsed: URL;\n\n try {\n parsed = new URL(url);\n } catch {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertSafeUrl] Malformed url | url: ${url}`,\n });\n }\n\n if (!allowedSchemes.includes(parsed.protocol)) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertSafeUrl] Disallowed scheme | scheme: ${parsed.protocol} | allowed: ${allowedSchemes.join(', ')}`,\n });\n }\n\n if (parsed.username !== '' || parsed.password !== '') {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message:\n '[assertSafeUrl] Url carries a username or a password | credentials do not belong in a url',\n });\n }\n\n if (policy?.allowedHosts && !policy.allowedHosts.includes(parsed.hostname)) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertSafeUrl] Host is not in the allow-list | host: ${parsed.hostname}`,\n });\n }\n\n const address = UrlPolicy.readHostAddress({ hostname: parsed.hostname });\n const isLiteralAddress = /^[\\d.]+$/.test(address) || address.includes(':');\n\n if (!allowPrivateAddress && isLiteralAddress && UrlPolicy.isNonPublicAddress({ address })) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertSafeUrl] Url points at a non-public address | address: ${address}`,\n });\n }\n\n return parsed;\n }\n\n /**\n * True when the url will never be allowed, whatever happens next: a bad scheme, a non-public\n * address, a host outside the allow-list, a malformed url, or too many hops. Retrying any of those\n * repeats the same rejection - drop the work instead.\n *\n * A timeout, a DNS failure or a 5xx answers `false`: those are worth another attempt.\n */\n static isRefusedError(opts: { error: unknown }): boolean {\n const source = opts.error as { normalized?: { code?: string } };\n\n return source?.normalized?.code === UrlSafetyErrors.URL_REFUSED.message.code;\n }\n}\n\nexport { UrlSafetyDefaults, UrlSchemes };\nexport type { IUrlSafetyPolicy };\n"]}
1
+ {"version":3,"file":"policy.js","sourceRoot":"","sources":["../../../../../../src/modules/network/utilities/url-safety/policy.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,+FAA+F;AAC/F,gGAAgG;AAChG,iBAAiB;AAEjB,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAGrE,+EAA+E;AAC/E,MAAM,OAAO,SAAS;IACpB,4GAA4G;IACpG,MAAM,CAAC,eAAe,CAAC,IAAyB;QACtD,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAEtC,iHAAiH;QACjH,sGAAsG;QACtG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,cAAc,CAAC,IAAwB;QAC5C,OAAO,iBAAiB,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC;;AAGH,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,CAAC","sourcesContent":["// The browser-pure half of the guard: a url and a literal address are decided with string and\n// number work alone. Resolving a hostname needs `node:dns` and lives in `guard.ts`, which this\n// file must never import - `policy.ts` is re-exported from the `./core` subpath and is gated by\n// `make purity`.\n\nimport { HTTP } from '@/common/constants';\nimport { getError } from '@/modules/error';\nimport { UrlSafetyDefaults, UrlSchemes } from './common/constants';\nimport { UrlSafetyErrors, UrlSafetyRefusals } from './common/errors';\nimport type { IUrlSafetyPolicy } from './common/types';\n\n/** Everything about a url that can be decided without touching the network. */\nexport class UrlPolicy {\n /** A dotted-quad that is not routable on the public internet. An unparseable input counts as non-public. */\n private static isNonPublicIPv4(opts: { address: string }): boolean {\n const texts = opts.address.split('.');\n\n // Canonical dotted decimal only: an octet with a leading zero (`0177`, which inet_aton reads as octal 127) or an\n // exponent (`1e2`) is read differently by different parsers, so it is refused rather than guessed at.\n if (texts.length !== 4 || !texts.every((text) => /^(0|[1-9]\\d{0,2})$/.test(text))) {\n return true;\n }\n\n const parts = texts.map(Number);\n\n if (parts.some((part) => part > 255)) {\n return true;\n }\n\n const [first, second] = parts;\n\n return (\n first === 0 || // this host\n first === 10 || // private\n first === 127 || // loopback\n (first === 100 && second >= 64 && second <= 127) || // carrier-grade NAT\n (first === 169 && second === 254) || // link-local, and the cloud metadata address\n (first === 172 && second >= 16 && second <= 31) || // private\n (first === 192 && second === 0) || // IETF protocol assignments\n (first === 192 && second === 168) || // private\n (first === 198 && (second === 18 || second === 19)) || // benchmarking\n first >= 224 // multicast and reserved\n );\n }\n\n /** The four octets of a dotted quad as two IPv6 groups, or `null` when it is not one. */\n private static dottedToGroups(opts: { dotted: string }): number[] | null {\n const octets = opts.dotted.split('.');\n\n if (octets.length !== 4 || !octets.every((octet) => /^(0|[1-9]\\d{0,2})$/.test(octet))) {\n return null;\n }\n\n const [first, second, third, fourth] = octets.map(Number);\n\n if ([first, second, third, fourth].some((octet) => octet > 255)) {\n return null;\n }\n\n return [(first << 8) | second, (third << 8) | fourth];\n }\n\n /**\n * The eight 16-bit groups of an IPv6 literal, whatever its spelling: `::` compression, leading zeros,\n * upper case and a trailing dotted quad (`::127.0.0.1`) all expand to the same groups. `null` for a\n * string that is not an IPv6 literal.\n */\n private static expandIPv6(opts: { address: string }): number[] | null {\n let text = opts.address;\n const dotted = /(\\d+\\.\\d+\\.\\d+\\.\\d+)$/.exec(text)?.[1];\n\n if (dotted) {\n const groups = UrlPolicy.dottedToGroups({ dotted });\n\n if (!groups) {\n return null;\n }\n\n text = `${text.slice(0, -dotted.length)}${groups[0].toString(16)}:${groups[1].toString(16)}`;\n }\n\n const halves = text.split('::');\n\n if (halves.length > 2) {\n return null;\n }\n\n const head = halves[0] === '' ? [] : halves[0].split(':');\n const tail = halves.length === 2 && halves[1] !== '' ? halves[1].split(':') : [];\n const missing = 8 - head.length - tail.length;\n\n if (halves.length === 1 ? missing !== 0 : missing < 1) {\n return null;\n }\n\n const groups = [\n ...head,\n ...new Array<string>(halves.length === 2 ? missing : 0).fill('0'),\n ...tail,\n ];\n\n return groups.every((group) => /^[\\da-f]{1,4}$/.test(group))\n ? groups.map((group) => Number.parseInt(group, 16))\n : null;\n }\n\n /** The IPv4 rules applied to the address carried in two IPv6 groups. */\n private static isNonPublicEmbedded(opts: { high: number; low: number }): boolean {\n const { high, low } = opts;\n\n return UrlPolicy.isNonPublicIPv4({\n address: [high >> 8, high & 0xff, low >> 8, low & 0xff].join('.'),\n });\n }\n\n /**\n * An address that must never be reached with an untrusted url. Anything unrecognised answers\n * `true`: a guard that fails open on a string it cannot parse is not a guard. Takes an IP literal\n * only, in canonical text (dotted decimal without leading zeros; any IPv6 spelling): a domain name or a non-canonical IPv4\n * such as `0177.0.0.1` answers `true`.\n *\n * An IPv6 literal is expanded to its eight groups before it is classified, so every spelling of an\n * address gets the same answer. An address that carries an IPv4 one is judged by the IPv4 rules: v4-mapped\n * (`::ffff:0:0/96`), v4-compatible (`::a.b.c.d`), NAT64 (`64:ff9b::/96`) and 6to4 (`2002::/16`); a\n * `64:ff9b::` address reaches 169.254.169.254 through a NAT64 gateway just as the dotted form does.\n * Unspecified, loopback, unique local (`fc00::/7`), link-local (`fe80::/10`), multicast (`ff00::/8`),\n * site-local (`fec0::/10`), documentation (`2001:db8::/32`, `3fff::/20`), the IETF protocol assignments `2001::/23` (Teredo among them), discard (`100::/64`), SRv6 (`5f00::/16`), the rest of `64:ff9b::/32` and the reserved `::/8` are non-public.\n */\n static isNonPublicAddress(opts: { address: string }): boolean {\n const normalized = opts.address.toLowerCase().split('%')[0];\n\n if (!normalized.includes(':')) {\n return UrlPolicy.isNonPublicIPv4({ address: normalized });\n }\n\n // The longest IPv6 text is 45 characters; a longer string is not an address, and the cap bounds the work below.\n if (normalized.length > 45) {\n return true;\n }\n\n const groups = UrlPolicy.expandIPv6({ address: normalized });\n\n if (!groups) {\n return true;\n }\n\n const [g0, g1, g2, g3, g4, g5, g6, g7] = groups;\n const leadingZeros = [g0, g1, g2, g3, g4].every((group) => group === 0);\n\n // The v4-mapped `::ffff:a.b.c.d` (new URL writes it as `::ffff:a9fe:a9fe`) and the v4-compatible `::a.b.c.d`\n // start with five zero groups. `::` and `::1` are the same shape, and their IPv4 reading (0.0.0.0, 0.0.0.1) is non-public.\n if (leadingZeros && (g5 === 0xffff || g5 === 0)) {\n return UrlPolicy.isNonPublicEmbedded({ high: g6, low: g7 });\n }\n\n // NAT64: the well-known /96 carries an IPv4 address; the rest of 64:ff9b::/32 (local-use /48 included) is not a\n // translation prefix a public host sits behind.\n if (g0 === 0x64 && g1 === 0xff9b) {\n return g2 === 0 && g3 === 0 && g4 === 0 && g5 === 0\n ? UrlPolicy.isNonPublicEmbedded({ high: g6, low: g7 })\n : true;\n }\n\n return g0 === 0x2002 // 6to4: the IPv4 address is groups 1 and 2\n ? UrlPolicy.isNonPublicEmbedded({ high: g1, low: g2 })\n : (g0 & 0xff00) === 0 || // 0000::/8, reserved by IETF: nothing a public host sits on\n (g0 === 0x100 && g1 === 0 && g2 === 0 && g3 === 0) || // discard-only 100::/64\n (g0 & 0xfe00) === 0xfc00 || // unique local\n (g0 & 0xffc0) === 0xfe80 || // link-local\n (g0 & 0xffc0) === 0xfec0 || // site-local, deprecated\n (g0 & 0xff00) === 0xff00 || // multicast\n g0 === 0x5f00 || // SRv6 segment identifiers\n (g0 === 0x3fff && (g1 & 0xf000) === 0) || // documentation 3fff::/20\n (g0 === 0x2001 && (g1 < 0x200 || g1 === 0xdb8)); // IETF protocol assignments 2001::/23 (Teredo, ORCHID, AMT, AS112, ...) and documentation\n }\n\n /** `127.0.0.0/8`, as the URL parser writes an IPv4 host. */\n private static readonly LOOPBACK_IPV4_PATTERN = /^127(?:\\.\\d{1,3}){3}$/;\n\n private static readonly LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '[::1]']);\n\n /** The addresses that mean \"any local address\", not a host: as the URL parser writes them. */\n private static readonly UNSPECIFIED_HOSTS: ReadonlySet<string> = new Set(['0.0.0.0', '[::]']);\n\n /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */\n static isLoopbackHost(opts: { hostname: string }): boolean {\n const { hostname } = opts;\n\n return UrlPolicy.LOOPBACK_HOSTS.has(hostname) || UrlPolicy.LOOPBACK_IPV4_PATTERN.test(hostname);\n }\n\n /** Whether the URL parser's hostname is an IP literal (a dotted quad or a bracketed IPv6), not a name. */\n static isLiteralHost(opts: { hostname: string }): boolean {\n const address = UrlPolicy.readHostAddress(opts);\n\n return /^[\\d.]+$/.test(address) || address.includes(':');\n }\n\n /** The IPv4 metadata services: the link-local block (AWS, GCP, Azure, ...) and Alibaba's address. */\n private static isMetadataIPv4(opts: { address: string }): boolean {\n const { address } = opts;\n\n return address.startsWith('169.254.') || address === '100.100.100.200';\n }\n\n /**\n * An address a cloud metadata service answers on: `169.254.0.0/16` (`169.254.169.254` among them), `100.100.100.200`,\n * `fd00:ec2::254`, the IPv6 link-local block `fe80::/10`, and each IPv4 one written inside an IPv6 address\n * (v4-mapped, v4-compatible, NAT64, 6to4). A trusted host name never opens one of these; only a trusted origin whose\n * host IS the literal does. Anything unparseable answers `true`.\n */\n static isMetadataAddress(opts: { address: string }): boolean {\n const normalized = opts.address.toLowerCase().split('%')[0];\n\n if (!normalized.includes(':')) {\n return (\n !/^\\d{1,3}(?:\\.\\d{1,3}){3}$/.test(normalized) ||\n UrlPolicy.isMetadataIPv4({ address: normalized })\n );\n }\n\n const groups = normalized.length > 45 ? null : UrlPolicy.expandIPv6({ address: normalized });\n\n if (!groups) {\n return true;\n }\n\n const [g0, g1, g2, g3, g4, g5, g6, g7] = groups;\n const embedded = (high: number, low: number) =>\n UrlPolicy.isMetadataIPv4({\n address: [high >> 8, high & 0xff, low >> 8, low & 0xff].join('.'),\n });\n\n if ([g0, g1, g2, g3, g4].every((group) => group === 0) && (g5 === 0xffff || g5 === 0)) {\n return embedded(g6, g7);\n }\n\n // v4-translated `::ffff:0:a.b.c.d`\n if ([g0, g1, g2, g3].every((group) => group === 0) && g4 === 0xffff && g5 === 0) {\n return embedded(g6, g7);\n }\n\n // NAT64: the well-known /96 carries an IPv4 address; the rest of 64:ff9b::/32 is not a translation prefix.\n if (g0 === 0x64 && g1 === 0xff9b) {\n return g2 === 0 && g3 === 0 && g4 === 0 && g5 === 0 ? embedded(g6, g7) : true;\n }\n\n if (g0 === 0x2002) {\n return embedded(g1, g2);\n }\n\n const isAwsIPv6 =\n g0 === 0xfd00 &&\n g1 === 0x0ec2 &&\n [g2, g3, g4, g5, g6].every((group) => group === 0) &&\n g7 === 0x254;\n\n return (g0 & 0xffc0) === 0xfe80 || isAwsIPv6;\n }\n\n /**\n * Validates the trusted origins and answers them as a set. An entry is valid only when the URL parser writes the same\n * origin back, so a path, a query, credentials, upper case, a trailing slash, a default port, an odd IP spelling\n * (`http://2130706433`, `http://[::ffff:10.0.0.5]`) and a scheme other than http or https are refused, never\n * corrected or ignored. `0.0.0.0` and `[::]` are not hosts and are refused too.\n */\n static resolveTrustedOrigins(opts: {\n scope: string;\n trusted?: unknown;\n /** The config key the list came from, named in a refusal. */\n label?: string;\n }): ReadonlySet<string> {\n const { scope, trusted } = opts;\n const label = opts.label ?? 'policy.hosts.trusted';\n\n if (trusted === undefined) {\n return new Set();\n }\n\n if (!Array.isArray(trusted)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} must be a list of origins`,\n });\n }\n\n const resolved = new Set<string>();\n\n for (const entry of trusted) {\n if (typeof entry !== 'string' || !UrlPolicy.isOriginText({ entry })) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} holds ${JSON.stringify(entry)} | list exact origins only, written as the URL parser writes them: 'https://cdn.example.com', 'http://10.0.0.5:8080' or 'http://[fd00::1]' - no path, query, credentials, trailing slash, upper case, default port or wildcard`,\n });\n }\n\n resolved.add(entry);\n }\n\n return resolved;\n }\n\n /** Whether `entry` is exactly an http or https origin as the URL parser writes it. */\n private static isOriginText(opts: { entry: string }): boolean {\n const { entry } = opts;\n\n let parsed: URL;\n\n try {\n parsed = new URL(entry);\n // eslint-disable-next-line venizia/no-silent-catch -- an entry the parser refuses is not an origin: the caller refuses it\n } catch {\n return false;\n }\n\n const isHttp = parsed.protocol === UrlSchemes.HTTP || parsed.protocol === UrlSchemes.HTTPS;\n\n // The parser lets `*` and other odd characters through a host; an origin names a host, never a pattern.\n const isPlainHost = /^(?:\\[[0-9a-f:.]+\\]|[a-z0-9][a-z0-9.-]*)$/.test(parsed.hostname);\n\n return (\n isHttp &&\n isPlainHost &&\n parsed.origin === entry &&\n !UrlPolicy.UNSPECIFIED_HOSTS.has(parsed.hostname) &&\n parsed.port !== '0'\n );\n }\n\n /**\n * Reads `policy.hosts`: its trusted origins, validated, and `strict`. A policy still carrying `allowedHosts` is refused:\n * ignoring it would widen \"only these hosts\" to \"any public host\".\n */\n private static readHosts(opts: { policy?: IUrlSafetyPolicy; scope?: string }): {\n trusted: ReadonlySet<string>;\n strict: boolean;\n } {\n const { policy } = opts;\n const scope = opts.scope ?? 'readHosts';\n\n if (policy && 'allowedHosts' in policy) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] policy.allowedHosts was removed | use policy.hosts: { trusted: ['https://cdn.example.com'], strict: true }`,\n });\n }\n\n const hosts = policy?.hosts;\n const trusted = UrlPolicy.resolveTrustedOrigins({ scope, trusted: hosts?.trusted });\n const strict = hosts?.strict ?? false;\n\n if (strict && trusted.size === 0) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] policy.hosts.strict needs at least one trusted origin | nothing would pass`,\n });\n }\n\n return { trusted, strict };\n }\n\n /** Whether `origin` (as `new URL(...).origin` writes it) is one the policy trusts. */\n static isTrustedOrigin(opts: { origin: string; policy?: IUrlSafetyPolicy }): boolean {\n return UrlPolicy.readHosts({ policy: opts.policy }).trusted.has(opts.origin);\n }\n\n /** A bracketed IPv6 literal arrives as `[::1]`; the brackets are not part of the address. */\n static readHostAddress(opts: { hostname: string }): string {\n const { hostname } = opts;\n\n return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n }\n\n /**\n * A hostname that RESOLVES to a private address passes here on purpose - `UrlGuard` catches that,\n * and this half runs where `node:dns` does not exist.\n */\n static assertSafeUrl(opts: {\n url: string;\n policy?: IUrlSafetyPolicy;\n /** `false` judges a trusted origin like any other (a guarded fetcher call passes it once a hop of the chain was untrusted). @default true */\n isTrustedAllowed?: boolean;\n }): URL {\n const { url, policy } = opts;\n const allowedSchemes = policy?.allowedSchemes ?? UrlSafetyDefaults.ALLOWED_SCHEMES;\n const allowPrivateAddress =\n policy?.allowPrivateAddress ?? UrlSafetyDefaults.ALLOW_PRIVATE_ADDRESS;\n\n let parsed: URL;\n\n try {\n parsed = new URL(url);\n } catch {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertSafeUrl] Malformed url | url: ${url}`,\n });\n }\n\n // Before the trusted check: an origin carries no credentials, so `http://user:pw@vault` has a trusted origin.\n if (parsed.username !== '' || parsed.password !== '') {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message:\n '[assertSafeUrl] Url carries a username or a password | credentials do not belong in a url',\n });\n }\n\n const { trusted, strict } = UrlPolicy.readHosts({ policy, scope: 'assertSafeUrl' });\n\n // A trusted origin carries its own scheme and may be private: it skips the scheme and address checks below.\n if (trusted.has(parsed.origin)) {\n if (opts.isTrustedAllowed ?? true) {\n return parsed;\n }\n } else if (strict) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertSafeUrl] Origin is not trusted | origin: ${parsed.origin}`,\n });\n }\n\n if (!allowedSchemes.includes(parsed.protocol)) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertSafeUrl] Disallowed scheme | scheme: ${parsed.protocol} | allowed: ${allowedSchemes.join(', ')}`,\n });\n }\n\n const address = UrlPolicy.readHostAddress({ hostname: parsed.hostname });\n\n if (\n !allowPrivateAddress &&\n UrlPolicy.isLiteralHost({ hostname: parsed.hostname }) &&\n UrlPolicy.isNonPublicAddress({ address })\n ) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertSafeUrl] Url points at a non-public address | address: ${address}`,\n });\n }\n\n return parsed;\n }\n\n /**\n * True when the url will never be allowed, whatever happens next: a bad scheme, a non-public\n * address, an origin outside a strict trusted list, a malformed url, or too many hops. Retrying any of those\n * repeats the same rejection - drop the work instead.\n *\n * A timeout, a DNS failure or a 5xx answers `false`: those are worth another attempt.\n */\n static isRefusedError(opts: { error: unknown }): boolean {\n return UrlSafetyRefusals.is(opts);\n }\n}\n\nexport { UrlSafetyDefaults, UrlSchemes };\nexport type { IUrlSafetyPolicy };\n"]}
@@ -1,9 +1,16 @@
1
+ import type { ValueOrPromise } from '../../../common/index.js';
1
2
  import { BaseHelper } from '../../base.js';
2
3
  import { type IRedisHelper, type TRedisClient } from '../../redis/index.js';
3
- import type { Job, Processor, Queue, QueueOptions, Worker, WorkerOptions } from 'bullmq';
4
+ import type { Job, JobsOptions, Processor, Queue, QueueOptions, Worker, WorkerOptions } from 'bullmq';
4
5
  import { type TBullQueueRole } from '../common/index.js';
6
+ /** `Queue.add` for this helper's element and result types: BullMQ resolves its name and data types through conditional types, so they are read off the method. */
7
+ type TQueueAdd<TElement, TResult> = Queue<TElement, TResult>['add'];
8
+ /** What `onWorkerData` is told beside the job: the metadata the producer's helper stamped, `undefined` for a job added without one. */
9
+ export interface IBullMQJobContext<TMetadata extends object = Record<string, unknown>> {
10
+ metadata: TMetadata | undefined;
11
+ }
5
12
  /** Options for {@link BullMQHelper}. `role` decides whether a `Queue` or a `Worker` is built. */
6
- export interface IBullMQOptions<TQueueElement = unknown, TQueueResult = unknown> {
13
+ export interface IBullMQOptions<TQueueElement = unknown, TQueueResult = unknown, TMetadata extends object = Record<string, unknown>> {
7
14
  queueName: string;
8
15
  identifier: string;
9
16
  role: TBullQueueRole;
@@ -20,11 +27,22 @@ export interface IBullMQOptions<TQueueElement = unknown, TQueueResult = unknown>
20
27
  * @default BullMQDefaults.LOCK_DURATION_MS
21
28
  */
22
29
  lockDuration?: number;
30
+ /**
31
+ * The prefix of every Redis key of the queue, on the Queue AND the Worker so they cannot disagree. Opt-in: unset is BullMQ's own
32
+ * `bull`, so no key moves. A `queueOptions.prefix` or `workerOptions.prefix` that differs is refused. Switching it strands the
33
+ * waiting, failed and repeatable jobs and the job schedulers under the old prefix: see the queue helper's migration notes.
34
+ */
35
+ prefix?: string;
36
+ /**
37
+ * A block stamped on every job added through `add`, run on each add and stored in the job's `opts.metadata`, outside `job.data`.
38
+ * A throw fails the add; the answer must be a plain object. The worker reads it as `context.metadata`.
39
+ */
40
+ metadata?: () => ValueOrPromise<TMetadata>;
23
41
  /** Merged over the framework defaults, under the fields the helper owns (`connection`) - see `queueOptionsFor`. */
24
42
  queueOptions?: Omit<QueueOptions, 'connection'>;
25
43
  /** Merged under the fields the helper owns (`connection`, `concurrency`, `lockDuration`) - see `workerOptionsFor`. */
26
44
  workerOptions?: Omit<WorkerOptions, 'connection' | 'concurrency' | 'lockDuration'>;
27
- onWorkerData?: (job: Job<TQueueElement, TQueueResult>) => Promise<TQueueResult>;
45
+ onWorkerData?: (job: Job<TQueueElement, TQueueResult>, context: IBullMQJobContext<TMetadata>) => Promise<TQueueResult>;
28
46
  onWorkerDataCompleted?: (job: Job<TQueueElement, TQueueResult>, result: TQueueResult) => Promise<void>;
29
47
  onWorkerDataFail?: (job: Job<TQueueElement, TQueueResult> | undefined, error: Error) => Promise<void>;
30
48
  }
@@ -32,7 +50,7 @@ export interface IBullMQOptions<TQueueElement = unknown, TQueueResult = unknown>
32
50
  * Wraps a BullMQ `Queue` or `Worker` (per `role`) on one Redis connection.
33
51
  * Worker concurrency is `numberOfWorker`; `lockDuration` is in milliseconds.
34
52
  */
35
- export declare class BullMQHelper<TQueueElement = unknown, TQueueResult = unknown> extends BaseHelper {
53
+ export declare class BullMQHelper<TQueueElement = unknown, TQueueResult = unknown, TMetadata extends object = Record<string, unknown>> extends BaseHelper {
36
54
  protected queueName: string;
37
55
  protected role: TBullQueueRole;
38
56
  protected redisConnection: IRedisHelper;
@@ -42,17 +60,34 @@ export declare class BullMQHelper<TQueueElement = unknown, TQueueResult = unknow
42
60
  protected lockDuration: number;
43
61
  protected queueOptions?: Omit<QueueOptions, 'connection'>;
44
62
  protected workerOptions?: Omit<WorkerOptions, 'connection' | 'concurrency' | 'lockDuration'>;
45
- protected onWorkerData?: (job: Job<TQueueElement, TQueueResult>) => Promise<TQueueResult>;
63
+ protected prefix?: string;
64
+ protected metadata?: () => ValueOrPromise<TMetadata>;
65
+ protected onWorkerData?: (job: Job<TQueueElement, TQueueResult>, context: IBullMQJobContext<TMetadata>) => Promise<TQueueResult>;
46
66
  protected onWorkerDataCompleted?: (job: Job<TQueueElement, TQueueResult>, result: TQueueResult) => Promise<void>;
47
67
  protected onWorkerDataFail?: (job: Job<TQueueElement, TQueueResult> | undefined, error: Error) => Promise<void>;
48
68
  private readonly bullmqModule?;
49
69
  private isClosing;
50
70
  /** Every duplicate this helper handed to BullMQ: BullMQ never quits a client it is given, so `close()` does. */
51
71
  private readonly duplicates;
52
- constructor(options: IBullMQOptions<TQueueElement, TQueueResult>);
72
+ constructor(options: IBullMQOptions<TQueueElement, TQueueResult, TMetadata>);
53
73
  /** BullMQ never reconnects a client: once ioredis stops reconnecting (`maxRetry` attempts used up) it is `end` for good, no job moves, and nothing else says so. */
54
74
  protected reportClientEnded(): void;
55
- static newInstance<T = unknown, R = unknown>(opts: IBullMQOptions<T, R>): BullMQHelper<T, R>;
75
+ static newInstance<T = unknown, R = unknown, M extends object = Record<string, unknown>>(opts: IBullMQOptions<T, R, M>): BullMQHelper<T, R, M>;
76
+ /** `prefix` as the helper keeps it: a non-empty string with no whitespace and no brace (a brace would move the cluster hash tag), the same on the Queue and the Worker; unset stays unset (BullMQ's `bull`). */
77
+ private static resolvePrefix;
78
+ /** The metadata a producer's helper stamped on `job`, or `undefined` for a job added without one (a raw `queue.add`, another producer). Not part of `job.data`. Returned as stored: its fields are not validated against `TMetadata`. */
79
+ static readMetadata<TMetadata extends object = Record<string, unknown>>(opts: {
80
+ job: Pick<Job, 'opts'> | undefined;
81
+ }): TMetadata | undefined;
82
+ /**
83
+ * Adds a job, stamped by the `metadata` option: the stamp goes to `opts.metadata`, and `data` is exactly what you pass (any shape). A direct
84
+ * `queue.add` is available and unstamped. Refuses `opts.metadata` from the caller (the stamp is the one source) and a stamp that is not an object.
85
+ */
86
+ add(opts: {
87
+ name: Parameters<TQueueAdd<TQueueElement, TQueueResult>>[0];
88
+ data: Parameters<TQueueAdd<TQueueElement, TQueueResult>>[1];
89
+ opts?: JobsOptions;
90
+ }): ReturnType<TQueueAdd<TQueueElement, TQueueResult>>;
56
91
  /** Structural, never `instanceof`: ioredis is an optional peer, and a second copy fails `instanceof` anyway. */
57
92
  protected isClusterClient(): boolean;
58
93
  protected resolveQueueName(): string;
@@ -89,4 +124,5 @@ export declare class BullMQHelper<TQueueElement = unknown, TQueueResult = unknow
89
124
  private static release;
90
125
  close(): Promise<void>;
91
126
  }
127
+ export {};
92
128
  //# sourceMappingURL=helper.d.ts.map