@webship.co/workspace-ghost 0.0.0-stage → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,175 @@
1
+ 'use strict';
2
+
3
+ // The accounts of a Ghost site, through its Admin API: complete the setup with the owner, add the
4
+ // staff accounts, delete them, list who is there. Ghost has no command line for accounts, so this
5
+ // is the one door.
6
+ //
7
+ // Runs with Node.js inside the project's web container, against Ghost's own port, and reads the
8
+ // staff invitations from the Mailpit of the same container: nothing is e-mailed outside. The
9
+ // functions of the plugin (fun-ghost.sh) pipe it to `node -` and hand it what it needs in
10
+ // GHOST_ACCOUNTS, base64 of a JSON object:
11
+ //
12
+ // { url, title, owner: { name, email, password }, staff: [{ name, email, password, role }] }
13
+ //
14
+ // Verbs: installed | setup | add | cancel | list. Every one can run again: what is already as
15
+ // asked is left alone. No password is ever printed.
16
+
17
+ const GHOST = process.env.GHOST_INTERNAL_URL || 'http://127.0.0.1:2368';
18
+ const MAILPIT = process.env.MAILPIT_INTERNAL_URL || 'http://127.0.0.1:8025';
19
+ const API = GHOST + '/ghost/api/admin';
20
+
21
+ function input() {
22
+ const raw = process.env.GHOST_ACCOUNTS || '';
23
+ if (!raw) return {};
24
+ try {
25
+ return JSON.parse(Buffer.from(raw, 'base64').toString('utf8'));
26
+ } catch (error) {
27
+ throw new Error('GHOST_ACCOUNTS is not base64 of a JSON object.');
28
+ }
29
+ }
30
+
31
+ const given = input();
32
+ const SITE_URL = String(given.url || '').replace(/\/+$/, '');
33
+ let cookie = '';
34
+
35
+ async function call(method, endpoint, body) {
36
+ // Ghost sits behind the router of the container tool: say the request was https, and send the
37
+ // Origin its session check compares with the address of the site.
38
+ const headers = { 'X-Forwarded-Proto': 'https', Origin: SITE_URL };
39
+ if (cookie) headers.Cookie = cookie;
40
+ let payload;
41
+ if (body) {
42
+ headers['Content-Type'] = 'application/json';
43
+ payload = JSON.stringify(body);
44
+ }
45
+ const response = await fetch(API + endpoint, { method, headers, body: payload, redirect: 'manual' });
46
+ const setCookie = response.headers.getSetCookie ? response.headers.getSetCookie() : [];
47
+ for (const line of setCookie) {
48
+ if (/^ghost-admin-api-session=/.test(line)) cookie = line.split(';')[0];
49
+ }
50
+ const text = await response.text();
51
+ let json = null;
52
+ try { json = text ? JSON.parse(text) : null; } catch (error) { /* not JSON */ }
53
+ if (!response.ok) {
54
+ const said = json && json.errors && json.errors[0] ? json.errors[0].message + (json.errors[0].context ? ' ' + json.errors[0].context : '') : text.slice(0, 300);
55
+ const failure = new Error(`${method} ${endpoint} answered ${response.status}: ${said}`);
56
+ failure.status = response.status;
57
+ throw failure;
58
+ }
59
+ return json;
60
+ }
61
+
62
+ async function isSetUp() {
63
+ const status = await call('GET', '/authentication/setup/');
64
+ return !!status.setup[0].status;
65
+ }
66
+
67
+ async function signInAsOwner() {
68
+ const owner = given.owner || {};
69
+ cookie = '';
70
+ try {
71
+ await call('POST', '/session/', { username: owner.email, password: owner.password });
72
+ } catch (error) {
73
+ throw new Error(`Could not sign in as the owner (${owner.email}): ${error.message}\n`
74
+ + 'The owner of the site is the workspace account (account: in core/config/settings.yml); if its address or password was changed on the site, the accounts cannot be managed from here.');
75
+ }
76
+ }
77
+
78
+ async function setup() {
79
+ if (await isSetUp()) {
80
+ console.log(' The site is already set up.');
81
+ return;
82
+ }
83
+ const owner = given.owner || {};
84
+ await call('POST', '/authentication/setup/', {
85
+ setup: [{ name: owner.name, email: owner.email, password: owner.password, blogTitle: given.title || 'Site' }],
86
+ });
87
+ console.log(` The site is set up; its owner is ${owner.email}.`);
88
+ }
89
+
90
+ async function invitationFor(email) {
91
+ for (let attempt = 0; attempt < 30; attempt++) {
92
+ const found = await (await fetch(`${MAILPIT}/api/v1/search?query=${encodeURIComponent('to:' + email)}`)).json();
93
+ if (found.messages && found.messages.length) {
94
+ const id = found.messages[0].ID;
95
+ const mail = await (await fetch(`${MAILPIT}/api/v1/message/${id}`)).json();
96
+ return { id, body: mail.Text || mail.HTML || '' };
97
+ }
98
+ await new Promise((resolve) => setTimeout(resolve, 1000));
99
+ }
100
+ throw new Error(`No invitation for ${email} reached the mailbox of the container (${MAILPIT}). Is the mail of the site still sent to it (config.production.json, "mail")?`);
101
+ }
102
+
103
+ async function add() {
104
+ await signInAsOwner();
105
+ const roles = (await call('GET', '/roles/?limit=all')).roles;
106
+ const users = (await call('GET', '/users/?limit=all')).users;
107
+ for (const person of given.staff || []) {
108
+ if (users.find((user) => user.email === person.email)) {
109
+ console.log(` ${person.email} is already there.`);
110
+ continue;
111
+ }
112
+ const role = roles.find((candidate) => candidate.name === person.role);
113
+ if (!role) throw new Error(`This site has no "${person.role}" role; it has: ${roles.map((r) => r.name).join(', ')}.`);
114
+ const invites = (await call('GET', '/invites/?limit=all')).invites;
115
+ if (!invites.find((invite) => invite.email === person.email)) {
116
+ await call('POST', '/invites/', { invites: [{ email: person.email, role_id: role.id }] });
117
+ }
118
+ const mail = await invitationFor(person.email);
119
+ const match = /\/ghost\/(?:#\/)?signup\/([^/\s"'<>]+)/.exec(mail.body);
120
+ if (!match) throw new Error(`The invitation for ${person.email} has no sign up link.`);
121
+ // The invitation is accepted by the invited person: without the session of the owner.
122
+ const session = cookie;
123
+ cookie = '';
124
+ await call('POST', '/authentication/invitation/', {
125
+ invitation: [{ token: decodeURIComponent(match[1]), email: person.email, name: person.name, password: person.password }],
126
+ });
127
+ cookie = session;
128
+ // The invitation is used: take it out of the mailbox, and leave every other message there.
129
+ await fetch(`${MAILPIT}/api/v1/messages`, { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ IDs: [mail.id] }) });
130
+ console.log(` ${person.email} added (${person.role}).`);
131
+ }
132
+ }
133
+
134
+ async function cancel() {
135
+ await signInAsOwner();
136
+ const users = (await call('GET', '/users/?limit=all')).users;
137
+ const invites = (await call('GET', '/invites/?limit=all')).invites;
138
+ for (const person of given.staff || []) {
139
+ const invite = invites.find((candidate) => candidate.email === person.email);
140
+ if (invite) await call('DELETE', `/invites/${invite.id}/`);
141
+ const user = users.find((candidate) => candidate.email === person.email);
142
+ if (!user) {
143
+ console.log(` ${person.email} is not there.`);
144
+ continue;
145
+ }
146
+ await call('DELETE', `/users/${user.id}/`);
147
+ console.log(` ${person.email} deleted.`);
148
+ }
149
+ }
150
+
151
+ async function list() {
152
+ await signInAsOwner();
153
+ const users = (await call('GET', '/users/?limit=all&include=roles')).users;
154
+ for (const user of users) {
155
+ console.log(` ${user.email.padEnd(32)} ${(user.roles || []).map((role) => role.name).join(', ').padEnd(14)} ${user.name}`);
156
+ }
157
+ }
158
+
159
+ const verbs = {
160
+ installed: async () => { if (!(await isSetUp())) process.exit(3); },
161
+ setup,
162
+ add,
163
+ cancel,
164
+ list,
165
+ };
166
+
167
+ const verb = process.argv[2];
168
+ if (!verbs[verb]) {
169
+ console.error('ghost-accounts.js <installed|setup|add|cancel|list>');
170
+ process.exit(2);
171
+ }
172
+ verbs[verb]().catch((error) => {
173
+ console.error(' ' + error.message);
174
+ process.exit(1);
175
+ });
@@ -0,0 +1,47 @@
1
+ Feature: The site answers and its accounts work
2
+ As the owner of the site
3
+ I want the front page, the sign in screen and each default account to work
4
+ So that a build that came out broken is caught before anything else is tested
5
+
6
+ # Placed by the workspace's testing setup as a starting point: it is yours to change.
7
+ # The accounts are the default ones (cmd-tools-add-users.sh); a scenario signs in by a handle of
8
+ # the users registry in cucumber.js, so no password is written here.
9
+
10
+ @critical
11
+ Scenario: The front page is served
12
+ Given I am an anonymous user
13
+ When I go to the homepage
14
+ Then the response status code should be 200
15
+ And the page should be the home page
16
+
17
+ @critical
18
+ Scenario: The sign in screen is served to a visitor who asks for the admin
19
+ Given I am an anonymous user
20
+ Then the admin screen "Posts" should not be available
21
+ And I should be on the admin screen "sign in"
22
+ And I should not be logged in to the admin
23
+
24
+ Scenario Outline: Each default account signs in and has its role
25
+ Given I am logged in to the admin as "<handle>"
26
+ Then I should be logged in to the admin as "<handle>"
27
+ And the user menu should show "<handle>@example.com"
28
+ When I log in to the admin as "administrator"
29
+ Then I should see the staff user "<handle>" with the role "<role>"
30
+
31
+ Examples:
32
+ | handle | role |
33
+ | administrator | Administrator |
34
+ | editor | Editor |
35
+ | author | Author |
36
+ | contributor | Contributor |
37
+
38
+ Scenario: An account is refused a screen its role may not open
39
+ Given I am logged in to the admin as "contributor"
40
+ Then the admin screen "Settings" should not be available
41
+ And the admin screen "Members" should not be available
42
+
43
+ Scenario: An anonymous visitor has no session
44
+ Given I am an anonymous user
45
+ When I go to the homepage
46
+ Then I should not be logged in to the admin
47
+ And I should see a subscribe button