-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpublish.js
More file actions
340 lines (329 loc) · 10.1 KB
/
Copy pathpublish.js
File metadata and controls
340 lines (329 loc) · 10.1 KB
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/*
Copyright 2017 The BioBricks Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var AJV = require('ajv')
var attachmentPath = require('./util/attachment-path')
var concat = require('simple-concat')
var crypto = require('crypto')
var encoding = require('./encoding')
var flushWriteStream = require('flush-write-stream')
var fs = require('fs')
var https = require('https')
var latest = require('./latest')
var mkdirp = require('mkdirp')
var once = require('once')
var parse = require('json-parse-errback')
var path = require('path')
var pump = require('pump')
var recordDirectoryPath = require('./util/record-directory-path')
var recordPath = require('./util/record-path')
var runParallel = require('run-parallel')
var runSeries = require('run-series')
var sodium = require('sodium-prebuilt').api
var stringify = require('json-stable-stringify')
var through2 = require('through2')
var timestampPath = require('./util/timestamp-path')
var uuid = require('uuid/v4')
var publicationSchema = latest(require('./schemas/publication'))
var timestampSchema = latest(require('./schemas/timestamp'))
var validatePublication = new AJV({allErrors: true})
.compile(publicationSchema)
// TODO: Delete attachment files in /tmp for invalid publications.
// Create a writable stream that accepts one or more attachment chunks,
// followed by a publication chunk, and writes files and a signed
// timestamp to the data directory.
//
// Attachment chunks look like:
//
// {
// type: 'attachment',
// stream: Readable,
// filename: String,
// encoding: String,
// mimetype: String
// }
//
// Publication fields contain JSON data.
module.exports = function (configuration, log, callback) {
var directory = configuration.directory
var attachments = []
var validPublication = false
return flushWriteStream.obj(
function (object, _, done) {
if (object.type === 'attachment') {
writeAttachment(object, done)
} else {
writePublication(object, function (error, digest) {
if (error) return done(error)
validPublication = digest
done()
})
}
},
function (done) {
if (validPublication) {
callback(validPublication)
} else {
runParallel(
attachments.map(function (attachment) {
return function unlinkTemporaryFile (done) {
fs.unlink(attachment.temporaryFile, function (error) {
log.error(error)
done()
})
}
}),
function () {
done()
}
)
}
}
)
function writeAttachment (object, callback) {
// Save to ./tmp/{UUID}.
var id = uuid()
var temporaryFile = path.join(directory, 'tmp', id)
var attachment = {
stream: object.stream,
temporaryFile: temporaryFile,
type: object.mimetype + '; charset=' + object.encoding
}
log.info('attachment', {
uuid: id,
filename: object.filename,
encoding: object.encoding,
mimetype: object.mimetype
})
attachments.push(attachment)
var hash = crypto.createHash('sha256')
var size = 0
pump(
object.stream,
// Compute SHA256 as we write to disk.
through2(function (chunk, chunkEncoding, done) {
size += chunk.length
hash.update(chunk, chunkEncoding)
this.push(chunk, chunkEncoding)
done()
}),
fs.createWriteStream(temporaryFile),
function (error) {
/* istanbul ignore next */
if (error) {
callback(error)
} else {
if (size === 0) {
var index = attachments.indexOf(attachment)
attachments.splice(index, 1)
} else {
attachment.digest = encoding.encode(hash.digest())
}
callback()
}
}
)
}
function writePublication (publication, callback) {
var secretKey = configuration.keypair.secret
var publicKey = configuration.keypair.public
var time = new Date().toISOString()
publication.attachments = attachments
.map(function (attachment) {
return attachment.digest
})
.sort()
log.info('publication', publication)
publication.version = '1.0.0'
validatePublication(publication)
var validationErrors = validatePublication.errors
if (validationErrors) {
log.info('validationErrors', validationErrors)
var validationError = new Error('Invalid input')
validationError.validationErrors = validationErrors
callback(validationError)
} else {
var record = Buffer.from(stringify(publication), 'utf8')
var digest = encoding.encode(
sodium.crypto_hash_sha256(record)
)
var uri = (
'https://' + configuration.hostname +
'/publications/' + digest
)
var timestamp = {
digest: digest,
uri: uri,
time: time
}
var signature = encoding.encode(
sodium.crypto_sign_detached(
Buffer.from(stringify(timestamp)),
secretKey
)
)
runSeries([
function writeJSONFile (done) {
fs.writeFile(recordPath(directory, digest), record, done)
},
function createDirectory (done) {
mkdirp(recordDirectoryPath(directory, digest), done)
},
function writeTimestampFile (done) {
fs.writeFile(
timestampPath(directory, digest, publicKey),
stringify({
timestamp: timestamp,
signature: signature,
version: timestampSchema.properties.version.constant
}),
done
)
},
function writeAttachments (done) {
if (attachments.length > 0) {
runParallel(
attachments.reduce(
function (tasks, attachment) {
var file = attachmentPath(
directory, digest, attachment.digest
)
return tasks.concat([
function writeTypeFile (done) {
fs.writeFile(
file + '.type',
attachment.type,
'utf8',
done
)
},
function moveFile (done) {
fs.rename(
attachment.temporaryFile, file,
done
)
}
])
},
[]
),
done
)
} else {
done()
}
},
function appendToAccessions (done) {
fs.appendFile(
path.join(directory, 'accessions'),
time + ',' + digest + '\n',
done
)
},
function stampWithStampery (done) {
if (configuration.stampery) {
stamp(configuration, log, digest, done)
} else {
done()
}
}
], function (error) {
/* istanbul ignore if */
if (error) {
error.statusCode = 500
callback(error)
} else {
callback(null, digest)
}
})
}
}
}
function stamp (configuration, log, digest, callback) {
callback = once(callback)
var auth = (
configuration.stampery.user + ':' +
configuration.stampery.password
)
https.request({
host: 'api-prod.stampery.com',
path: '/stamps/' + digest,
auth: auth
})
.once('error', function (error) {
log.error(error)
callback()
})
.once('response', function (response) {
concat(response, function (error, buffer) {
if (error) {
log.error(error)
callback()
} else {
parse(buffer, function (error, data) {
if (error) {
log.error(error)
callback()
} else if (data.error) {
log.error(data)
callback()
} else if (!Array.isArray(data.results)) {
log.error('no stampery results')
callback()
} else {
if (data.results.length !== 0) {
log.info('already stamped')
callback()
} else {
https.request({
method: 'POST',
host: 'api-prod.stampery.com',
path: '/stamps',
auth: auth,
headers: {
'Content-Type': 'application/json'
}
})
.once('error', function (error) {
log.error(error)
callback()
})
.once('response', function (response) {
concat(response, function (error, buffer) {
if (error) {
log.error(error)
callback()
} else {
parse(buffer, function (error, data) {
if (error) {
log.error(error)
} else if (data.error) {
log.error(data.error)
} else if (!data.result) {
log.error('no stampery result')
} else {
log.info(data.result, 'stamp')
}
callback()
})
}
})
})
.end(JSON.stringify({hash: digest}))
}
}
})
}
})
})
.end()
}