addons-scanner-utils 10.1.0 → 11.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
@@ -0,0 +1,10 @@
1
+ export type ApiError = Error & {
2
+ extraInfo?: string;
3
+ status: number;
4
+ };
5
+ export type CreateApiErrorParams = {
6
+ message: string;
7
+ extraInfo?: string;
8
+ status?: number;
9
+ };
10
+ export declare const createApiError: ({ message, extraInfo, status, }: CreateApiErrorParams) => ApiError;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createApiError = void 0;
4
+ const createApiError = ({ message, extraInfo, status = 500, }) => {
5
+ const error = new Error(message);
6
+ error.status = status;
7
+ error.extraInfo = extraInfo;
8
+ return error;
9
+ };
10
+ exports.createApiError = createApiError;
@@ -0,0 +1,14 @@
1
+ export declare const DEFAULT_DOWNLOAD_FILENAME = "input.xpi";
2
+ export declare class DownloadFileError extends Error {
3
+ status: number;
4
+ extraInfo?: string;
5
+ constructor(message: string, extraInfo?: string, status?: number);
6
+ toApiError(): import("./api").ApiError;
7
+ }
8
+ export type DownloadFileUploadParams = {
9
+ downloadURL: string;
10
+ allowedOrigin: string;
11
+ tmpDir?: string;
12
+ filename?: string;
13
+ };
14
+ export declare const downloadFileUpload: ({ downloadURL, allowedOrigin, tmpDir, filename, }: DownloadFileUploadParams) => Promise<string>;
@@ -0,0 +1,60 @@
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
+ class DownloadFileError extends Error {
24
+ constructor(message, extraInfo, status = 500) {
25
+ super(message);
26
+ this.name = 'DownloadFileError';
27
+ this.status = status;
28
+ this.extraInfo = extraInfo;
29
+ }
30
+ toApiError() {
31
+ return (0, api_1.createApiError)({
32
+ message: this.message,
33
+ extraInfo: this.extraInfo,
34
+ status: this.status,
35
+ });
36
+ }
37
+ }
38
+ exports.DownloadFileError = DownloadFileError;
39
+ const downloadFileUpload = (_a) => __awaiter(void 0, [_a], void 0, function* ({ downloadURL, allowedOrigin, tmpDir = node_os_1.default.tmpdir(), filename = exports.DEFAULT_DOWNLOAD_FILENAME, }) {
40
+ if (!downloadURL.startsWith(`${allowedOrigin}/`)) {
41
+ throw new DownloadFileError(`download URL does not match allowed origin: ${allowedOrigin}`, undefined, 400);
42
+ }
43
+ try {
44
+ const response = yield fetch(downloadURL);
45
+ if (!response.ok || !response.body) {
46
+ throw new DownloadFileError(`unexpected response: ${response.statusText}`);
47
+ }
48
+ const filepath = node_path_1.default.join(tmpDir, filename);
49
+ yield (0, promises_1.pipeline)(node_stream_1.Readable.fromWeb(response.body), (0, node_fs_1.createWriteStream)(filepath));
50
+ return filepath;
51
+ }
52
+ catch (err) {
53
+ if (err instanceof DownloadFileError) {
54
+ throw err;
55
+ }
56
+ const message = err instanceof Error ? err.message : String(err);
57
+ throw new DownloadFileError('failed to download file', message);
58
+ }
59
+ });
60
+ exports.downloadFileUpload = downloadFileUpload;
@@ -0,0 +1,12 @@
1
+ import { Request, RequestHandler } from 'express';
2
+ export type RequestWithExtraProps = Request & {
3
+ rawBody?: Buffer;
4
+ };
5
+ export type FunctionConfig = {
6
+ _console?: typeof console;
7
+ _process?: typeof process;
8
+ apiKeyEnvVarName?: string;
9
+ };
10
+ export declare const createExpressApp: ({ _console, _process, apiKeyEnvVarName, }?: FunctionConfig) => (handler: RequestHandler) => import("express-serve-static-core").Express;
11
+ export * from './api';
12
+ 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,14 @@ 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
+ const createExpressApp = ({ _console = console, _process = process, apiKeyEnvVarName = 'LAMBDA_API_KEY', } = {}) => (handler) => {
34
36
  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
37
  const apiKey = _process.env[apiKeyEnvVarName] || null;
40
38
  if (apiKey) {
41
39
  // Delete the env var to not expose it to add-ons.
@@ -52,44 +50,43 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
52
50
  };
53
51
  // Parse JSON body requests.
54
52
  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.
53
+ // Authentication middleware plus some extra checks.
59
54
  app.use((req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
55
+ var _a;
56
+ // We only allow POST because the `handler` is passed to `app.post()`.
60
57
  const allowedMethods = ['POST'];
61
58
  if (req.headers['content-type'] !== 'application/json') {
62
59
  // We do not throw because we are inside a callback, so we pass an error
63
60
  // to the next middleware, which will be the error handler.
64
61
  // See: https://expressjs.com/en/guide/error-handling.html
65
- next((0, exports.createApiError)({
62
+ next((0, api_1.createApiError)({
66
63
  message: 'unsupported content type',
67
64
  status: 415,
68
65
  }));
69
66
  return;
70
67
  }
71
68
  if (!apiKey) {
72
- next((0, exports.createApiError)({
69
+ next((0, api_1.createApiError)({
73
70
  message: `api key must be set`,
74
71
  status: 500,
75
72
  }));
76
73
  return;
77
74
  }
78
- if (!req.get('authorization')) {
79
- next((0, exports.createApiError)({
75
+ const authorization = (_a = req.get('X-Forwarded-Authorization')) !== null && _a !== void 0 ? _a : req.get('Authorization');
76
+ if (!authorization) {
77
+ next((0, api_1.createApiError)({
80
78
  message: `missing authorization header`,
81
79
  status: 400,
82
80
  }));
83
81
  return;
84
82
  }
85
- const authorization = String(req.get('authorization'));
86
83
  if (authorization.startsWith('HMAC-SHA256 ') && req.rawBody) {
87
84
  const digest = node_crypto_1.default
88
85
  .createHmac('sha256', apiKey)
89
86
  .update(req.rawBody)
90
87
  .digest('hex');
91
88
  if (!(0, safe_compare_1.default)(`HMAC-SHA256 ${digest}`, authorization)) {
92
- next((0, exports.createApiError)({
89
+ next((0, api_1.createApiError)({
93
90
  message: 'authentication has failed',
94
91
  status: 401,
95
92
  }));
@@ -98,7 +95,7 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
98
95
  }
99
96
  else if (authorization.startsWith('Bearer ')) {
100
97
  if (!(0, safe_compare_1.default)(`Bearer ${apiKey}`, authorization)) {
101
- next((0, exports.createApiError)({
98
+ next((0, api_1.createApiError)({
102
99
  message: 'authentication has failed',
103
100
  status: 401,
104
101
  }));
@@ -106,7 +103,7 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
106
103
  }
107
104
  }
108
105
  else {
109
- next((0, exports.createApiError)({
106
+ next((0, api_1.createApiError)({
110
107
  message: 'unsupported authorization scheme',
111
108
  status: 400,
112
109
  }));
@@ -115,53 +112,16 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
115
112
  if (!allowedMethods
116
113
  .map((method) => method.toLowerCase())
117
114
  .includes(req.method.toLowerCase())) {
118
- next((0, exports.createApiError)({ message: 'method not allowed', status: 405 }));
119
- return;
120
- }
121
- const downloadURL = req.body[requiredDownloadUrlParam];
122
- if (!downloadURL) {
123
- next((0, exports.createApiError)({
124
- message: `missing "${requiredDownloadUrlParam}" parameter`,
125
- status: 400,
126
- }));
127
- return;
128
- }
129
- if (!downloadURL.startsWith(allowedOrigin)) {
130
- next((0, exports.createApiError)({ message: 'invalid origin', status: 400 }));
131
- return;
132
- }
133
- try {
134
- const xpiFilepath = path_1.default.join(tmpDir, xpiFilename);
135
- const streamPipeline = util_1.default.promisify(stream_1.default.pipeline);
136
- const response = yield _fetch(downloadURL);
137
- if (!response.ok) {
138
- throw new Error(`unexpected response ${response.statusText}`);
139
- }
140
- yield streamPipeline(response.body, fs_1.default.createWriteStream(xpiFilepath));
141
- req.xpiFilepath = xpiFilepath;
142
- // Add a listener that will run code after the response is sent.
143
- res.on('finish', () => {
144
- _unlinkFile(xpiFilepath).catch((error) => {
145
- _console.error(`_unlinkFile(): ${error}`);
146
- });
147
- });
148
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
149
- }
150
- catch (err) {
151
- next((0, exports.createApiError)({
152
- message: 'failed to download file',
153
- extraInfo: err.message,
154
- }));
115
+ next((0, api_1.createApiError)({ message: 'method not allowed', status: 405 }));
155
116
  return;
156
117
  }
157
118
  next();
158
119
  }));
159
- // We register the handler for the tool that will be exposed. This handler is
160
- // guaranteed to have a valid `xpiFilepath` stored on disk.
120
+ // We register the handler for the tool that will be exposed.
161
121
  app.post('/', handler);
162
122
  // NotFound handler.
163
123
  app.use((req, res, next) => {
164
- next((0, exports.createApiError)({ message: 'not found', status: 404 }));
124
+ next((0, api_1.createApiError)({ message: 'not found', status: 404 }));
165
125
  });
166
126
  // Error handler. Even though we are not using `next`, it must be kept
167
127
  // because the Express error handler signature requires 4 arguments.
@@ -179,3 +139,5 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
179
139
  return app;
180
140
  };
181
141
  exports.createExpressApp = createExpressApp;
142
+ __exportStar(require("./api"), exports);
143
+ __exportStar(require("./download"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "addons-scanner-utils",
3
- "version": "10.1.0",
3
+ "version": "11.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,7 +10,6 @@
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",
@@ -20,16 +19,12 @@
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
- "prettier": "3.8.0",
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 {};