-
Notifications
You must be signed in to change notification settings - Fork 100
/
index.js
executable file
·245 lines (179 loc) · 7.68 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
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
'use strict';
const Boom = require('boom');
const Bounce = require('bounce');
const Hoek = require('hoek');
const Joi = require('joi');
const internals = {};
module.exports = {
pkg: require('../package.json'),
requirements: {
hapi: '>=17.7.0'
},
register: (server, options) => {
server.auth.scheme('cookie', internals.implementation);
}
};
internals.schema = Joi.object({
cookie: Joi.string().default('sid'),
password: Joi.alternatives(Joi.string(), Joi.object().type(Buffer)).required(),
ttl: Joi.number().integer().min(0).allow(null).when('keepAlive', { is: true, then: Joi.required() }),
domain: Joi.string().allow(null),
path: Joi.string().default('/'),
clearInvalid: Joi.boolean().default(false),
keepAlive: Joi.boolean().default(false),
isSameSite: Joi.valid('Strict', 'Lax').allow(false).default('Strict'),
isSecure: Joi.boolean().default(true),
isHttpOnly: Joi.boolean().default(true),
redirectTo: Joi.alternatives(Joi.string(), Joi.func()).allow(false),
appendNext: Joi.alternatives(Joi.string(), Joi.boolean(), Joi.object({ raw: Joi.boolean(), name: Joi.string() })).default(false),
validateFunc: Joi.func(),
requestDecoratorName: Joi.string().default('cookieAuth'),
ignoreIfDecorated: Joi.boolean().default(true)
}).required();
internals.CookieAuth = class {
constructor(request, settings) {
this.request = request;
this.settings = settings;
}
set(session, value) {
const { h, request, settings } = this;
if (arguments.length > 1) {
const key = session;
Hoek.assert(key && typeof key === 'string', 'Invalid session key');
session = request.auth.artifacts;
Hoek.assert(session, 'No active session to apply key to');
session[key] = value;
return h.state(settings.cookie, session);
}
Hoek.assert(session && typeof session === 'object', 'Invalid session');
request.auth.artifacts = session;
h.state(settings.cookie, session);
}
clear(key) {
const { h, request, settings } = this;
if (arguments.length) {
Hoek.assert(key && typeof key === 'string', 'Invalid session key');
const session = request.auth.artifacts;
Hoek.assert(session, 'No active session to clear key from');
delete session[key];
return h.state(settings.cookie, session);
}
request.auth.artifacts = null;
h.unstate(settings.cookie);
}
ttl(msecs) {
const { h, request, settings } = this;
const session = request.auth.artifacts;
Hoek.assert(session, 'No active session to modify ttl on');
h.state(settings.cookie, session, { ttl: msecs });
}
};
internals.implementation = (server, options) => {
const results = Joi.validate(options, internals.schema);
Hoek.assert(!results.error, results.error);
const settings = results.value;
const cookieOptions = {
encoding: 'iron',
password: settings.password,
isSecure: settings.isSecure, // Defaults to true
path: settings.path,
isSameSite: settings.isSameSite,
isHttpOnly: settings.isHttpOnly, // Defaults to true
clearInvalid: settings.clearInvalid,
ignoreErrors: true
};
if (settings.ttl) {
cookieOptions.ttl = settings.ttl;
}
if (settings.domain) {
cookieOptions.domain = settings.domain;
}
if (typeof settings.appendNext === 'boolean') {
settings.appendNext = (settings.appendNext ? 'next' : '');
}
if (typeof settings.appendNext === 'object') {
settings.appendNextRaw = settings.appendNext.raw;
settings.appendNext = settings.appendNext.name || 'next';
}
server.state(settings.cookie, cookieOptions);
const decoration = (request) => {
return new internals.CookieAuth(request, settings);
};
// Check if the request object should be decorated
const isDecorated = server.decorations.request.indexOf(settings.requestDecoratorName) >= 0;
if (!settings.ignoreIfDecorated || !isDecorated) {
server.decorate('request', settings.requestDecoratorName, decoration, { apply: true });
}
server.ext('onPreAuth', (request, h) => {
// Used for setting and unsetting state, not for replying to request
request[settings.requestDecoratorName].h = h;
return h.continue;
});
const scheme = {
authenticate: async (request, h) => {
const validate = async () => {
// Check cookie
const session = request.state[settings.cookie];
if (!session) {
return unauthenticated(Boom.unauthorized(null, 'cookie'));
}
if (!settings.validateFunc) {
if (settings.keepAlive) {
h.state(settings.cookie, session);
}
return h.authenticated({ credentials: session, artifacts: session });
}
let credentials = session;
try {
const result = await settings.validateFunc(request, session);
Hoek.assert(typeof result === 'object', 'Invalid return from validateFunc');
Hoek.assert(Object.prototype.hasOwnProperty.call(result, 'valid'), 'validateFunc must have valid property in return');
if (!result.valid) {
throw Boom.unauthorized(null, 'cookie');
}
credentials = result.credentials || credentials;
if (settings.keepAlive) {
h.state(settings.cookie, session);
}
return h.authenticated({ credentials, artifacts: session });
}
catch (err) {
Bounce.rethrow(err, 'system');
if (settings.clearInvalid) {
h.unstate(settings.cookie);
}
const unauthorized = Boom.isBoom(err) && err.typeof === Boom.unauthorized ? err : Boom.unauthorized('Invalid cookie');
return unauthenticated(unauthorized, { credentials, artifacts: session });
}
};
const unauthenticated = (err, result) => {
let redirectTo = settings.redirectTo;
if (request.route.settings.plugins['hapi-auth-cookie'] &&
request.route.settings.plugins['hapi-auth-cookie'].redirectTo !== undefined) {
redirectTo = request.route.settings.plugins['hapi-auth-cookie'].redirectTo;
}
let uri = (typeof (redirectTo) === 'function') ? redirectTo(request) : redirectTo;
if (!uri || request.auth.mode !== 'required') {
return h.unauthenticated(err);
}
if (settings.appendNext) {
if (uri.indexOf('?') !== -1) {
uri += '&';
}
else {
uri += '?';
}
if (settings.appendNextRaw) {
uri += settings.appendNext + '=' + encodeURIComponent(request.raw.req.url);
}
else {
uri += settings.appendNext + '=' + encodeURIComponent(request.url.path);
}
}
return h.response('You are being redirected...').takeover().redirect(uri);
};
return await validate();
}
};
return scheme;
};