@balena/pinejs 14.64.2-build-fisehara-utilise-env-parser-module-febed128fc23b88aaf491563740112abc7abaa18-1 → 14.65.0-build-add-basic-permission-middleware-and-tests-6a47a9a209312171c0f77e5e8deeb16a798a3a6f-1

Sign up to get free protection for your applications and to get access to all the features.
@@ -53,7 +53,7 @@ export const cache = {
53
53
  apiKeyActorId: false as CacheOpts,
54
54
  };
55
55
 
56
- import { boolVar, intVar } from '@balena/env-parsing';
56
+ import { boolVar } from '@balena/env-parsing';
57
57
  import * as memoize from 'memoizee';
58
58
  import memoizeWeak = require('memoizee/weak');
59
59
  export const createCache = <T extends (...args: any[]) => any>(
@@ -82,7 +82,17 @@ export const createCache = <T extends (...args: any[]) => any>(
82
82
  });
83
83
  };
84
84
 
85
- const timeoutMS = intVar('TRANSACTION_TIMEOUT_MS', 10000);
85
+ let timeoutMS: number;
86
+ if (process.env.TRANSACTION_TIMEOUT_MS) {
87
+ timeoutMS = parseInt(process.env.TRANSACTION_TIMEOUT_MS, 10);
88
+ if (Number.isNaN(timeoutMS) || timeoutMS <= 0) {
89
+ throw new Error(
90
+ `Invalid valid for TRANSACTION_TIMEOUT_MS: ${process.env.TRANSACTION_TIMEOUT_MS}`,
91
+ );
92
+ }
93
+ } else {
94
+ timeoutMS = 10000;
95
+ }
86
96
 
87
97
  export const db = {
88
98
  poolSize: 50,
@@ -10,7 +10,6 @@ import * as _ from 'lodash';
10
10
  import { TypedError } from 'typed-error';
11
11
  import * as env from '../config-loader/env';
12
12
  import { fromCallback, timeout } from '../sbvr-api/control-flow';
13
- import { optionalVar } from '@balena/env-parsing';
14
13
 
15
14
  export const metrics = new EventEmitter();
16
15
 
@@ -484,7 +483,7 @@ if (maybePg != null) {
484
483
  const PG_CHECK_CONSTRAINT_VIOLATION = '23514';
485
484
  const PG_EXCLUSION_CONSTRAINT_VIOLATION = '23P01';
486
485
 
487
- const PG_SCHEMA = optionalVar('PG_SCHEMA', undefined);
486
+ const { PG_SCHEMA } = process.env;
488
487
  const initPool = (config: Pg.PoolConfig) => {
489
488
  config.max ??= env.db.poolSize;
490
489
  config.idleTimeoutMillis ??= env.db.idleTimeoutMillis;
@@ -1,9 +1,8 @@
1
- import { optionalVar } from '@balena/env-parsing';
2
1
  import type * as Fs from 'fs';
3
2
 
4
3
  import * as _ from 'lodash';
5
4
 
6
- const cacheFile = optionalVar('PINEJS_CACHE_FILE', '.pinejs-cache.json');
5
+ const cacheFile = process.env.PINEJS_CACHE_FILE || '.pinejs-cache.json';
7
6
  let cache: null | {
8
7
  [name: string]: {
9
8
  [version: string]: {
@@ -1521,6 +1521,52 @@ export const customAuthorizationMiddleware = (expectedScheme = 'Bearer') => {
1521
1521
  // A default bearer middleware for convenience
1522
1522
  export const authorizationMiddleware = customAuthorizationMiddleware();
1523
1523
 
1524
+ export const resolveBasicAuthHeader = async (
1525
+ req: Express.Request,
1526
+ expectedScheme = 'Basic',
1527
+ ): Promise<PermissionReq['user']> => {
1528
+ const auth = req.header('Authorization');
1529
+ if (!auth) {
1530
+ return;
1531
+ }
1532
+
1533
+ const parts = auth.split(' ');
1534
+ if (parts.length !== 2) {
1535
+ return;
1536
+ }
1537
+
1538
+ const [scheme, basicAuthContentBase64] = parts;
1539
+ if (scheme.toLowerCase() !== expectedScheme.toLowerCase()) {
1540
+ return;
1541
+ }
1542
+
1543
+ const basicAuthContent = Buffer.from(basicAuthContentBase64, 'base64')
1544
+ .toString()
1545
+ .trim();
1546
+ const [username, password] = basicAuthContent.split(';');
1547
+ return checkPassword(username, password);
1548
+ };
1549
+
1550
+ export const basicUserPasswordAuthorizationMiddleware = (
1551
+ expectedScheme = 'Basic',
1552
+ ) => {
1553
+ expectedScheme = expectedScheme.toLowerCase();
1554
+ return async (
1555
+ req: Express.Request,
1556
+ _res?: Express.Response,
1557
+ next?: Express.NextFunction,
1558
+ ): Promise<void> => {
1559
+ try {
1560
+ const user = await resolveBasicAuthHeader(req, expectedScheme);
1561
+ if (user) {
1562
+ req.user = user;
1563
+ }
1564
+ } finally {
1565
+ next?.();
1566
+ }
1567
+ };
1568
+ };
1569
+
1524
1570
  export const resolveApiKey = async (
1525
1571
  req: HookReq | Express.Request,
1526
1572
  paramName = 'apikey',
@@ -9,7 +9,6 @@ import * as migratorUtils from '../migrator/utils';
9
9
 
10
10
  import * as sbvrUtils from '../sbvr-api/sbvr-utils';
11
11
  import { PINEJS_ADVISORY_LOCK } from '../config-loader/env';
12
- import { optionalVar } from '@balena/env-parsing';
13
12
 
14
13
  export * as dbModule from '../database-layer/db';
15
14
  export { PinejsSessionStore } from '../pinejs-session-store/pinejs-session-store';
@@ -30,8 +29,8 @@ if (dbModule.engines.websql != null) {
30
29
  };
31
30
  } else {
32
31
  let databaseURL: string;
33
- if (optionalVar('DATABASE_URL')) {
34
- databaseURL = optionalVar('DATABASE_URL', '');
32
+ if (process.env.DATABASE_URL) {
33
+ databaseURL = process.env.DATABASE_URL;
35
34
  } else if (dbModule.engines.postgres != null) {
36
35
  databaseURL = 'postgres://postgres:.@localhost:5432/postgres';
37
36
  } else if (dbModule.engines.mysql == null) {
@@ -64,8 +63,6 @@ export const init = async <T extends string>(
64
63
  await cfgLoader.loadConfig(migrator.config);
65
64
 
66
65
  const promises: Array<Promise<void>> = [];
67
- // cannot be replaced with env-parsing module as it's overwritten in webpack process with a text-match plugin.
68
- // needs to remain `process.env.SBVR_SERVER_ENABLED` as this is the string the plugin will search for.
69
66
  if (process.env.SBVR_SERVER_ENABLED) {
70
67
  const sbvrServer = await import('../data-server/sbvr-server');
71
68
  const transactions = require('../http-transactions/transactions');
@@ -76,8 +73,6 @@ export const init = async <T extends string>(
76
73
  .then(() => transactions.addModelHooks('data')),
77
74
  );
78
75
  }
79
- // cannot be replaced with env-parsing module as it's overwritten in webpack process with a text-match plugin.
80
- // needs to remain `process.env.CONFIG_LOADER_DISABLED` as this is the string the plugin will search for.
81
76
  if (!process.env.CONFIG_LOADER_DISABLED) {
82
77
  promises.push(cfgLoader.loadApplicationConfig(config));
83
78
  }
@@ -16,7 +16,6 @@ export { ExtendedSBVRParser } from '../extended-sbvr-parser/extended-sbvr-parser
16
16
  import * as passportPinejs from '../passport-pinejs/passport-pinejs';
17
17
 
18
18
  import * as express from 'express';
19
- import { intVar, boolVar } from '@balena/env-parsing';
20
19
 
21
20
  const app = express();
22
21
 
@@ -90,7 +89,7 @@ export const initialised = Pinejs.init(app)
90
89
  if (
91
90
  typeof process === 'undefined' ||
92
91
  process == null ||
93
- !boolVar('DISABLE_DEFAULT_AUTH')
92
+ !process.env.DISABLE_DEFAULT_AUTH
94
93
  ) {
95
94
  app.post(
96
95
  '/login',
@@ -119,7 +118,7 @@ export const initialised = Pinejs.init(app)
119
118
  });
120
119
  }
121
120
 
122
- app.listen(intVar('PORT', 1337), () => {
121
+ app.listen(process.env.PORT || 1337, () => {
123
122
  console.info('Server started');
124
123
  });
125
124
  })