addons-scanner-utils 10.2.0 → 12.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.
package/README.md CHANGED
@@ -12,7 +12,7 @@ yarn add addons-scanner-utils
12
12
 
13
13
  ## Requirements
14
14
 
15
- - You need [Node](https://nodejs.org/) 16, which is the current [LTS](https://github.com/nodejs/LTS) (long term support) release.
15
+ - You need [Node](https://nodejs.org/) 20, which is the current [LTS](https://github.com/nodejs/LTS) (long term support) release.
16
16
  - You need [yarn](https://yarnpkg.com/en/) to manage dependencies and run commands.
17
17
 
18
18
  ## Development
package/dist/const.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const ECMA_VERSION = 15;
1
+ export declare const ECMA_VERSION = 16;
package/dist/const.js CHANGED
@@ -2,4 +2,4 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ECMA_VERSION = void 0;
4
4
  // This is the ECMAScript version officially supported by AMO.
5
- exports.ECMA_VERSION = 15; // a.k.a. 2024
5
+ exports.ECMA_VERSION = 16; // a.k.a. 2025
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Error object with HTTP status code and optional extra information.
3
+ *
4
+ * @property message - Error message
5
+ * @property extraInfo - Additional error details
6
+ * @property status - HTTP status code
7
+ */
8
+ export type ApiError = Error & {
9
+ extraInfo?: string;
10
+ status: number;
11
+ };
12
+ /**
13
+ * Parameters for creating an API error.
14
+ *
15
+ * @property message - Error message
16
+ * @property extraInfo - Additional error details
17
+ * @property status - HTTP status code (default: 500)
18
+ */
19
+ export type CreateApiErrorParams = {
20
+ message: string;
21
+ extraInfo?: string;
22
+ status?: number;
23
+ };
24
+ /**
25
+ * Create API error object with status code and extra information.
26
+ */
27
+ export declare const createApiError: ({ message, extraInfo, status, }: CreateApiErrorParams) => ApiError;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createApiError = void 0;
4
+ /**
5
+ * Create API error object with status code and extra information.
6
+ */
7
+ const createApiError = ({ message, extraInfo, status = 500, }) => {
8
+ const error = new Error(message);
9
+ error.status = status;
10
+ error.extraInfo = extraInfo;
11
+ return error;
12
+ };
13
+ exports.createApiError = createApiError;
@@ -0,0 +1,37 @@
1
+ export declare const DEFAULT_DOWNLOAD_FILENAME = "input.xpi";
2
+ /**
3
+ * Error thrown when file download operations fail.
4
+ *
5
+ * @property status - HTTP status code
6
+ * @property extraInfo - Additional error details
7
+ */
8
+ export declare class DownloadFileError extends Error {
9
+ status: number;
10
+ extraInfo?: string;
11
+ constructor(message: string, extraInfo?: string, status?: number);
12
+ /**
13
+ * Convert this error to ApiError format.
14
+ */
15
+ toApiError(): import("./api").ApiError;
16
+ }
17
+ /**
18
+ * Parameters for downloading a file upload.
19
+ *
20
+ * @property downloadURL - URL to download from
21
+ * @property allowedOrigin - Allowed origin for the download URL
22
+ * @property tmpDir - Temporary directory for download (default: os.tmpdir())
23
+ * @property filename - Downloaded file name (default: 'input.xpi')
24
+ */
25
+ export type DownloadFileUploadParams = {
26
+ downloadURL: string;
27
+ allowedOrigin: string;
28
+ tmpDir?: string;
29
+ filename?: string;
30
+ };
31
+ /**
32
+ * Download a file from a URL to a temporary location.
33
+ *
34
+ * @returns Promise resolving to the file path of the downloaded file
35
+ * @throws DownloadFileError if the download fails or URL origin doesn't match
36
+ */
37
+ export declare const downloadFileUpload: ({ downloadURL, allowedOrigin, tmpDir, filename, }: DownloadFileUploadParams) => Promise<string>;
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.downloadFileUpload = exports.DownloadFileError = exports.DEFAULT_DOWNLOAD_FILENAME = void 0;
16
+ const node_os_1 = __importDefault(require("node:os"));
17
+ const node_path_1 = __importDefault(require("node:path"));
18
+ const node_fs_1 = require("node:fs");
19
+ const node_stream_1 = require("node:stream");
20
+ const promises_1 = require("node:stream/promises");
21
+ const api_1 = require("./api");
22
+ exports.DEFAULT_DOWNLOAD_FILENAME = 'input.xpi';
23
+ /**
24
+ * Error thrown when file download operations fail.
25
+ *
26
+ * @property status - HTTP status code
27
+ * @property extraInfo - Additional error details
28
+ */
29
+ class DownloadFileError extends Error {
30
+ constructor(message, extraInfo, status = 500) {
31
+ super(message);
32
+ this.name = 'DownloadFileError';
33
+ this.status = status;
34
+ this.extraInfo = extraInfo;
35
+ }
36
+ /**
37
+ * Convert this error to ApiError format.
38
+ */
39
+ toApiError() {
40
+ return (0, api_1.createApiError)({
41
+ message: this.message,
42
+ extraInfo: this.extraInfo,
43
+ status: this.status,
44
+ });
45
+ }
46
+ }
47
+ exports.DownloadFileError = DownloadFileError;
48
+ /**
49
+ * Download a file from a URL to a temporary location.
50
+ *
51
+ * @returns Promise resolving to the file path of the downloaded file
52
+ * @throws DownloadFileError if the download fails or URL origin doesn't match
53
+ */
54
+ const downloadFileUpload = (_a) => __awaiter(void 0, [_a], void 0, function* ({ downloadURL, allowedOrigin, tmpDir = node_os_1.default.tmpdir(), filename = exports.DEFAULT_DOWNLOAD_FILENAME, }) {
55
+ if (!downloadURL.startsWith(`${allowedOrigin}/`)) {
56
+ throw new DownloadFileError(`download URL does not match allowed origin: ${allowedOrigin}`, undefined, 400);
57
+ }
58
+ try {
59
+ const response = yield fetch(downloadURL);
60
+ if (!response.ok || !response.body) {
61
+ throw new DownloadFileError(`unexpected response: ${response.statusText}`);
62
+ }
63
+ const filepath = node_path_1.default.join(tmpDir, filename);
64
+ yield (0, promises_1.pipeline)(node_stream_1.Readable.fromWeb(response.body), (0, node_fs_1.createWriteStream)(filepath));
65
+ return filepath;
66
+ }
67
+ catch (err) {
68
+ if (err instanceof DownloadFileError) {
69
+ throw err;
70
+ }
71
+ const message = err instanceof Error ? err.message : String(err);
72
+ throw new DownloadFileError('failed to download file', message);
73
+ }
74
+ });
75
+ exports.downloadFileUpload = downloadFileUpload;
@@ -0,0 +1,50 @@
1
+ import { Request, RequestHandler } from 'express';
2
+ /**
3
+ * Extended Express request type with additional properties added by the
4
+ * middleware.
5
+ *
6
+ * @property rawBody - Raw request body buffer used for HMAC signature
7
+ * verification
8
+ */
9
+ export type RequestWithExtraProps = Request & {
10
+ rawBody?: Buffer;
11
+ };
12
+ /**
13
+ * Configuration options for creating an Express application.
14
+ *
15
+ * @property _console - Console object for logging (for testing purposes)
16
+ * @property _process - Process object for environment variables (for testing
17
+ * purposes)
18
+ * @property apiKeyEnvVarName - Environment variable name for the API key
19
+ */
20
+ export type FunctionConfig = {
21
+ _console?: typeof console;
22
+ _process?: typeof process;
23
+ apiKeyEnvVarName?: string;
24
+ };
25
+ /**
26
+ * Easily create a new scanner application with built-in authentication
27
+ * middleware. The middleware validates that the content-type is
28
+ * `application/json`, authenticates the request, and ensures the method is
29
+ * POST. Appropriate HTTP error codes are returned for various failure
30
+ * scenarios:
31
+ * - 400 (bad request)
32
+ * - 401 (unauthorized)
33
+ * - 404 (not found)
34
+ * - 405 (method not allowed)
35
+ * - 415 (unsupported media type)
36
+ * - 500 (internal server error)
37
+ *
38
+ * @remarks
39
+ * **Environment Variables:**
40
+ * - `LAMBDA_API_KEY` - Required. API key for authentication (configurable
41
+ * via `apiKeyEnvVarName`)
42
+ *
43
+ * **Authentication:**
44
+ * - Bearer token: `Authorization: Bearer <api_key>` (deprecated)
45
+ * - HMAC-SHA256: `Authorization: HMAC-SHA256 <digest>` (digest of request
46
+ * body)
47
+ */
48
+ export declare const createExpressApp: ({ _console, _process, apiKeyEnvVarName, }?: FunctionConfig) => (handler: RequestHandler) => import("express-serve-static-core").Express;
49
+ export * from './api';
50
+ export * from './download';
@@ -1,4 +1,18 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
2
16
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
17
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
18
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -12,30 +26,37 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
27
  };
14
28
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.createExpressApp = exports.createApiError = void 0;
29
+ exports.createExpressApp = void 0;
16
30
  const node_crypto_1 = __importDefault(require("node:crypto"));
17
- const fs_1 = __importDefault(require("fs"));
18
- const os_1 = __importDefault(require("os"));
19
- const path_1 = __importDefault(require("path"));
20
- const stream_1 = __importDefault(require("stream"));
21
- const util_1 = __importDefault(require("util"));
22
31
  const express_1 = __importDefault(require("express"));
23
32
  const body_parser_1 = __importDefault(require("body-parser"));
24
- const node_fetch_1 = __importDefault(require("node-fetch"));
25
33
  const safe_compare_1 = __importDefault(require("safe-compare"));
26
- const createApiError = ({ message, extraInfo, status = 500, }) => {
27
- const error = new Error(message);
28
- error.status = status;
29
- error.extraInfo = extraInfo;
30
- return error;
31
- };
32
- exports.createApiError = createApiError;
33
- const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _process = process, _unlinkFile = fs_1.default.promises.unlink, apiKeyEnvVarName = 'LAMBDA_API_KEY', requiredDownloadUrlParam = 'download_url', tmpDir = os_1.default.tmpdir(), xpiFilename = 'input.xpi', } = {}) => (handler) => {
34
+ const api_1 = require("./api");
35
+ /**
36
+ * Easily create a new scanner application with built-in authentication
37
+ * middleware. The middleware validates that the content-type is
38
+ * `application/json`, authenticates the request, and ensures the method is
39
+ * POST. Appropriate HTTP error codes are returned for various failure
40
+ * scenarios:
41
+ * - 400 (bad request)
42
+ * - 401 (unauthorized)
43
+ * - 404 (not found)
44
+ * - 405 (method not allowed)
45
+ * - 415 (unsupported media type)
46
+ * - 500 (internal server error)
47
+ *
48
+ * @remarks
49
+ * **Environment Variables:**
50
+ * - `LAMBDA_API_KEY` - Required. API key for authentication (configurable
51
+ * via `apiKeyEnvVarName`)
52
+ *
53
+ * **Authentication:**
54
+ * - Bearer token: `Authorization: Bearer <api_key>` (deprecated)
55
+ * - HMAC-SHA256: `Authorization: HMAC-SHA256 <digest>` (digest of request
56
+ * body)
57
+ */
58
+ const createExpressApp = ({ _console = console, _process = process, apiKeyEnvVarName = 'LAMBDA_API_KEY', } = {}) => (handler) => {
34
59
  const app = (0, express_1.default)();
35
- const allowedOrigin = _process.env.ALLOWED_ORIGIN || null;
36
- if (!allowedOrigin) {
37
- throw new Error('ALLOWED_ORIGIN is not set or unexpectedly empty!');
38
- }
39
60
  const apiKey = _process.env[apiKeyEnvVarName] || null;
40
61
  if (apiKey) {
41
62
  // Delete the env var to not expose it to add-ons.
@@ -52,25 +73,23 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
52
73
  };
53
74
  // Parse JSON body requests.
54
75
  app.use(body_parser_1.default.json(jsonOptions));
55
- // This middleware handles the common logic needed to expose our tools. It
56
- // adds a new `xpiFilepath` attribute to the Express request or returns an
57
- // error that will be converted to an API error by the error handler
58
- // middleware declared at the bottom of the middleware chain.
76
+ // Authentication middleware plus some extra checks.
59
77
  app.use((req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
60
78
  var _a;
79
+ // We only allow POST because the `handler` is passed to `app.post()`.
61
80
  const allowedMethods = ['POST'];
62
81
  if (req.headers['content-type'] !== 'application/json') {
63
82
  // We do not throw because we are inside a callback, so we pass an error
64
83
  // to the next middleware, which will be the error handler.
65
84
  // See: https://expressjs.com/en/guide/error-handling.html
66
- next((0, exports.createApiError)({
85
+ next((0, api_1.createApiError)({
67
86
  message: 'unsupported content type',
68
87
  status: 415,
69
88
  }));
70
89
  return;
71
90
  }
72
91
  if (!apiKey) {
73
- next((0, exports.createApiError)({
92
+ next((0, api_1.createApiError)({
74
93
  message: `api key must be set`,
75
94
  status: 500,
76
95
  }));
@@ -78,7 +97,7 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
78
97
  }
79
98
  const authorization = (_a = req.get('X-Forwarded-Authorization')) !== null && _a !== void 0 ? _a : req.get('Authorization');
80
99
  if (!authorization) {
81
- next((0, exports.createApiError)({
100
+ next((0, api_1.createApiError)({
82
101
  message: `missing authorization header`,
83
102
  status: 400,
84
103
  }));
@@ -90,7 +109,7 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
90
109
  .update(req.rawBody)
91
110
  .digest('hex');
92
111
  if (!(0, safe_compare_1.default)(`HMAC-SHA256 ${digest}`, authorization)) {
93
- next((0, exports.createApiError)({
112
+ next((0, api_1.createApiError)({
94
113
  message: 'authentication has failed',
95
114
  status: 401,
96
115
  }));
@@ -99,7 +118,7 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
99
118
  }
100
119
  else if (authorization.startsWith('Bearer ')) {
101
120
  if (!(0, safe_compare_1.default)(`Bearer ${apiKey}`, authorization)) {
102
- next((0, exports.createApiError)({
121
+ next((0, api_1.createApiError)({
103
122
  message: 'authentication has failed',
104
123
  status: 401,
105
124
  }));
@@ -107,7 +126,7 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
107
126
  }
108
127
  }
109
128
  else {
110
- next((0, exports.createApiError)({
129
+ next((0, api_1.createApiError)({
111
130
  message: 'unsupported authorization scheme',
112
131
  status: 400,
113
132
  }));
@@ -116,53 +135,16 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
116
135
  if (!allowedMethods
117
136
  .map((method) => method.toLowerCase())
118
137
  .includes(req.method.toLowerCase())) {
119
- next((0, exports.createApiError)({ message: 'method not allowed', status: 405 }));
120
- return;
121
- }
122
- const downloadURL = req.body[requiredDownloadUrlParam];
123
- if (!downloadURL) {
124
- next((0, exports.createApiError)({
125
- message: `missing "${requiredDownloadUrlParam}" parameter`,
126
- status: 400,
127
- }));
128
- return;
129
- }
130
- if (!downloadURL.startsWith(allowedOrigin)) {
131
- next((0, exports.createApiError)({ message: 'invalid origin', status: 400 }));
132
- return;
133
- }
134
- try {
135
- const xpiFilepath = path_1.default.join(tmpDir, xpiFilename);
136
- const streamPipeline = util_1.default.promisify(stream_1.default.pipeline);
137
- const response = yield _fetch(downloadURL);
138
- if (!response.ok) {
139
- throw new Error(`unexpected response ${response.statusText}`);
140
- }
141
- yield streamPipeline(response.body, fs_1.default.createWriteStream(xpiFilepath));
142
- req.xpiFilepath = xpiFilepath;
143
- // Add a listener that will run code after the response is sent.
144
- res.on('finish', () => {
145
- _unlinkFile(xpiFilepath).catch((error) => {
146
- _console.error(`_unlinkFile(): ${error}`);
147
- });
148
- });
149
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
150
- }
151
- catch (err) {
152
- next((0, exports.createApiError)({
153
- message: 'failed to download file',
154
- extraInfo: err.message,
155
- }));
138
+ next((0, api_1.createApiError)({ message: 'method not allowed', status: 405 }));
156
139
  return;
157
140
  }
158
141
  next();
159
142
  }));
160
- // We register the handler for the tool that will be exposed. This handler is
161
- // guaranteed to have a valid `xpiFilepath` stored on disk.
143
+ // We register the handler for the tool that will be exposed.
162
144
  app.post('/', handler);
163
145
  // NotFound handler.
164
146
  app.use((req, res, next) => {
165
- next((0, exports.createApiError)({ message: 'not found', status: 404 }));
147
+ next((0, api_1.createApiError)({ message: 'not found', status: 404 }));
166
148
  });
167
149
  // Error handler. Even though we are not using `next`, it must be kept
168
150
  // because the Express error handler signature requires 4 arguments.
@@ -180,3 +162,5 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
180
162
  return app;
181
163
  };
182
164
  exports.createExpressApp = createExpressApp;
165
+ __exportStar(require("./api"), exports);
166
+ __exportStar(require("./download"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "addons-scanner-utils",
3
- "version": "10.2.0",
3
+ "version": "12.0.0",
4
4
  "description": "Various addons related helpers to build CLIs.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -10,26 +10,21 @@
10
10
  "author": "Mozilla Add-ons Team",
11
11
  "license": "MPL-2.0",
12
12
  "dependencies": {
13
- "@types/yauzl": "2.10.3",
14
13
  "common-tags": "1.8.2",
15
14
  "first-chunk-stream": "3.0.0",
16
15
  "strip-bom-stream": "4.0.0",
17
16
  "upath": "2.0.1",
18
- "yauzl": "2.10.0"
17
+ "yauzl": "3.2.0"
19
18
  },
20
19
  "peerDependencies": {
21
20
  "body-parser": "2.2.2",
22
21
  "express": "5.2.1",
23
- "node-fetch": "2.6.11",
24
22
  "safe-compare": "1.1.4"
25
23
  },
26
24
  "peerDependenciesMeta": {
27
25
  "body-parser": {
28
26
  "optional": true
29
27
  },
30
- "node-fetch": {
31
- "optional": true
32
- },
33
28
  "express": {
34
29
  "optional": true
35
30
  },
@@ -42,10 +37,9 @@
42
37
  "@types/express": "5.0.6",
43
38
  "@types/jest": "^30.0.0",
44
39
  "@types/node": "^25.0.1",
45
- "@types/node-fetch": "^2.6.4",
46
40
  "@types/safe-compare": "^1.1.0",
47
- "@types/sinon": "^21.0.0",
48
41
  "@types/supertest": "^6.0.2",
42
+ "@types/yauzl": "2.10.3",
49
43
  "@typescript-eslint/eslint-plugin": "^8.46.2",
50
44
  "@typescript-eslint/parser": "^8.46.2",
51
45
  "body-parser": "2.2.2",
@@ -55,12 +49,10 @@
55
49
  "eslint-plugin-amo": "^2.0.0",
56
50
  "express": "5.2.1",
57
51
  "jest": "^30.2.0",
58
- "node-fetch": "2.6.11",
59
52
  "prettier": "3.8.1",
60
53
  "pretty-quick": "4.2.2",
61
54
  "rimraf": "^6.1.0",
62
55
  "safe-compare": "1.1.4",
63
- "sinon": "^21.0.0",
64
56
  "supertest": "^7.0.0",
65
57
  "ts-jest": "^29.0.0",
66
58
  "type-coverage": "^2.3.0",
@@ -1,29 +0,0 @@
1
- import fs from 'fs';
2
- import { Request, RequestHandler } from 'express';
3
- import fetch from 'node-fetch';
4
- type ApiError = Error & {
5
- extraInfo?: string;
6
- status?: number;
7
- };
8
- type CreateApiErrorParams = {
9
- message: string;
10
- extraInfo?: string;
11
- status?: number;
12
- };
13
- export declare const createApiError: ({ message, extraInfo, status, }: CreateApiErrorParams) => ApiError;
14
- export type RequestWithExtraProps = Request & {
15
- xpiFilepath?: string;
16
- rawBody?: Buffer;
17
- };
18
- export type FunctionConfig = {
19
- _console?: typeof console;
20
- _fetch?: typeof fetch;
21
- _process?: typeof process;
22
- _unlinkFile?: typeof fs.promises.unlink;
23
- apiKeyEnvVarName?: string;
24
- requiredDownloadUrlParam?: string;
25
- tmpDir?: string;
26
- xpiFilename?: string;
27
- };
28
- export declare const createExpressApp: ({ _console, _fetch, _process, _unlinkFile, apiKeyEnvVarName, requiredDownloadUrlParam, tmpDir, xpiFilename, }?: FunctionConfig) => (handler: RequestHandler) => import("express-serve-static-core").Express;
29
- export {};