-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
151 lines (132 loc) · 4.05 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
'use strict';
const AWS = require('aws-sdk');
const http = require('http');
const S = require('string');
const EventEmitter = require('events');
module.exports.SNS = class SNS extends EventEmitter {
constructor(options) {
super();
const initOptions = options || {};
this.port = initOptions.port || '8081';
this.subscriptionArn = false;
this.subscriptionEndpoint = false;
this.sns = new AWS.SNS({
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || 'SOME_KEY',
accessKeyId: process.env.AWS_ACCESS_KEY_ID || 'SOME_SECRET',
apiVersion: '2010-03-31',
region: process.env.AWS_REGION || 'eu-west-1',
});
if (!process.env.AWS_TOPIC_ARN) {
process.env.AWS_TOPIC_ARN = 'SOME_TOPIC_ARN';
}
if (!process.env.NO_SUBSCRIPTION) {
this.getEndpoint(() => {
this.startServer(() => {
this.subscribe();
});
});
} else {
setTimeout(() => {this.emit('ready');}, 1);
}
}
startServer(done) {
function endResponse(res, statusCode) {
res.statusCode = statusCode || 200;
res.setHeader('Content-Type', 'text/plain');
res.end();
}
this.server = http.createServer((req, res) => {
let msg = '';
req.on('data', (chunk) => {
msg += chunk;
});
req.on('end', () => {
try {
msg = JSON.parse(msg);
// TODO: validate message - https://github.com/aws/aws-js-sns-message-validator
if (msg.TopicArn !== process.env.AWS_TOPIC_ARN) {
return endResponse(res, 404);
}
if (msg.Type === 'SubscriptionConfirmation') {
this.sns.confirmSubscription({
Token: msg.Token,
TopicArn: msg.TopicArn,
}, (err, subscription) => {
if (err) {
return endResponse(res, 500);
}
this.subscriptionArn = subscription.SubscriptionArn;
this.emit('ready');
return endResponse(res, 200);
});
}
if (msg.Type === 'Notification') {
try {
this.emit('message', { subject: msg.Subject, body: JSON.parse(msg.Message) });
endResponse(res, 200);
} catch (e) {
endResponse(res, 400);
}
}
} catch (e) {
return endResponse(res, 400);
}
return false;
});
});
this.server.listen(this.port, () => {
done();
});
}
send(data) {
if (!data || !data.subject || !data.message) {
throw new Error('Invalid data to SNS.send()');
}
this.sns.publish({
Subject: data.subject,
Message: JSON.stringify(data.message),
TopicArn: process.env.AWS_TOPIC_ARN,
}, (error, result) => {
if (error) {
throw error;
}
});
}
getEndpoint(done, ignoreEnv) {
if (process.env.AWS_SUBSCRIPTION_ENDPOINT && !ignoreEnv) {
// getting public IP, check http://docs.aws.amazon.co
// using endpoint from env (testing only)
this.subscriptionEndpoint = process.env.AWS_SUBSCRIPTION_ENDPOINT;
done();
} else {
// getting public IP, check http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
this.getIP((ip) => {
this.subscriptionEndpoint = `http://${ip}:${this.port}`;
done();
});
}
}
subscribe() {
this.sns.subscribe({
Protocol: 'http',
TopicArn: process.env.AWS_TOPIC_ARN,
Endpoint: this.subscriptionEndpoint,
}, (error) => {
if (error) {
throw error;
}
});
}
getIP(done, privateIP) {
// getting public IP, check http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
http.get(`http://169.254.169.254/latest/meta-data/${privateIP ? 'local' : 'public'}-ipv4`, (res) => {
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
done(S(rawData).trim().toString());
});
}).on('error', (e) => {
throw new Error('Unable to get IP', e);
});
}
};