-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
459 lines (383 loc) · 14.9 KB
/
Copy pathapi.js
File metadata and controls
459 lines (383 loc) · 14.9 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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
const crypto = require('crypto');
const packageInfo = require('./package.json');
const packageVersion = packageInfo.version;
// NOTE: bump this default when major versions are released
const defaultAcceptVersionHeader = 'v6.0';
const supportedVersions = ['v2', 'v3', 'v4', 'v5', 'v6', 'canary'];
const packageName = '@dollardeploy/ghost-cli';
function base64url(input) {
return Buffer.from(input)
.toString('base64')
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
}
/**
* Sign a Ghost Admin API token (HS256 JWT) without external dependencies.
*
* @param {string} key - Admin API key in `{id}:{secret}` form
* @param {string} audience - JWT audience, e.g. `/admin/`
* @returns {string}
*/
function token(key, audience) {
const [id, secret] = key.split(':');
const header = {alg: 'HS256', typ: 'JWT', kid: id};
const now = Math.floor(Date.now() / 1000);
const payload = {iat: now, exp: now + 5 * 60, aud: audience};
const encodedHeader = base64url(JSON.stringify(header));
const encodedPayload = base64url(JSON.stringify(payload));
const unsignedToken = `${encodedHeader}.${encodedPayload}`;
const signature = crypto
.createHmac('sha256', Buffer.from(secret, 'hex'))
.update(unsignedToken)
.digest('base64')
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
return `${unsignedToken}.${signature}`;
}
/**
* Serialize query parameters using the same comma-joined format the Ghost API
* expects (arrays become comma separated lists, values are URI encoded).
*
* @param {string} url
* @param {Object} params
* @returns {string}
*/
function serializeQuery(url, params = {}) {
const keys = Object.keys(params);
if (!keys.length) {
return url;
}
const queryString = keys.reduce((parts, key) => {
const value = encodeURIComponent([].concat(params[key]).join(','));
return parts.concat(`${key}=${value}`);
}, []).join('&');
if (!queryString) {
return url;
}
return url.includes('?') ? `${url}&${queryString}` : `${url}?${queryString}`;
}
/**
* This method can go away in favor of only sending 'Accept-Version` headers
* once the Ghost API removes a concept of version from it's URLS (with Ghost v5)
*
* @param {string} [version] version in `v{major}` format
* @returns {string}
*/
const resolveAPIPrefix = (version) => {
let prefix;
// Only v2, v3, v4, and canary need version prefixes in the URL
if (version === 'v2' || version === 'v3' || version === 'v4' || version === 'canary') {
prefix = `/${version}/admin/`;
} else if (version && version.match(/^v[2-4]\.\d+/)) {
const versionPrefix = /^(v[2-4])\.\d+/.exec(version)[1];
prefix = `/${versionPrefix}/admin/`;
} else {
// Default for v5+, v6, undefined, etc. - no version prefix
prefix = `/admin/`;
}
return prefix;
};
/**
*
* @param {Object} options
* @param {String} options.url
* @param {String} [options.ghostPath]
* @param {String|Boolean} options.version - a version string like v3.2, v4.1, v5.8 or boolean value identifying presence of Accept-Version header
* @param {String|Boolean} [options.userAgent] - flag controlling if the 'User-Agent' header should be sent with a request
* @param {Function} [options.makeRequest]
* @param {Function} [options.generateToken]
* @param {String} [options.host] Deprecated
*/
module.exports = function GhostAdminAPI(options) {
if (this instanceof GhostAdminAPI) {
return GhostAdminAPI(options);
}
const defaultConfig = {
ghostPath: 'ghost',
userAgent: true,
generateToken: token,
async makeRequest({url, method, data, params = {}, headers = {}}) {
const requestUrl = serializeQuery(url, params);
const requestHeaders = Object.assign({}, headers);
const fetchOptions = {method, headers: requestHeaders};
const hasBody = data !== undefined && data !== null && data !== '';
if (hasBody) {
const hasContentType = Object.keys(requestHeaders).some(
(key) => key.toLowerCase() === 'content-type'
);
if (!hasContentType) {
requestHeaders['Content-Type'] = 'application/json';
}
fetchOptions.body = typeof data === 'string' ? data : JSON.stringify(data);
}
const response = await fetch(requestUrl, fetchOptions);
const rawBody = await response.text();
let parsedBody;
if (rawBody) {
try {
parsedBody = JSON.parse(rawBody);
} catch (e) {
parsedBody = rawBody;
}
}
if (!response.ok) {
const error = new Error(`Request failed with status code ${response.status}`);
error.response = {status: response.status, data: parsedBody};
throw error;
}
return parsedBody;
}
};
const config = Object.assign({}, defaultConfig, options);
//
/**
* host parameter is deprecated
* @deprecated use "url" instead
* @example new GhostAdminAPI({host: '...'})
*/
if (config.host) {
// eslint-disable-next-line
console.warn(`${packageName}: The 'host' parameter is deprecated, please use 'url' instead`);
if (!config.url) {
config.url = config.host;
}
}
if (config.version === undefined) {
throw new Error(`${packageName} Config Missing: 'version' is required. E.g. ${supportedVersions.join(',')}`);
}
if (typeof config.version === 'boolean') {
if (config.version === true) {
config.acceptVersionHeader = defaultAcceptVersionHeader;
}
config.version = undefined;
} else if (!supportedVersions.includes(config.version) && !(config.version.match(/^v\d+\.\d+/))) {
throw new Error(`${packageName} Config Invalid: 'version' ${config.version} is not supported`);
} else if (supportedVersions.includes(config.version) || config.version.match(/^v\d+\.\d+/)) {
if (config.version === 'canary') {
// eslint-disable-next-line
console.warn(`${packageName}: The 'version' parameter has a deprecated format 'canary', please use 'v{major}.{minor}' format instead`);
config.acceptVersionHeader = defaultAcceptVersionHeader;
} else if (config.version.match(/^v\d+$/)) {
// eslint-disable-next-line
console.warn(`${packageName}: The 'version' parameter has a deprecated format 'v{major}', please use 'v{major}.{minor}' format instead`);
// CASE: all the v1, v2, v4 ... strings should be normalized to fit 'v{major}.{minor}' format
config.acceptVersionHeader = `${config.version}.0`;
} else {
config.acceptVersionHeader = config.version;
}
}
if (!config.url) {
throw new Error(`${packageName} Config Missing: 'url' is required. E.g. 'https://site.com'`);
}
if (!/https?:\/\//.test(config.url)) {
throw new Error(`${packageName} Config Invalid: 'url' ${config.url} requires a protocol. E.g. 'https://site.com'`);
}
if (config.url.endsWith('/')) {
throw new Error(`${packageName} Config Invalid: 'url' ${config.url} must not have a trailing slash. E.g. 'https://site.com'`);
}
if (config.ghostPath.endsWith('/') || config.ghostPath.startsWith('/')) {
throw new Error(`${packageName} Config Invalid: 'ghostPath' ${config.ghostPath} must not have a leading or trailing slash. E.g. 'ghost'`);
}
if (!config.key) {
throw new Error(`${packageName} Config Invalid: 'key' ${config.key} must have 26 hex characters`);
}
if (!/[0-9a-f]{24}:[0-9a-f]{64}/.test(config.key)) {
throw new Error(`${packageName} Config Invalid: 'key' ${config.key} must have the following format {A}:{B}, where A is 24 hex characters and B is 64 hex characters`);
}
const resources = [
'posts',
'pages',
'tags',
'webhooks',
'members',
'users',
'newsletters'
];
if (typeof config.version === 'string' && config.version.startsWith('v2')) {
resources.push('subscribers');
}
const api = resources.reduce((apiObject, resourceType) => {
function add(data, queryParams = {}) {
if (!data || !Object.keys(data).length) {
return Promise.reject(new Error('Missing data'));
}
const mapped = {};
mapped[resourceType] = [data];
return makeResourceRequest(resourceType, queryParams, mapped, 'POST');
}
function edit(data, queryParams = {}) {
if (!data) {
return Promise.reject(new Error('Missing data'));
}
if (!data.id) {
return Promise.reject(new Error('Must include data.id'));
}
const body = {};
const urlParams = {};
if (data.id) {
urlParams.id = data.id;
delete data.id;
}
body[resourceType] = [data];
return makeResourceRequest(resourceType, queryParams, body, 'PUT', urlParams);
}
function del(data, queryParams = {}) {
if (!data) {
return Promise.reject(new Error('Missing data'));
}
if (!data.id && !data.email) {
return Promise.reject(new Error('Must include either data.id or data.email'));
}
const urlParams = data;
return makeResourceRequest(resourceType, queryParams, data, 'DELETE', urlParams);
}
function browse(opts = {}) {
return makeResourceRequest(resourceType, opts);
}
function read(data, queryParams) {
if (!data) {
return Promise.reject(new Error('Missing data'));
}
if (!data.id && !data.slug && !data.email) {
return Promise.reject(new Error('Must include either data.id or data.slug or data.email'));
}
const urlParams = {
id: data.id,
slug: data.slug,
email: data.email
};
delete data.id;
delete data.slug;
delete data.email;
queryParams = Object.assign({}, queryParams, data);
return makeResourceRequest(resourceType, queryParams, '', 'GET', urlParams);
}
let resourceAPI = {};
if (resourceType === 'webhooks') {
resourceAPI = {
[resourceType]: {
add,
edit,
delete: del
}
};
} else {
resourceAPI = {
[resourceType]: {
read,
browse,
add,
edit,
delete: del
}
};
}
return Object.assign(apiObject, resourceAPI);
}, {});
api.config = {
read() {
return makeResourceRequest('config', {}, {});
}
};
api.site = {
read() {
return makeResourceRequest('site', {}, {});
}
};
api.themes = {
activate(name) {
if (!name) {
return Promise.reject(new Error('Missing theme name'));
}
return makeResourceRequest('themes', {}, {}, 'PUT', {id: `${name}/activate`});
}
};
return api;
function makeResourceRequest(resourceType, queryParams = {}, body = '', method = 'GET', urlParams = {}) {
return makeApiRequest({
endpoint: endpointFor(resourceType, urlParams),
method,
queryParams,
body
}).then((data) => {
if (method === 'DELETE') {
return data;
}
if (!Array.isArray(data[resourceType])) {
return data[resourceType];
}
if (data[resourceType].length === 1 && !data.meta) {
return data[resourceType][0];
}
return Object.assign(data[resourceType], {meta: data.meta});
});
}
function endpointFor(resource, {id, slug, email} = {}) {
const {ghostPath, version} = config;
const apiPrefix = resolveAPIPrefix(version);
let endpoint = `/${ghostPath}/api${apiPrefix}${resource}/`;
if (id) {
endpoint = `${endpoint}${id}/`;
} else if (slug) {
endpoint = `${endpoint}slug/${slug}/`;
} else if (email) {
endpoint = `${endpoint}email/${email}/`;
}
return endpoint;
}
function makeApiRequest({endpoint, method, body, queryParams = {}, headers = {}}) {
const {url: apiUrl, key, version, makeRequest} = config;
const url = `${apiUrl}${endpoint}`;
let authorizationHeader;
const audience = resolveAPIPrefix(version);
authorizationHeader = `Ghost ${config.generateToken(key, audience)}`;
const ghostHeaders = {
Authorization: authorizationHeader
};
if (config.userAgent) {
if (typeof config.userAgent === 'boolean') {
ghostHeaders['User-Agent'] = `GhostAdminSDK/${packageVersion}`;
} else {
headers['User-Agent'] = config.userAgent;
}
}
if (config.acceptVersionHeader) {
ghostHeaders['Accept-Version'] = config.acceptVersionHeader;
}
headers = Object.assign({}, headers, ghostHeaders);
return makeRequest({
url,
method,
data: body,
params: queryParams,
headers
}).catch((err) => {
/**
* @NOTE:
*
* If you are overriding `makeRequest`, we can't garante that the returned format is the same, but
* we try to detect & return a proper error instance.
*/
if (err.response && err.response.data && err.response.data.errors) {
const props = err.response.data.errors[0];
const toThrow = new Error(props.message);
const keys = Object.keys(props);
toThrow.name = props.type;
keys.forEach((k) => {
toThrow[k] = props[k];
});
// @TODO: bring back with a better design idea. if you log the error, the stdout is hard to read
// if we return the full response object, which includes also the request etc.
// toThrow.response = err.response;
throw toThrow;
} else {
delete err.request;
delete err.config;
delete err.response;
throw err;
}
});
}
};