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
|
const { access, constants, readFile, writeFile } = require("node:fs");
const { join } = require("node:path");
const { auth } = require("express-openid-connect");
const internals = {
kLogoutURL: "/logout",
kLoginURL: "/auth/login",
kClaimURL: "/auth/claim-wiki",
kSuccessfulLoginURL: "/auth/success",
buildBaseURL({ url, wiki_domain, security_useHttps }) {
let host = wiki_domain || url;
if (host.includes("//")) {
if (security_useHttps) {
return host.replace(/^http:\/\//, "https://");
}
return host;
}
const protocol = security_useHttps ? "https" : "http";
return `${protocol}://${host}`;
},
};
/**
* Creates a security handler for the wiki.
* @param {(...args: any[]) => void} log a logger function pre-configured to
* only log if debug is on.
* @param {(...args: any[]) => void} loga a logger function that always logs.
* @argv {Object} argv The wiki configuration.
*/
module.exports = function createHandler(
log,
loga,
{
id: idFile,
url,
wiki_domain,
admin,
security_useHttps,
oidc_claimOnFirstLogin,
oidc_clientID,
oidc_clientSecret,
oidc_idpLogout,
oidc_issuerBaseURL,
oidc_issuerName,
oidc_secret,
oidc_logoutRedirectURL,
restricted,
restrictedDomains,
restrictedUsers,
},
) {
let owner = null;
const security = {
/**
* Reads the owner file to determine the owner.
*/
retrieveOwner(callback) {
access(idFile, constants.F_OK, (error) => {
if (error) {
owner = null;
return callback();
}
readFile(idFile, "utf8", (error, data) => {
if (error) {
owner = null;
return callback(error);
}
owner = JSON.parse(data);
callback();
});
});
},
/**
* Reads the owner file to determine the owner.
*/
getOwner() {
return owner?.name || "";
},
/**
* Sets a new owner.
*/
setOwner(newOwner, callback) {
access(idFile, constants.F_OK, (error) => {
if (!error) {
return callback(new Error("Site already claimed"));
}
writeFile(idFile, JSON.stringify(newOwner), (error) => {
if (error) {
return callback(
new Error("Could not write owner to file."),
);
}
loga(`Claiming wiki ${url} for ${newOwner.name}`);
owner = newOwner;
callback();
});
});
},
/**
* Gets the current authenticated user.
*/
getUser(req) {
return req.oidc?.user || "";
},
/**
* Checks if the current authenticated user is authorized.
*/
isAuthorized(req) {
if (owner === null) {
loga("isAuthorized: Site not claimed");
return true;
}
const preferredUsername = req.oidc.user?.preferred_username;
return preferredUsername && preferredUsername === owner.username;
},
/**
* Checks if the current authenticated user is an admin.
*/
isAdmin(req) {
if (!admin) {
return false;
}
if (!req.oidc?.user) {
return false;
}
const preferredUsername = req.oidc.user?.preferred_username;
return preferredUsername && preferredUsername === admin;
},
/**
* Defines security routes for the wiki.
*/
defineRoutes(app, _, updateOwner) {
const viewsPath = join(__dirname, "..", "views");
const config = {
authRequired: false,
idpLogout: !!oidc_idpLogout,
baseURL: internals.buildBaseURL({
url,
wiki_domain,
security_useHttps,
}),
clientID: oidc_clientID,
clientSecret: oidc_clientSecret,
clientAuthMethod: "client_secret_post",
issuerBaseURL: oidc_issuerBaseURL,
secret: oidc_secret,
enableTelemetry: false,
routes: {
login: false,
logout: false,
callback: "/auth/oidc/callback",
},
};
app.use(auth(config));
// Starts the OIDC login process.
app.get("/auth/oidc", (_, res) =>
res.oidc.login({
returnTo: internals.kSuccessfulLoginURL,
}),
);
// Displays the login dialog.
app.get(internals.kLoginURL, (_, res) => {
res.render(join(viewsPath, "login.html"), {
issuerName: oidc_issuerName || "SSO",
wikiName: wiki_domain || url || "wiki",
});
});
// Shown after a successful login.
app.get(internals.kSuccessfulLoginURL, (req, res) => {
if (!req.oidc.isAuthenticated()) {
return res.redirect(internals.kLoginURL);
}
const username =
req.oidc.user.preferred_username ||
req.oidc.user.name ||
"User";
res.render(join(viewsPath, "success.html"), { username });
});
// Claims a wiki.
app.get(internals.kClaimURL, (req, res) => {
if (!req.oidc.isAuthenticated()) {
return res.status(401).json({ error: "Not authenticated" });
}
const user = req.oidc.user;
const newOwner = {
name: user.name || user.preferred_username || user.email,
username: user.preferred_username || user.email,
};
security.setOwner(newOwner, (error) => {
if (error) {
loga(`Failed to claim wiki: ${error.message}`);
return res.status(400).json({ error: error.message });
}
log(`Wiki claimed by ${newOwner.name}`);
updateOwner(newOwner.name);
res.json({ success: true, owner: newOwner.name });
});
});
// Settings sent to the client.
app.get("/auth/client-settings.json", (req, res) => {
const authenticated = req.oidc.isAuthenticated();
const settings = {
claimOnFirstLogin: !!oidc_claimOnFirstLogin,
logoutURL: internals.kLogoutURL,
loginURL: internals.kLoginURL,
claimURL: internals.kClaimURL,
wikiHost: wiki_domain,
useHttps: security_useHttps,
owner: owner ? owner.name : null,
isOwner: authenticated && security.isAuthorized(req),
};
res.json(settings);
});
app.get(internals.kLogoutURL, (_, res) => {
const returnTo = oidc_logoutRedirectURL || "/";
res.oidc.logout({
returnTo,
});
});
if (restricted) {
const allowedToView = (req) => {
if (!req.oidc?.user) {
return false;
}
const user = req.oidc.user;
const username = user.preferred_username || user.email;
if (restrictedDomains) {
const domains = restrictedDomains
.split(",")
.map((d) => d.trim());
const email = user.email || "";
const emailDomain = email.split("@")[1];
if (domains.includes(emailDomain)) {
return true;
}
}
if (restrictedUsers) {
const users = restrictedUsers
.split(",")
.map((u) => u.trim());
if (users.includes("*") || users.includes(username)) {
return true;
}
}
return false;
};
app.all("*", (req, res, next) => {
// Site flags are public.
if (req.url === "/favicon.png") {
return next();
}
if (!/\.(json|html)$/.test(req.url)) {
return next();
}
res.header(
"Access-Control-Allow-Origin",
req.get("Origin") || "*",
);
res.header("Access-Control-Allow-Credentials", "true");
if (
(security.isAuthorized(req) && owner !== null) ||
allowedToView(req)
) {
return next();
}
// Allow HTML views.
const htmlMatch = req.url.match(/\/(.*)\.html/);
if (htmlMatch) {
return res.redirect(`/view/${htmlMatch[1]}`);
}
// Sitemap is public.
if (req.url === "/system/sitemap.json") {
return res.json(["Login Required"]);
}
// If not allowed, show the login page.
const problem =
"This is a restricted wiki requires users to login to view pages. You do not have to be the site owner but you do need to login with a participating email address.";
const details = `[http://ward.asia.wiki.org/login-to-view.html details]`;
res.status(200).json({
title: "Login Required",
story: [
{
type: "paragraph",
id: "55d44b367ed64875",
text: `${problem} ${details}`,
},
],
});
});
}
},
};
return security;
};
|