addons-scanner-utils 10.2.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,25 +50,23 @@ 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* () {
60
55
  var _a;
56
+ // We only allow POST because the `handler` is passed to `app.post()`.
61
57
  const allowedMethods = ['POST'];
62
58
  if (req.headers['content-type'] !== 'application/json') {
63
59
  // We do not throw because we are inside a callback, so we pass an error
64
60
  // to the next middleware, which will be the error handler.
65
61
  // See: https://expressjs.com/en/guide/error-handling.html
66
- next((0, exports.createApiError)({
62
+ next((0, api_1.createApiError)({
67
63
  message: 'unsupported content type',
68
64
  status: 415,
69
65
  }));
70
66
  return;
71
67
  }
72
68
  if (!apiKey) {
73
- next((0, exports.createApiError)({
69
+ next((0, api_1.createApiError)({
74
70
  message: `api key must be set`,
75
71
  status: 500,
76
72
  }));
@@ -78,7 +74,7 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
78
74
  }
79
75
  const authorization = (_a = req.get('X-Forwarded-Authorization')) !== null && _a !== void 0 ? _a : req.get('Authorization');
80
76
  if (!authorization) {
81
- next((0, exports.createApiError)({
77
+ next((0, api_1.createApiError)({
82
78
  message: `missing authorization header`,
83
79
  status: 400,
84
80
  }));
@@ -90,7 +86,7 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
90
86
  .update(req.rawBody)
91
87
  .digest('hex');
92
88
  if (!(0, safe_compare_1.default)(`HMAC-SHA256 ${digest}`, authorization)) {
93
- next((0, exports.createApiError)({
89
+ next((0, api_1.createApiError)({
94
90
  message: 'authentication has failed',
95
91
  status: 401,
96
92
  }));
@@ -99,7 +95,7 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
99
95
  }
100
96
  else if (authorization.startsWith('Bearer ')) {
101
97
  if (!(0, safe_compare_1.default)(`Bearer ${apiKey}`, authorization)) {
102
- next((0, exports.createApiError)({
98
+ next((0, api_1.createApiError)({
103
99
  message: 'authentication has failed',
104
100
  status: 401,
105
101
  }));
@@ -107,7 +103,7 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
107
103
  }
108
104
  }
109
105
  else {
110
- next((0, exports.createApiError)({
106
+ next((0, api_1.createApiError)({
111
107
  message: 'unsupported authorization scheme',
112
108
  status: 400,
113
109
  }));
@@ -116,53 +112,16 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
116
112
  if (!allowedMethods
117
113
  .map((method) => method.toLowerCase())
118
114
  .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
- }));
115
+ next((0, api_1.createApiError)({ message: 'method not allowed', status: 405 }));
156
116
  return;
157
117
  }
158
118
  next();
159
119
  }));
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.
120
+ // We register the handler for the tool that will be exposed.
162
121
  app.post('/', handler);
163
122
  // NotFound handler.
164
123
  app.use((req, res, next) => {
165
- next((0, exports.createApiError)({ message: 'not found', status: 404 }));
124
+ next((0, api_1.createApiError)({ message: 'not found', status: 404 }));
166
125
  });
167
126
  // Error handler. Even though we are not using `next`, it must be kept
168
127
  // because the Express error handler signature requires 4 arguments.
@@ -180,3 +139,5 @@ const createExpressApp = ({ _console = console, _fetch = node_fetch_1.default, _
180
139
  return app;
181
140
  };
182
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.2.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
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 {};