This repository was archived by the owner on May 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathSolidClient.js
More file actions
265 lines (239 loc) · 8.43 KB
/
SolidClient.js
File metadata and controls
265 lines (239 loc) · 8.43 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
const { URL, resolve, parse: parseUrl } = require('url');
const https = require('https');
const querystring = require('querystring');
const RelyingParty = require('@solid/oidc-rp');
const PoPToken = require('@solid/oidc-rp/lib/PoPToken');
// Fake redirect URL
const redirectUrl = 'http://example.org/';
class SolidClient {
constructor({ identityManager }) {
this._identityManager = identityManager;
}
/**
* Logs the user in with the given identity provider
*
* @param identityProvider string The URL of the identity provider
* @param credentials object An object with username and password keys
*
* @returns Promise<Session> A session for the given user
*/
async login(identityProvider, credentials) {
// Obtain a relying party
const relyingParty = await this.getRelyingParty(identityProvider);
// Load or create a session
const username = credentials.username;
let session = this._identityManager.getSession(relyingParty, username);
if (!session || this.isExpired(session)) {
session = await this.createSession(relyingParty, credentials);
this._identityManager.addSession(relyingParty, username, session);
}
return session;
}
/**
* Logs the user in with the given identity provider
*
* @param relyingParty RelyingParty The relying party
* @param credentials object An object with username and password keys
*
* @returns Promise<Session> A session for the given user
*/
async createSession(relyingParty, credentials) {
// Obtain the authorization URL
const authData = {};
const authUrl = await relyingParty.createRequest({ redirect_uri: redirectUrl }, authData);
// Perform the login
const loginParams = await this.getLoginParams(authUrl);
const accessUrl = await this.performLogin(loginParams.loginUrl, loginParams, credentials);
const session = await relyingParty.validateResponse(accessUrl, authData);
return session;
}
/**
* Creates an access token for the given URL.
*
* @param url string
* @param session Session
*
* @returns Promise<string> An access token
*/
async createToken(url, session) {
return PoPToken.issueFor(url, session);
}
/**
* Obtains a relying party for the given identity provider.
*
* @param identityProvider string The URL of the identity provider
*
* @returns Promise<RelyingParty> A relying party
*/
async getRelyingParty(identityProvider) {
// Try to load an existing relying party
let relyingParty;
const providerSettings = this._identityManager.getProviderSettings(identityProvider);
if (providerSettings) {
relyingParty = RelyingParty.from(providerSettings);
}
// Create a new relying party
else {
relyingParty = await this.registerRelyingParty(identityProvider);
this._identityManager.addProviderSettings(relyingParty);
}
return relyingParty;
}
/**
* Registers a relying party for the given identity provider.
*
* @param identityProvider string The URL of the identity provider
*
* @returns Promise<RelyingParty> A relying party
*/
async registerRelyingParty(identityProvider) {
const responseType = 'id_token token';
const registration = {
issuer: identityProvider,
grant_types: ['implicit'],
redirect_uris: [redirectUrl],
response_types: [responseType],
scope: 'openid profile',
};
const options = {
defaults: {
authenticate: {
redirect_uri: redirectUrl,
response_type: responseType,
},
},
};
return RelyingParty.register(identityProvider, registration, options);
}
/**
* Obtains the login parameters through the given authentication URL.
*
* @param authUrl String The authentication URL
*
* @returns Promise<object> A key/value object of login parameters
*/
async getLoginParams(authUrl) {
// Retrieve the login page in HTML
const authorizationPage = await this.fetch(authUrl);
const loginPageUrl = resolve(authUrl, authorizationPage.headers.location);
const loginPage = await this.fetch(loginPageUrl);
// Extract the password form's target URL
const passwordForm = loginPage.body.match(/<form[^]*?<\/form>/)[0];
const loginUrl = resolve(loginPageUrl, passwordForm.match(/action="([^"]+)"/)[1]);
// Extract the password form's hidden fields
const loginParams = { loginUrl };
let match, inputRegex = /<input.*?name="([^"]+)".*?value="([^"]+)"/g;
while ((match = inputRegex.exec(passwordForm)))
loginParams[match[1]] = match[2];
return loginParams;
}
/**
* Sends the login information to the login page.
*
* @param loginUrl string The URL of the login page
* @param loginParams object The login parameters
* @param credentials object The user's credentials
*
* @returns Promise<string> An access URL.
*/
async performLogin(loginUrl, loginParams, credentials) {
// Set the credentials
loginParams.username = credentials.username;
loginParams.password = credentials.password;
// Perform the login POST request
const options = parseUrl(loginUrl);
const postData = querystring.stringify(loginParams);
options.method = 'POST';
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length,
};
const loginResponse = await this.fetch(options, postData);
// Verify the login was successful
if (loginResponse.statusCode !== 302) {
const message = loginResponse.body.match(/<strong>(.*?)<\/strong>/);
const cause = message ? message[1] : 'unknown cause';
throw new Error(`Could not log in: ${cause}`);
}
// Redirect to the authentication page, passing the session cookie
let authUrl = loginResponse.headers.location;
const cookie = loginResponse.headers['set-cookie'][0].replace(/;.*/, '');
// Handle the new consent page in 5.1.1
if (this.isAboveVersion511(loginResponse.headers['x-powered-by'])) {
const consentUrl = new URL(authUrl);
const search = consentUrl.search.substring(1);
if (!search) {
throw new Error(`Login response doesn't contain a search string: ${authUrl}`);
}
let consPostData = {};
try {
const searchJson = decodeURIComponent(search)
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/\=/g, '":"');
consPostData = JSON.parse(`{"${searchJson}"}`);
}
catch (error) {
throw new Error(
`Login response doesn't contain a search string: ${authUrl}, causing a JSON parsing error: ${error}`
);
}
consPostData.consent = true;
consPostData.access_mode = ['Read', 'Write', 'Append', 'Control'];
consPostData = querystring.stringify(consPostData);
const consOptions = parseUrl(`${consentUrl.origin}${consentUrl.pathname}`);
consOptions.method = 'POST';
consOptions.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': consPostData.length,
cookie,
};
const consentResponse = await this.fetch(consOptions, consPostData);
authUrl = consentResponse.headers.location;
}
const authResponse = await this.fetch(
Object.assign(parseUrl(authUrl), {
headers: { cookie },
})
);
// Obtain the access URL from the redirected response
const accessUrl = authResponse.headers.location;
return accessUrl;
}
isAboveVersion511(version) {
return /^solid-server\/5\.(1\.[1-9]|[2-9]|1\d)/.test(version);
}
/**
* Fetches the given resource over HTTP.
*
* @param options object The request options
* @param data? string The request body
*
* @returns Promise<Response> The HTTP response with a body property
*/
fetch(options, data) {
return new Promise((resolve, reject) => {
const request = https.request(options);
request.end(data);
request.on('response', response => {
response.body = '';
response.on('data', data => (response.body += data));
response.on('end', () => resolve(response));
});
request.on('error', reject);
});
}
/**
* Determines whether the session has expired.
*
* @param session object The session
*
* @returns boolean Whether the session has expired
*/
isExpired(session) {
const now = Date.now() / 1000;
const expiry = (session.idClaims && session.idClaims.exp) || 0;
return expiry < now;
}
}
module.exports = SolidClient;