UNPKG

9.61 kBJavaScriptView Raw
1'use strict'
2
3let co = require('co')
4let cli = require('heroku-cli-util')
5let _ = require('lodash')
6let inquirer = require('inquirer')
7let psl = require('psl')
8
9let error = require('../../lib/error.js')
10let readFile = require('../../lib/read_file.js')
11let findMatch = require('../../lib/find_match.js')
12let endpoints = require('../../lib/endpoints.js')
13let sslDoctor = require('../../lib/ssl_doctor.js')
14let displayWarnings = require('../../lib/display_warnings.js')
15let certificateDetails = require('../../lib/certificate_details.js')
16let isWildcard = require('../../lib/is_wildcard.js')
17let isWildcardMatch = require('../../lib/is_wildcard_match.js')
18
19function Domains (domains) {
20 this.domains = domains
21
22 this.added = this.domains.filter((domain) => !domain._failed)
23 this.failed = this.domains.filter((domain) => domain._failed)
24
25 this.hasFailed = this.failed.length > 0
26}
27
28function * getMeta (context, heroku) {
29 let type = context.flags.type
30
31 if (type) {
32 switch (type) {
33 case 'endpoint':
34 return endpoints.meta(context.app, 'ssl')
35 case 'sni':
36 return endpoints.meta(context.app, 'sni')
37 default:
38 error.exit(1, "Must pass --type with either 'endpoint' or 'sni'")
39 }
40 }
41
42 let {hasSpace, hasAddon} = yield {
43 hasSpace: endpoints.hasSpace(context.app, heroku),
44 hasAddon: endpoints.hasAddon(context.app, heroku)
45 }
46
47 if (hasSpace) {
48 return endpoints.meta(context.app, 'ssl')
49 } else if (!hasAddon) {
50 return endpoints.meta(context.app, 'sni')
51 } else {
52 error.exit(1, "Must pass --type with either 'endpoint' or 'sni'")
53 }
54}
55
56function * getFiles (context) {
57 let files = yield {
58 crt: readFile(context.args.CRT, 'utf-8'),
59 key: readFile(context.args.KEY, 'utf-8')
60 }
61
62 let crt, key
63 if (context.flags.bypass) {
64 crt = files.crt
65 key = files.key
66 } else {
67 let res = JSON.parse(yield sslDoctor('resolve-chain-and-key', [files.crt, files.key]))
68 crt = res.pem
69 key = res.key
70 }
71
72 return {crt, key}
73}
74
75function hasMatch (certDomains, domain) {
76 return _.find(certDomains, (certDomain) => (certDomain === domain || isWildcardMatch(certDomain, domain)))
77}
78
79function getFlagChoices (context, certDomains, existingDomains) {
80 let flagDomains = context.flags.domains.split(',').map((str) => str.trim()).filter((str) => str !== '')
81 let choices = _.difference(flagDomains, existingDomains)
82
83 let badChoices = _.remove(choices, (choice) => (!hasMatch(certDomains, choice)))
84 badChoices.forEach(function (choice) {
85 cli.warn(`Not adding ${choice} because it is not listed in the certificate`)
86 })
87
88 return choices
89}
90
91function getPromptChoices (context, certDomains, existingDomains, newDomains) {
92 let nonWildcardDomains = newDomains.filter((domain) => !isWildcard(domain))
93
94 if (nonWildcardDomains.length === 0) {
95 return Promise.resolve({domains: []})
96 }
97
98 return inquirer.prompt([{
99 type: 'checkbox',
100 name: 'domains',
101 message: 'Select domains you would like to add',
102 choices: nonWildcardDomains.map(function (domain) {
103 return {name: domain}
104 })
105 }])
106}
107
108function * getChoices (certDomains, newDomains, existingDomains, context) {
109 if (newDomains.length === 0) {
110 return []
111 } else {
112 if (context.flags.domains !== undefined) {
113 return getFlagChoices(context, certDomains, existingDomains)
114 } else {
115 return (yield getPromptChoices(context, certDomains, existingDomains, newDomains)).domains
116 }
117 }
118}
119
120function * getDomains (context, heroku) {
121 function someNull (domains) {
122 return _.some(domains, (domain) => domain.kind === 'custom' && !domain.cname)
123 }
124
125 function apiRequest (context, heroku) {
126 return heroku.request({
127 path: `/apps/${context.app}/domains`
128 })
129 }
130
131 let apiDomains = yield apiRequest(context, heroku)
132
133 if (someNull(apiDomains)) {
134 yield cli.action('Waiting for stable domains to be created', co(function * () {
135 const wait = require('co-wait')
136
137 let i = 0
138 do {
139 // trying 30 times was easier for me to test that setTimeout
140 if (i >= 30) {
141 throw new Error('Timed out while waiting for stable domains to be created')
142 }
143
144 yield wait(1000)
145 apiDomains = yield apiRequest(context, heroku)
146
147 i++
148 } while (someNull(apiDomains))
149 }))
150 }
151
152 return apiDomains
153}
154
155function * addDomains (context, heroku, meta, cert) {
156 let certDomains = cert.ssl_cert.cert_domains
157
158 let apiDomains = yield getDomains(context, heroku)
159
160 let existingDomains = []
161 let newDomains = []
162 let herokuDomains = []
163
164 certDomains.forEach(function (certDomain) {
165 let matches = findMatch(certDomain, apiDomains)
166 if (matches) {
167 if (matches.kind === 'heroku') {
168 herokuDomains.push(certDomain)
169 } else {
170 existingDomains.push(certDomain)
171 }
172 } else {
173 newDomains.push(certDomain)
174 }
175 })
176
177 if (herokuDomains.length > 0) {
178 cli.log()
179 cli.styledHeader('The following common names are for hosts that are managed by Heroku')
180 herokuDomains.forEach((domain) => cli.log(domain))
181 }
182
183 if (existingDomains.length > 0) {
184 cli.log()
185 cli.styledHeader('The following common names already have domain entries')
186 existingDomains.forEach((domain) => cli.log(domain))
187 }
188
189 let choices = yield getChoices(certDomains, newDomains, existingDomains, context)
190 let domains
191
192 if (choices.length === 0) {
193 domains = new Domains([])
194 } else {
195 // Add a newline between the existing and adding messages
196 cli.console.error()
197
198 let promise = Promise.all(choices.map(function (certDomain) {
199 return heroku.request({
200 path: `/apps/${context.app}/domains`,
201 method: 'POST',
202 body: {'hostname': certDomain}
203 }).catch(function (err) {
204 return {_hostname: certDomain, _failed: true, _err: err}
205 })
206 })).then(function (data) {
207 let domains = new Domains(data)
208 if (domains.hasFailed) {
209 throw domains
210 }
211 return domains
212 })
213
214 let label = choices.length > 1 ? 'domains' : 'domain'
215 let message = `Adding ${label} ${choices.map((choice) => cli.color.green(choice)).join(', ')} to ${cli.color.app(context.app)}`
216 domains = yield cli.action(message, {}, promise).catch(function (err) {
217 if (err instanceof Domains) {
218 return err
219 }
220 throw err
221 })
222 }
223
224 if (domains.hasFailed) {
225 cli.log()
226 domains.failed.forEach(function (domain) {
227 cli.error(`An error was encountered when adding ${domain._hostname}`)
228 cli.error(domain._err)
229 })
230 }
231
232 cli.log()
233
234 let type = function (domain) {
235 return psl.parse(domain.hostname).subdomain === null ? 'ALIAS/ANAME' : 'CNAME'
236 }
237
238 let hasWildcard = _.some(certDomains, (certDomain) => isWildcard(certDomain))
239
240 let domainsTable = apiDomains.concat(domains.added)
241 .filter((domain) => domain.kind === 'custom')
242 .map(function (domain) {
243 let warning = null
244 if (hasWildcard && domain.hostname) {
245 if (!hasMatch(certDomains, domain.hostname)) {
246 warning = '! Does not match any domains on your SSL certificate'
247 }
248 }
249
250 return Object.assign({}, domain, {type: type(domain), warning: warning})
251 })
252
253 if (domainsTable.length === 0) {
254 /* eslint-disable no-irregular-whitespace */
255 cli.styledHeader(`Your certificate has been added successfully.  Add a custom domain to your app by running ${cli.color.app('heroku domains:add <yourdomain.com>')}`)
256 /* eslint-enable no-irregular-whitespace */
257 } else {
258 cli.styledHeader("Your certificate has been added successfully. Update your application's DNS settings as follows")
259
260 let columns = [
261 {label: 'Domain', key: 'hostname'},
262 {label: 'Record Type', key: 'type'},
263 {label: 'DNS Target', key: 'cname'}
264 ]
265
266 if (_.some(domainsTable, (domain) => domain.warning)) {
267 columns.push({label: 'Warnings', key: 'warning'})
268 }
269
270 cli.table(domainsTable, {columns: columns})
271 }
272
273 if (domains.hasFailed) {
274 error.exit(2)
275 }
276}
277
278function * run (context, heroku) {
279 let meta = yield getMeta(context, heroku)
280
281 let files = yield getFiles(context)
282
283 let cert = yield cli.action(`Adding SSL certificate to ${cli.color.app(context.app)}`, {}, heroku.request({
284 path: meta.path,
285 method: 'POST',
286 body: {certificate_chain: files.crt, private_key: files.key},
287 headers: {'Accept': `application/vnd.heroku+json; version=3.${meta.variant}`}
288 }))
289
290 cert._meta = meta
291
292 // Remove the warning for SNI endpoints because we will provide our own error
293 if (cert.warnings && cert.warnings.ssl_cert) {
294 _.pull(cert.warnings.ssl_cert, 'provides no domain(s) that are configured for this Heroku app')
295 }
296
297 if (meta.type !== 'SNI' || cert.cname) {
298 cli.log(`${cli.color.app(context.app)} now served by ${cli.color.green(cert.cname)}`)
299 }
300
301 certificateDetails(cert)
302
303 yield addDomains(context, heroku, meta, cert)
304
305 displayWarnings(cert)
306}
307
308module.exports = {
309 topic: 'certs',
310 command: 'add',
311 args: [
312 {name: 'CRT', optional: false},
313 {name: 'KEY', optional: false}
314 ],
315 flags: [
316 {name: 'bypass', description: 'bypass the trust chain completion step', hasValue: false},
317 {name: 'type', description: "type to create, either 'sni' or 'endpoint'", hasValue: true},
318 {name: 'domains', description: 'domains to create after certificate upload', hasValue: true}
319 ],
320 description: 'add an SSL certificate to an app',
321 help: `Example:
322
323 $ heroku certs:add example.com.crt example.com.key
324`,
325 needsApp: true,
326 needsAuth: true,
327 run: cli.command(co.wrap(run))
328}