This repository has been archived by the owner on Dec 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
192 lines (166 loc) · 5.22 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
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
const assert = require('assert')
const joinPaths = require('path').posix.join
const http = require('http')
const https = require('https')
const parseURL = require('url').parse
const DAT_KEY_REGEX = /([0-9a-f]{64})/i
const ACCOUNT_API_RELTYPE = 'https://archive.org/services/purl/purl/datprotocol/spec/pinning-service-account-api'
const DATS_API_RELTYPE = 'https://archive.org/services/purl/purl/datprotocol/spec/pinning-service-dats-api'
// exported api
// =
exports.createClient = function (hostUrl, login, cb) {
if (typeof login === 'function') {
// login is optional
cb = login
login = null
}
var client = new DatPinningServiceClient(hostUrl)
client.fetchPSADoc(function (err) {
if (err) return cb(err)
if (!login) return cb(null, client)
client.login(login.username, login.password, function (err) {
if (err) return cb(err)
cb(null, client)
})
})
}
class DatPinningServiceClient {
constructor (hostUrl, psaDoc) {
this.hostUrl = hostUrl.replace(/\/$/, '') // strip ending slash
this.psaDoc = null
this.accountsApiBaseUrl = null
this.datsApiBaseUrl = null
this.sessionToken = null
if (psaDoc) this.setPSADoc(psaDoc)
}
get hasSession () {
return !!this.sessionToken
}
setSession (token) {
this.sessionToken = token
}
fetchPSADoc (cb) {
var self = this
request(this.hostUrl, 'GET', '/.well-known/psa')(function (err, doc) {
if (err) return cb(err)
try { self.setPSADoc(doc) } catch (e) { return cb(e) }
cb()
})
}
setPSADoc (psaDoc) {
this.psaDoc = psaDoc
this.accountsApiBaseUrl = getBaseUrl(this.hostUrl, psaDoc, ACCOUNT_API_RELTYPE, 'accounts')
this.datsApiBaseUrl = getBaseUrl(this.hostUrl, psaDoc, DATS_API_RELTYPE, 'dats')
}
login (username, password, cb) {
var self = this
request(this.accountsApiBaseUrl, 'POST', '/login', null, {username, password})(function (err, res) {
if (err) return cb(err)
if (res.sessionToken) {
self.setSession(res.sessionToken)
}
cb(null, res)
})
}
logout (cb) {
request(this.accountsApiBaseUrl, 'POST', '/logout', this.sessionToken)(cb)
this.sessionToken = null
}
getAccount (cb) {
request(this.accountsApiBaseUrl, 'GET', '/account', this.sessionToken)(cb)
}
listDats (cb) {
request(this.datsApiBaseUrl, 'GET', '/', this.sessionToken)(cb)
}
addDat ({url, name, domains}, cb) {
request(this.datsApiBaseUrl, 'POST', '/add', this.sessionToken, {url, name, domains})(cb)
}
removeDat (url, cb) {
request(this.datsApiBaseUrl, 'POST', '/remove', this.sessionToken, {url})(cb)
}
getDat (key, cb) {
key = urlToKey(key)
request(this.datsApiBaseUrl, 'GET', joinPaths('/item', key), this.sessionToken)(cb)
}
updateDat (key, {name, domains}, cb) {
key = urlToKey(key)
request(this.datsApiBaseUrl, 'POST', joinPaths('/item', key), this.sessionToken, {name, domains})(cb)
}
}
exports.DatPinningServiceClient = DatPinningServiceClient
// internal methods
// =
function getBaseUrl (hostUrl, psaDoc, relType, desc) {
assert(psaDoc && typeof psaDoc === 'object', 'Invalid PSA service description document')
assert(psaDoc.links && Array.isArray(psaDoc.links), 'Invalid PSA service description document (no links array)')
var link = psaDoc.links.find(link => {
var rel = link.rel
return rel && typeof rel === 'string' && rel.indexOf(relType) !== -1
})
if (!link) {
throw new Error(`Service does not provide the pinning-service ${desc} API (rel ${relType})`)
}
var href = link.href
assert(href && typeof href === 'string', 'Invalid PSA service description document (no href on API link)')
if (href.startsWith('/')) {
href = hostUrl + link.href
}
return href
}
function urlToKey (url) {
var match = (url || '').match(DAT_KEY_REGEX)
if (match) {
return match[0].toLowerCase()
}
return url
}
function request (baseUrl, method, resourcePath, session, body) {
return function (cb) {
var opts = {method, headers: {}}
// parse URL
var urlp = parseURL(baseUrl)
var proto = (urlp.protocol === 'http:') ? http : https
opts.hostname = urlp.hostname
opts.path = joinPaths(urlp.pathname, resourcePath)
if (urlp.port) {
opts.port = urlp.port
}
// prepare body
if (body) {
body = JSON.stringify(body)
opts.headers['Content-Type'] = 'application/json'
opts.headers['Content-Length'] = Buffer.byteLength(body)
}
// prepare session
if (session) {
opts.headers['Authorization'] = 'Bearer ' + session
}
// send request
var req = proto.request(opts, res => {
var resBody = ''
res.setEncoding('utf8')
res.on('data', chunk => { resBody += chunk })
res.on('end', () => {
if (resBody) {
try {
resBody = JSON.parse(resBody)
} catch (e) {}
}
// reject / resolve
if (res.statusCode >= 400) {
var err = new Error(resBody && resBody.message ? resBody.message : 'Request failed')
err.statusCode = res.statusCode
err.responseBody = resBody
cb(err)
} else {
cb(null, resBody)
}
})
})
req.on('error', cb)
if (body) {
req.write(body)
}
req.end()
}
}