UNPKG

2.63 kBPlain TextView Raw
1import { DeviceCheck, DeviceCheckResult } from "./deviceTrust";
2import { CheckResultMetrics, SecurityCheckResultMetric } from "./metrics";
3import { MetricsService } from "@aerogear/core";
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 constructor(private metrics?: MetricsService) {
16 }
17
18 /**
19 * Execute the provided security check and return the result.
20 *
21 * @returns The result of the provided check.
22 */
23 public check(check: DeviceCheck): Promise<DeviceCheckResult> {
24 return check.check();
25 }
26
27 /**
28 * Execute the provided security check and publish the result as a metric.
29 *
30 * @return The sent metric for the check result.
31 */
32 public checkAndPublishMetric(check: DeviceCheck): Promise<SecurityCheckResultMetric> {
33 return this.check(check)
34 .then(checkResult => this.publishCheckResultMetrics(checkResult))
35 .then(checkMetrics => checkMetrics[0]);
36 }
37
38 /**
39 * Execute the provided security checks and return the results in an array.
40 *
41 * @returns An array of results for the provided checks.
42 */
43 public checkMany(...checks: DeviceCheck[]): Promise<DeviceCheckResult[]> {
44 return Promise.all(checks.map(check => check.check()));
45 }
46
47 /**
48 * Execute the provided security checks and publish the results as metrics.
49 *
50 * @return An array of the sent metrics.
51 */
52 public checkManyAndPublishMetric(...checks: DeviceCheck[]): Promise<SecurityCheckResultMetric[]> {
53 return this.checkMany(...checks)
54 .then(checkResults => this.publishCheckResultMetrics(...checkResults));
55 }
56
57 /**
58 * Publish metrics results from self defence checks to a metrics service.
59 * Application configuration must be provided to the security service on
60 * creation, otherwise metrics sending will always fail.
61 *
62 * @return Promise with the result of the underlying metrics publisher.
63 */
64 private publishCheckResultMetrics(...results: DeviceCheckResult[]): Promise<SecurityCheckResultMetric[]> {
65 if (!results || results.length === 0) {
66 return Promise.resolve([]);
67 }
68
69 const checkResultMetrics = new CheckResultMetrics(results);
70 if (!this.metrics) {
71 return Promise.reject(new Error("Metrics configuration is not available."));
72 }
73
74 return this.metrics.publish(SecurityService.METRICS_KEY, [checkResultMetrics])
75 .then(() => checkResultMetrics.collect());
76 }
77}