UNPKG

2.61 kBPlain TextView Raw
1import { INSTANCE } from "@aerogear/core";
2import { SecurityCheck, SecurityCheckResult } from "./deviceTrust";
3import { CheckResultMetrics, SecurityCheckResultMetric } from "./metrics";
4
5/**
6 * Service module for handling performing and reporting possible security
7 * issues in a mobile application.
8 *
9 * This requires the @aerogear/cordova-plugin-aerogear-security plugin to be
10 * included in an application.
11 */
12export class SecurityService {
13 private static readonly METRICS_KEY = "security";
14
15 /**
16 * Execute the provided security check and return the result.
17 *
18 * @returns The result of the provided check.
19 */
20 public check(check: SecurityCheck): Promise<SecurityCheckResult> {
21 return check.check();
22 }
23
24 /**
25 * Execute the provided security check and publish the result as a metric.
26 *
27 * @return The sent metric for the check result.
28 */
29 public checkAndPublishMetric(check: SecurityCheck): Promise<SecurityCheckResultMetric> {
30 return this.check(check)
31 .then(checkResult => this.publishCheckResultMetrics(checkResult))
32 .then(checkMetrics => checkMetrics[0]);
33 }
34
35 /**
36 * Execute the provided security checks and return the results in an array.
37 *
38 * @returns An array of results for the provided checks.
39 */
40 public checkMany(...checks: SecurityCheck[]): Promise<SecurityCheckResult[]> {
41 return Promise.all(checks.map(check => check.check()));
42 }
43
44 /**
45 * Execute the provided security checks and publish the results as metrics.
46 *
47 * @return An array of the sent metrics.
48 */
49 public checkManyAndPublishMetric(...checks: SecurityCheck[]): Promise<SecurityCheckResultMetric[]> {
50 return this.checkMany(...checks)
51 .then(checkResults => this.publishCheckResultMetrics(...checkResults));
52 }
53
54 /**
55 * Publish metrics results from self defence checks to a metrics service.
56 * Application configuration must be provided to the security service on
57 * creation, otherwise metrics sending will always fail.
58 *
59 * @return Promise with the result of the underlying metrics publisher.
60 */
61 private publishCheckResultMetrics(...results: SecurityCheckResult[]): Promise<SecurityCheckResultMetric[]> {
62 if (!results || results.length === 0) {
63 return Promise.resolve([]);
64 }
65
66 const checkResultMetrics = new CheckResultMetrics(results);
67 if (!INSTANCE || !INSTANCE.metrics) {
68 return Promise.reject(new Error("Metrics configuration is not available."));
69 }
70
71 return INSTANCE.metrics.publish(SecurityService.METRICS_KEY, [checkResultMetrics])
72 .then(() => checkResultMetrics.collect());
73 }
74}