addons-scanner-utils 13.0.0 → 14.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.
@@ -1,27 +1,19 @@
1
+ import { MakeJWTConfig } from './auth';
1
2
  /**
2
- * Error object with HTTP status code and optional extra information.
3
+ * Parameters for patching a scanner result.
3
4
  *
4
- * @property message - Error message
5
- * @property extraInfo - Additional error details
6
- * @property status - HTTP status code
5
+ * @property url - URL to PATCH
6
+ * @property payload - JSON body to send
7
7
  */
8
- export type ApiError = Error & {
9
- extraInfo?: string;
10
- status: number;
8
+ export type PatchScannerResultParams = MakeJWTConfig & {
9
+ url: string;
10
+ payload: Record<string, unknown>;
11
11
  };
12
12
  /**
13
- * Parameters for creating an API error.
13
+ * PATCH a scanner result to the AMO API, authenticating with a JWT token
14
+ * computed from the `AMO_JWT_ISS_KEY` and `AMO_JWT_SECRET` environment
15
+ * variables.
14
16
  *
15
- * @property message - Error message
16
- * @property extraInfo - Additional error details
17
- * @property status - HTTP status code (default: 500)
17
+ * @throws AMOError if the response is not ok
18
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;
19
+ export declare const patchScannerResult: ({ url, payload, env, }: PatchScannerResultParams) => Promise<void>;
@@ -1,13 +1,35 @@
1
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
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createApiError = void 0;
12
+ exports.patchScannerResult = void 0;
13
+ const error_1 = require("./error");
14
+ const auth_1 = require("./auth");
4
15
  /**
5
- * Create API error object with status code and extra information.
16
+ * PATCH a scanner result to the AMO API, authenticating with a JWT token
17
+ * computed from the `AMO_JWT_ISS_KEY` and `AMO_JWT_SECRET` environment
18
+ * variables.
19
+ *
20
+ * @throws AMOError if the response is not ok
6
21
  */
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;
22
+ const patchScannerResult = (_a) => __awaiter(void 0, [_a], void 0, function* ({ url, payload, env, }) {
23
+ const response = yield fetch(url, {
24
+ method: 'PATCH',
25
+ headers: {
26
+ 'Content-Type': 'application/json',
27
+ Authorization: `JWT ${(0, auth_1.makeJWT)({ env })}`,
28
+ },
29
+ body: JSON.stringify(payload),
30
+ });
31
+ if (!response.ok) {
32
+ throw new error_1.AMOError(`unexpected response: ${response.statusText}`);
33
+ }
34
+ });
35
+ exports.patchScannerResult = patchScannerResult;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Configuration for makeJWT.
3
+ *
4
+ * @property env - Environment variables object (default: process.env)
5
+ */
6
+ export type MakeJWTConfig = {
7
+ env?: NodeJS.ProcessEnv;
8
+ };
9
+ /**
10
+ * Create a signed JWT token for AMO API authentication using the
11
+ * `AMO_JWT_ISS_KEY` and `AMO_JWT_SECRET` environment variables.
12
+ *
13
+ * @returns A signed HS256 JWT string
14
+ * @throws Error if the required environment variables are not set
15
+ */
16
+ export declare const makeJWT: ({ env }?: MakeJWTConfig) => string;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeJWT = void 0;
7
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
+ const JWT_EXPIRY_SECONDS = 60;
9
+ /**
10
+ * Create a signed JWT token for AMO API authentication using the
11
+ * `AMO_JWT_ISS_KEY` and `AMO_JWT_SECRET` environment variables.
12
+ *
13
+ * @returns A signed HS256 JWT string
14
+ * @throws Error if the required environment variables are not set
15
+ */
16
+ const makeJWT = ({ env = process.env } = {}) => {
17
+ const issKey = env.AMO_JWT_ISS_KEY;
18
+ const secret = env.AMO_JWT_SECRET;
19
+ if (!issKey) {
20
+ throw new Error('AMO_JWT_ISS_KEY environment variable is not set');
21
+ }
22
+ if (!secret) {
23
+ throw new Error('AMO_JWT_SECRET environment variable is not set');
24
+ }
25
+ const issuedAt = Math.floor(Date.now() / 1000);
26
+ const payload = {
27
+ iss: issKey,
28
+ jti: Math.random().toString(),
29
+ iat: issuedAt,
30
+ exp: issuedAt + JWT_EXPIRY_SECONDS,
31
+ };
32
+ return jsonwebtoken_1.default.sign(payload, secret, { algorithm: 'HS256' });
33
+ };
34
+ exports.makeJWT = makeJWT;
@@ -1,19 +1,42 @@
1
+ import { MakeJWTConfig } from './auth';
1
2
  export declare const DEFAULT_DOWNLOAD_FILENAME = "input.xpi";
2
3
  /**
3
4
  * Error thrown when file download operations fail.
4
5
  *
5
- * @property status - HTTP status code
6
6
  * @property extraInfo - Additional error details
7
+ * @property status - HTTP status code to be used when returning the error
8
+ * response to the client. This is not the HTTP status code received when trying
9
+ * to download a file.
7
10
  */
8
11
  export declare class DownloadFileError extends Error {
9
12
  status: number;
10
13
  extraInfo?: string;
11
14
  constructor(message: string, extraInfo?: string, status?: number);
12
15
  /**
13
- * Convert this error to ApiError format.
16
+ * Convert this error to AppError format.
14
17
  */
15
- toApiError(): import("./api").ApiError;
18
+ toAppError(): import("./error").AppError;
16
19
  }
20
+ /**
21
+ * Parameters for downloading a file from the AMO API with JWT authentication.
22
+ *
23
+ * @property downloadURL - URL to download from
24
+ * @property tmpDir - Temporary directory for download (default: os.tmpdir())
25
+ * @property filename - Downloaded file name (default: 'input.xpi')
26
+ */
27
+ export type DownloadFileParams = MakeJWTConfig & {
28
+ downloadURL: string;
29
+ tmpDir?: string;
30
+ filename?: string;
31
+ };
32
+ /**
33
+ * Download a file from the AMO API, authenticating with a JWT token computed
34
+ * from the `AMO_JWT_ISS_KEY` and `AMO_JWT_SECRET` environment variables.
35
+ *
36
+ * @returns Promise resolving to the file path of the downloaded file
37
+ * @throws DownloadFileError if the download fails
38
+ */
39
+ export declare const downloadFile: ({ downloadURL, tmpDir, filename, env, }: DownloadFileParams) => Promise<string>;
17
40
  /**
18
41
  * Parameters for downloading a file upload.
19
42
  *
@@ -12,19 +12,22 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.downloadFileUpload = exports.DownloadFileError = exports.DEFAULT_DOWNLOAD_FILENAME = void 0;
15
+ exports.downloadFileUpload = exports.downloadFile = exports.DownloadFileError = exports.DEFAULT_DOWNLOAD_FILENAME = void 0;
16
16
  const node_os_1 = __importDefault(require("node:os"));
17
17
  const node_path_1 = __importDefault(require("node:path"));
18
18
  const node_fs_1 = require("node:fs");
19
19
  const node_stream_1 = require("node:stream");
20
20
  const promises_1 = require("node:stream/promises");
21
- const api_1 = require("./api");
21
+ const error_1 = require("./error");
22
+ const auth_1 = require("./auth");
22
23
  exports.DEFAULT_DOWNLOAD_FILENAME = 'input.xpi';
23
24
  /**
24
25
  * Error thrown when file download operations fail.
25
26
  *
26
- * @property status - HTTP status code
27
27
  * @property extraInfo - Additional error details
28
+ * @property status - HTTP status code to be used when returning the error
29
+ * response to the client. This is not the HTTP status code received when trying
30
+ * to download a file.
28
31
  */
29
32
  class DownloadFileError extends Error {
30
33
  constructor(message, extraInfo, status = 500) {
@@ -34,10 +37,10 @@ class DownloadFileError extends Error {
34
37
  this.extraInfo = extraInfo;
35
38
  }
36
39
  /**
37
- * Convert this error to ApiError format.
40
+ * Convert this error to AppError format.
38
41
  */
39
- toApiError() {
40
- return (0, api_1.createApiError)({
42
+ toAppError() {
43
+ return (0, error_1.createAppError)({
41
44
  message: this.message,
42
45
  extraInfo: this.extraInfo,
43
46
  status: this.status,
@@ -45,18 +48,9 @@ class DownloadFileError extends Error {
45
48
  }
46
49
  }
47
50
  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
- }
51
+ const fetchToFile = (downloadURL, tmpDir, filename, headers) => __awaiter(void 0, void 0, void 0, function* () {
58
52
  try {
59
- const response = yield fetch(downloadURL);
53
+ const response = yield fetch(downloadURL, { headers });
60
54
  if (!response.ok || !response.body) {
61
55
  throw new DownloadFileError(`unexpected response: ${response.statusText}`);
62
56
  }
@@ -72,4 +66,30 @@ const downloadFileUpload = (_a) => __awaiter(void 0, [_a], void 0, function* ({
72
66
  throw new DownloadFileError('failed to download file', message);
73
67
  }
74
68
  });
69
+ /**
70
+ * Download a file from the AMO API, authenticating with a JWT token computed
71
+ * from the `AMO_JWT_ISS_KEY` and `AMO_JWT_SECRET` environment variables.
72
+ *
73
+ * @returns Promise resolving to the file path of the downloaded file
74
+ * @throws DownloadFileError if the download fails
75
+ */
76
+ const downloadFile = (_a) => __awaiter(void 0, [_a], void 0, function* ({ downloadURL, tmpDir = node_os_1.default.tmpdir(), filename = exports.DEFAULT_DOWNLOAD_FILENAME, env, }) {
77
+ const token = (0, auth_1.makeJWT)({ env });
78
+ return fetchToFile(downloadURL, tmpDir, filename, {
79
+ Authorization: `JWT ${token}`,
80
+ });
81
+ });
82
+ exports.downloadFile = downloadFile;
83
+ /**
84
+ * Download a file from a URL to a temporary location.
85
+ *
86
+ * @returns Promise resolving to the file path of the downloaded file
87
+ * @throws DownloadFileError if the download fails or URL origin doesn't match
88
+ */
89
+ const downloadFileUpload = (_a) => __awaiter(void 0, [_a], void 0, function* ({ downloadURL, allowedOrigin, tmpDir = node_os_1.default.tmpdir(), filename = exports.DEFAULT_DOWNLOAD_FILENAME, }) {
90
+ if (!downloadURL.startsWith(`${allowedOrigin}/`)) {
91
+ throw new DownloadFileError(`download URL does not match allowed origin: ${allowedOrigin}`, undefined, 400);
92
+ }
93
+ return fetchToFile(downloadURL, tmpDir, filename);
94
+ });
75
95
  exports.downloadFileUpload = downloadFileUpload;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Error object with HTTP status code and optional extra information intended
3
+ * to be used by the error handler defined in `src/functions/index.ts`.
4
+ *
5
+ * @property message - Error message
6
+ * @property extraInfo - Additional error details
7
+ * @property status - HTTP status code
8
+ */
9
+ export type AppError = Error & {
10
+ extraInfo?: string;
11
+ status: number;
12
+ };
13
+ /**
14
+ * Parameters for creating an app error.
15
+ *
16
+ * @property message - Error message
17
+ * @property extraInfo - Additional error details
18
+ * @property status - HTTP status code (default: 500)
19
+ */
20
+ export type CreateAppErrorParams = {
21
+ message: string;
22
+ extraInfo?: string;
23
+ status?: number;
24
+ };
25
+ /**
26
+ * Create an app error object with status code and extra information.
27
+ */
28
+ export declare const createAppError: ({ message, extraInfo, status, }: CreateAppErrorParams) => AppError;
29
+ /**
30
+ * Error object used when interactions with the AMO API led to errors.
31
+ */
32
+ export declare class AMOError extends Error {
33
+ constructor(message: string);
34
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AMOError = exports.createAppError = void 0;
4
+ /**
5
+ * Create an app error object with status code and extra information.
6
+ */
7
+ const createAppError = ({ message, extraInfo, status = 500, }) => {
8
+ const error = new Error(message);
9
+ error.status = status;
10
+ error.extraInfo = extraInfo;
11
+ return error;
12
+ };
13
+ exports.createAppError = createAppError;
14
+ /**
15
+ * Error object used when interactions with the AMO API led to errors.
16
+ */
17
+ class AMOError extends Error {
18
+ constructor(message) {
19
+ super(message);
20
+ this.name = 'AMOError';
21
+ }
22
+ }
23
+ exports.AMOError = AMOError;
@@ -47,4 +47,6 @@ export type FunctionConfig = {
47
47
  */
48
48
  export declare const createExpressApp: ({ _console, _process, apiKeyEnvVarName, }?: FunctionConfig) => (handler: RequestHandler) => import("express-serve-static-core").Express;
49
49
  export * from './api';
50
+ export * from './auth';
50
51
  export * from './download';
52
+ export * from './error';
@@ -29,9 +29,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.createExpressApp = void 0;
30
30
  const node_crypto_1 = __importDefault(require("node:crypto"));
31
31
  const express_1 = __importDefault(require("express"));
32
- const body_parser_1 = __importDefault(require("body-parser"));
33
32
  const safe_compare_1 = __importDefault(require("safe-compare"));
34
- const api_1 = require("./api");
33
+ const error_1 = require("./error");
35
34
  /**
36
35
  * Easily create a new scanner application with built-in authentication
37
36
  * middleware. The middleware validates that the content-type is
@@ -72,7 +71,7 @@ const createExpressApp = ({ _console = console, _process = process, apiKeyEnvVar
72
71
  },
73
72
  };
74
73
  // Parse JSON body requests.
75
- app.use(body_parser_1.default.json(jsonOptions));
74
+ app.use(express_1.default.json(jsonOptions));
76
75
  // Authentication middleware plus some extra checks.
77
76
  app.use((req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
78
77
  var _a;
@@ -82,14 +81,14 @@ const createExpressApp = ({ _console = console, _process = process, apiKeyEnvVar
82
81
  // We do not throw because we are inside a callback, so we pass an error
83
82
  // to the next middleware, which will be the error handler.
84
83
  // See: https://expressjs.com/en/guide/error-handling.html
85
- next((0, api_1.createApiError)({
84
+ next((0, error_1.createAppError)({
86
85
  message: 'unsupported content type',
87
86
  status: 415,
88
87
  }));
89
88
  return;
90
89
  }
91
90
  if (!apiKey) {
92
- next((0, api_1.createApiError)({
91
+ next((0, error_1.createAppError)({
93
92
  message: `api key must be set`,
94
93
  status: 500,
95
94
  }));
@@ -97,7 +96,7 @@ const createExpressApp = ({ _console = console, _process = process, apiKeyEnvVar
97
96
  }
98
97
  const authorization = (_a = req.get('X-Forwarded-Authorization')) !== null && _a !== void 0 ? _a : req.get('Authorization');
99
98
  if (!authorization) {
100
- next((0, api_1.createApiError)({
99
+ next((0, error_1.createAppError)({
101
100
  message: `missing authorization header`,
102
101
  status: 400,
103
102
  }));
@@ -109,7 +108,7 @@ const createExpressApp = ({ _console = console, _process = process, apiKeyEnvVar
109
108
  .update(req.rawBody)
110
109
  .digest('hex');
111
110
  if (!(0, safe_compare_1.default)(`HMAC-SHA256 ${digest}`, authorization)) {
112
- next((0, api_1.createApiError)({
111
+ next((0, error_1.createAppError)({
113
112
  message: 'authentication has failed',
114
113
  status: 401,
115
114
  }));
@@ -118,7 +117,7 @@ const createExpressApp = ({ _console = console, _process = process, apiKeyEnvVar
118
117
  }
119
118
  else if (authorization.startsWith('Bearer ')) {
120
119
  if (!(0, safe_compare_1.default)(`Bearer ${apiKey}`, authorization)) {
121
- next((0, api_1.createApiError)({
120
+ next((0, error_1.createAppError)({
122
121
  message: 'authentication has failed',
123
122
  status: 401,
124
123
  }));
@@ -126,7 +125,7 @@ const createExpressApp = ({ _console = console, _process = process, apiKeyEnvVar
126
125
  }
127
126
  }
128
127
  else {
129
- next((0, api_1.createApiError)({
128
+ next((0, error_1.createAppError)({
130
129
  message: 'unsupported authorization scheme',
131
130
  status: 400,
132
131
  }));
@@ -135,7 +134,7 @@ const createExpressApp = ({ _console = console, _process = process, apiKeyEnvVar
135
134
  if (!allowedMethods
136
135
  .map((method) => method.toLowerCase())
137
136
  .includes(req.method.toLowerCase())) {
138
- next((0, api_1.createApiError)({ message: 'method not allowed', status: 405 }));
137
+ next((0, error_1.createAppError)({ message: 'method not allowed', status: 405 }));
139
138
  return;
140
139
  }
141
140
  next();
@@ -144,7 +143,7 @@ const createExpressApp = ({ _console = console, _process = process, apiKeyEnvVar
144
143
  app.post('/', handler);
145
144
  // NotFound handler.
146
145
  app.use((req, res, next) => {
147
- next((0, api_1.createApiError)({ message: 'not found', status: 404 }));
146
+ next((0, error_1.createAppError)({ message: 'not found', status: 404 }));
148
147
  });
149
148
  // Error handler. Even though we are not using `next`, it must be kept
150
149
  // because the Express error handler signature requires 4 arguments.
@@ -163,4 +162,6 @@ const createExpressApp = ({ _console = console, _process = process, apiKeyEnvVar
163
162
  };
164
163
  exports.createExpressApp = createExpressApp;
165
164
  __exportStar(require("./api"), exports);
165
+ __exportStar(require("./auth"), exports);
166
166
  __exportStar(require("./download"), exports);
167
+ __exportStar(require("./error"), exports);
@@ -81,7 +81,6 @@ class Directory extends base_1.IOBase {
81
81
  let content = '';
82
82
  readStream.on('readable', () => {
83
83
  let chunk;
84
- // eslint-disable-next-line no-cond-assign
85
84
  while ((chunk = readStream.read()) !== null) {
86
85
  content += chunk.toString();
87
86
  }
@@ -21,7 +21,6 @@ const readStringFromStream = (readStream, encoding) => {
21
21
  let content = '';
22
22
  readStream.on('readable', () => {
23
23
  let chunk;
24
- // eslint-disable-next-line no-cond-assign
25
24
  while ((chunk = readStream.read()) !== null) {
26
25
  content += chunk.toString(encoding);
27
26
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "addons-scanner-utils",
3
- "version": "13.0.0",
3
+ "version": "14.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",
@@ -12,19 +12,16 @@
12
12
  "dependencies": {
13
13
  "common-tags": "1.8.2",
14
14
  "first-chunk-stream": "3.0.0",
15
+ "jsonwebtoken": "^9.0.3",
15
16
  "strip-bom-stream": "4.0.0",
16
17
  "upath": "2.0.1",
17
- "yauzl": "3.2.0"
18
+ "yauzl": "3.2.1"
18
19
  },
19
20
  "peerDependencies": {
20
- "body-parser": "2.2.2",
21
21
  "express": "5.2.1",
22
22
  "safe-compare": "1.1.4"
23
23
  },
24
24
  "peerDependenciesMeta": {
25
- "body-parser": {
26
- "optional": true
27
- },
28
25
  "express": {
29
26
  "optional": true
30
27
  },
@@ -36,15 +33,15 @@
36
33
  "@types/common-tags": "^1.8.0",
37
34
  "@types/express": "5.0.6",
38
35
  "@types/jest": "^30.0.0",
36
+ "@types/jsonwebtoken": "^9.0.10",
39
37
  "@types/node": "^25.0.1",
40
38
  "@types/safe-compare": "^1.1.0",
41
39
  "@types/supertest": "^7.2.0",
42
40
  "@types/yauzl": "2.10.3",
43
41
  "@typescript-eslint/eslint-plugin": "^8.46.2",
44
42
  "@typescript-eslint/parser": "^8.46.2",
45
- "body-parser": "2.2.2",
46
- "eslint": "^8.1.0",
47
- "eslint-config-amo": "^6.1.0",
43
+ "eslint": "^9.0.0",
44
+ "eslint-config-amo": "^8.0.0",
48
45
  "eslint-import-resolver-typescript": "^4.4.4",
49
46
  "eslint-plugin-amo": "^3.0.0",
50
47
  "express": "5.2.1",
@@ -59,7 +56,7 @@
59
56
  "typescript": "^5.9.3"
60
57
  },
61
58
  "scripts": {
62
- "eslint": "eslint --ext ts --ext js src/",
59
+ "eslint": "eslint src/",
63
60
  "lint": "npm run eslint",
64
61
  "prepack": "rimraf dist/ && tsc --outDir dist/ && rimraf -g 'dist/**/*.spec.*' 'dist/*.spec.*'",
65
62
  "prettier": "prettier --write '**'",