-
Notifications
You must be signed in to change notification settings - Fork 4
/
auth.js
632 lines (585 loc) · 24 KB
/
auth.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
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
const PROFILE_LOGIN = 'http://iiif.io/api/auth/1/login';
const PROFILE_CLICKTHROUGH = 'http://iiif.io/api/auth/1/clickthrough';
const PROFILE_KIOSK = 'http://iiif.io/api/auth/1/kiosk';
const PROFILE_EXTERNAL = 'http://iiif.io/api/auth/1/external';
const PROFILE_TOKEN = 'http://iiif.io/api/auth/1/token';
const PROFILE_LOGOUT = 'http://iiif.io/api/auth/1/logout';
const PROFILE_PROBE = 'http://iiif.io/api/auth/1/probe';
const IMAGE_SERVICE_TYPE = 'ImageService2';
const HTTP_METHOD_GET = 'GET';
const HTTP_METHOD_HEAD = 'HEAD';
let viewer = null;
let dashPlayer = null;
let messages = {};
let sourcesMap = {};
window.addEventListener("message", receiveMessage, false);
// resolve returns { infoJson, status }
// reject returns an error message
function getInfoResponse(resourceId, token) {
/*
This now **synthesises** an object that can be passed around, describing the
resource and its auth services, and the user's current HTTP status, obtained
by interacting with the probe service.
If this is an image service, the info and the status are obtained by
making a GET request for the info.json.
If it isn't a service, the info is constructed from information already
supplied to the "viewer" (usually from a Manifest) and the status is obtained by
interacting with the probe service. If no explicit probe service is supplied,
the content resource acts as its own probe service and the viewer makes a HEAD
request against it. If an explicit probe service is provided, the viewer must make
a GET request for it, and observe both the HTTP status of the response, and
the contentLocation property of the probe response. If the response is a 200 but
the contentLocation is not what was asked for, it's just like a redirected info.json.
NOTE for implementers: resources arriving here will have a type.
In the UV (for example), a loaded P2 manifest won't have a type for the image service, but it will have a profile.
For consistency, the client should probably assign the resource a type:
myService.type = IMAGE_SERVICE_TYPE
*/
// we have already stored this information when initialising
let knownResource = sourcesMap[resourceId];
let info = null;
let probeService = resourceId;
let method = HTTP_METHOD_GET;
let cookieService = null;
if (knownResource.type == IMAGE_SERVICE_TYPE) {
probeService = resourceId + "/info.json";
log("this is a service, so the probe is " + probeService);
} else {
info = knownResource;
cookieService = first(knownResource.service, s => s.profile === PROFILE_LOGIN);
if (cookieService) {
let assertedProbeService = first(cookieService.service, s => s.profile === PROFILE_PROBE);
// Update 2022-09-23 to allow probe service to be directly asserted on resource, but also on cookie service to avoi breaking existing experiements.
if (!assertedProbeService) {
assertedProbeService = first(knownResource.service, s => s.profile === PROFILE_PROBE);
}
if (assertedProbeService) {
log("This resource asserts a separate probe service!");
probeService = assertedProbeService["@id"];
} else {
method = HTTP_METHOD_HEAD;
}
}
log("This is a content resource at " + resourceId);
log("The probe service is " + probeService);
}
log("Probe will be requested with HTTP " + method);
return new Promise((resolve, reject) => {
if (knownResource.type != IMAGE_SERVICE_TYPE && !cookieService) {
// no presence of, or possibility of auth; we don't know if the
// resource will respond to a HEAD and we don't want to send a token
// because that imposes CORS reqts on the server that they might
// not support because their content is open.
resolve({
info: info,
status: 200,
requestedId: resourceId,
cookieService: null
});
}
const request = new XMLHttpRequest();
request.open(method, probeService);
if (token) {
request.setRequestHeader("Authorization", "Bearer " + token);
}
request.onload = function() {
try {
if (this.status === 200 || this.status === 401) {
if (method == HTTP_METHOD_GET) {
probe = JSON.parse(this.response);
if (knownResource.type == IMAGE_SERVICE_TYPE) {
info = probe;
if (!info.hasOwnProperty("id")) {
info.id = probe.id || probe["@id"];
}
if (!info.hasOwnProperty("type")) {
info.type = IMAGE_SERVICE_TYPE;
}
} else {
info.id = probe.contentLocation;
}
}
resolve({
info: info,
status: this.status,
requestedId: resourceId,
cookieService: cookieService
});
} else {
reject(this.status + " " + this.statusText);
}
} catch (e) {
reject(e.message);
}
};
request.onerror = function() {
reject(this.status + " " + this.statusText);
};
request.send();
});
}
function init() {
const imageQs = /image=(.*)/g.exec(window.location.search);
const sourceQs = /sources=(.*)/g.exec(window.location.search);
const p3ManifestQs = /manifest=(.*)/g.exec(window.location.search)
if (imageQs && imageQs[1]) {
let imageServiceId = imageQs[1].replace(/\/info\.json$/, '');
sourcesMap[imageServiceId] = {
"type": IMAGE_SERVICE_TYPE,
"id": imageServiceId
}
selectResource(imageServiceId);
} else if (sourceQs && sourceQs[1]) {
loadSourceList(sourceQs[1]).then(sources => {
populateSourceList(sources);
});
} else if (p3ManifestQs && p3ManifestQs[1]) {
loadResourceFromManifest(p3ManifestQs[1]).then(resource => {
selectResource(resource);
});
} else {
document.querySelector("h1").innerText = "(no image on query string)";
}
}
function selectResource(resourceOrResourceId) {
let resource;
let resourceId;
if (resourceOrResourceId.hasOwnProperty("id")) {
resourceId = resourceOrResourceId.id;
resource = resourceOrResourceId;
} else {
resourceId = resourceOrResourceId;
resource = sourcesMap[resourceId];
}
// This will either be in the sourcesMap, or will be fetched as an info.json
// either way, we'll end up with an object that carries the resource URL and the auth services.
document.querySelector("h1").innerText = resourceId;
let resourceAnchor = document.getElementById("infoJson");
let resourceUrl = resourceId + "/info.json";
if (resource && resource.type != IMAGE_SERVICE_TYPE) {
// not an info.json; just display a link
resourceUrl = resource.id;
}
resourceAnchor.href = resourceUrl;
resourceAnchor.innerText = resourceUrl;
loadResource(resourceId).then(infoResponse => {
if (infoResponse) {
if (infoResponse.degraded || infoResponse.status === 401) {
doAuthChain(infoResponse);
}
}
});
}
function populateSourceList(sources) {
sourcesMap = {};
let sourceList = document.getElementById("sourceList");
sources.forEach(image => {
let opt = document.createElement("option");
opt.value = image.id;
opt.innerText = image.label;
sourceList.appendChild(opt);
sourcesMap[image.id] = image;
});
sourceList.style.display = "block";
sourceList.addEventListener("change", () => {
selectResource(sourceList.options[sourceList.selectedIndex].value);
});
let reloadButton = document.getElementById("reloadSource");
reloadButton.style.display = "block";
reloadButton.addEventListener("click", () => {
selectResource(sourceList.options[sourceList.selectedIndex].value);
});
}
function loadResourceFromManifest(manifestUrl) {
// This auth demo is not a Presentation API client, it's only for
// resources. But service-less resources are going to be found in
// Presentation 3 manifests, so it needs to load them to test. This
// just gets the first resource it can find.
sourcesMap = {};
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('GET', manifestUrl);
request.onload = function() {
try {
if (this.status === 200) {
manifest = JSON.parse(this.response);
if (manifest.items &&
manifest.items[0].items &&
manifest.items[0].items[0].items) {
// this is very fragile
const resource = manifest.items[0].items[0].items[0].body;
sourcesMap[resource.id] = resource;
resource.partOf = manifestUrl;
resolve(resource);
} else {
reject("Cannot find Presentation 3 resource in this manifest");
}
} else {
reject(this.status + " " + this.statusText);
}
} catch (e) {
reject(e.message);
}
};
request.onerror = function() {
reject(this.status + " " + this.statusText);
};
request.send();
});
}
// load a set of sample images from an instance of iiif-auth-server
function loadSourceList(sourcesUrl) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('GET', sourcesUrl);
request.onload = function() {
try {
if (this.status === 200) {
resolve(JSON.parse(this.response));
} else {
reject(this.status + " " + this.statusText);
}
} catch (e) {
reject(e.message);
}
};
request.onerror = function() {
reject(this.status + " " + this.statusText);
};
request.send();
});
}
async function loadResource(resourceId, token) {
let infoResponse;
try {
infoResponse = await getInfoResponse(resourceId, token);
} catch (e) {
log("Could not load " + resourceId);
log(e);
}
if (infoResponse && infoResponse.status === 200) {
renderResource(infoResponse, resourceId);
}
return infoResponse;
}
function renderResource(infoResponse, requestedResource) {
destroyViewer();
if (infoResponse.info.id != requestedResource) {
log("The requested imageService is " + requestedResource);
log("The id returned is " + infoResponse.info.id);
log("This image is most likely the degraded version of the one you asked for")
infoResponse.degraded = true;
}
if (infoResponse.info.type == IMAGE_SERVICE_TYPE) {
log("This resource is an image service.");
renderImageService(infoResponse.info);
} else {
log("The resource is of type " + infoResponse.info.type);
log("The resource is of format " + infoResponse.info.format);
let viewerHTML;
let isDash = (infoResponse.info.format == "application/dash+xml");
let avUrl = infoResponse.info.id;
if (infoResponse.info.type == "Video") {
viewerHTML = "<video id='html5AV' src='" + avUrl + "' autoplay>Video here</video>";
} else if (infoResponse.info.type == "Audio") {
viewerHTML = "<audio id='html5AV' src='" + avUrl + "' autoplay>audio here</audio>";
} else if (infoResponse.info.type == "Text" || infoResponse.info.type == "PhysicalObject") {
viewerHTML = "<a href='" + infoResponse.info.id + "' target='_blank'>Open document - " + infoResponse.info.label + "</a>";
} else {
viewerHTML = "<p>Not a known type</p>";
}
document.getElementById("viewer").innerHTML = viewerHTML;
if (isDash) {
dashPlayer = dashjs.MediaPlayer().create();
// Only send credentials for a DASH request if an auth service was present on the resource.
let withCredentials = infoResponse.cookieService != null;
dashPlayer.setXHRWithCredentialsForType("MPD", withCredentials);
// There's also
// dashPlayer.setXHRWithCredentialsForType("MediaSegment", true);
// dashPlayer.setXHRWithCredentialsForType("InitializationSegment", true);
// whether these get sent depends on whether the segment parts are authed with cookies,
// or with token fragments.
// TODO: How do we avoid the client having to work this out?
dashPlayer.initialize(document.querySelector("#html5AV"), avUrl, false);
// TODO - this is not getting destroyed correctly
}
}
}
function destroyViewer() {
if (viewer) {
viewer.destroy();
viewer = null;
}
dashPlayer = null;
document.getElementById("viewer").innerHTML = "";
document.getElementById("largeDownload").innerHTML = "";
}
function renderImageService(info) {
log("OSD will load " + info["@id"]);
viewer = OpenSeadragon({
id: "viewer",
prefixUrl: "openseadragon/images/",
tileSources: info
});
makeDownloadLink(info);
}
function makeDownloadLink(info) {
let largeDownload = document.getElementById("largeDownload");
let w = info["width"];
let h = info["height"]
let dims = "(" + w + " x " + h + ")";
maxWAssertion = first(info["profile"], pf => pf["maxWidth"]);
if (maxWAssertion) {
dims += " (max width is " + maxWAssertion["maxWidth"] + ")";
}
largeDownload.innerText = "Download large image: " + dims;
largeDownload.setAttribute("href", info["@id"] + "/full/full/0/default.jpg")
}
function asArray(obj) {
// wrap in array if singleton
if (obj) {
return (obj.constructor === Array ? obj : [obj]);
}
return [];
}
function first(objOrArray, predicate) {
let arr = asArray(objOrArray);
let filtered = arr.filter(predicate);
if (filtered.length > 0) {
return filtered[0];
}
return null;
}
async function attemptImageWithToken(authService, imageService) {
log("attempting token interaction for " + authService["@id"]);
let tokenService = first(authService.service, s => s.profile === PROFILE_TOKEN);
if (tokenService) {
log("found token service: " + tokenService["@id"]);
let tokenMessage = await openTokenService(tokenService);
if (tokenMessage && tokenMessage.accessToken) {
let withTokenInfoResponse = await loadResource(imageService, tokenMessage.accessToken);
log("info request with token resulted in " + withTokenInfoResponse.status);
if (withTokenInfoResponse.status == 200) {
renderResource(withTokenInfoResponse, imageService);
return true;
}
}
}
log("Didn't get a 200 info response.")
return false;
}
async function doAuthChain(infoResponse) {
// This function enters the flowchart at the < External? > junction
// http://iiif.io/api/auth/1.0/#workflow-from-the-browser-client-perspective
if (!infoResponse.info.service) {
log("No services found")
return;
}
let services = asArray(infoResponse.info.service);
let lastAttempted = null;
let requestedId = infoResponse.requestedId;
// repetition of logic is left in these steps for clarity:
log("Looking for external pattern");
let serviceToTry = first(services, s => s.profile === PROFILE_EXTERNAL);
if (serviceToTry) {
lastAttempted = serviceToTry;
let success = await attemptImageWithToken(serviceToTry, requestedId);
if (success) return;
}
log("Looking for kiosk pattern");
serviceToTry = first(services, s => s.profile === PROFILE_KIOSK);
if (serviceToTry) {
lastAttempted = serviceToTry;
let kioskWindow = openContentProviderWindow(serviceToTry);
if (kioskWindow) {
await userInteractionWithContentProvider(kioskWindow);
let success = await attemptImageWithToken(serviceToTry, requestedId);
if (success) return;
} else {
log("Could not open kiosk window");
}
}
// The code for the next two patterns is identical (other than the profile name).
// The difference is in the expected behaviour of
//
// await userInteractionWithContentProvider(contentProviderWindow);
//
// For clickthrough the opened window should close immediately having established
// a session, whereas for login the user might spend some time entering credentials etc.
log("Looking for clickthrough pattern");
serviceToTry = first(services, s => s.profile === PROFILE_CLICKTHROUGH);
if (serviceToTry) {
lastAttempted = serviceToTry;
let contentProviderWindow = await getContentProviderWindowFromModal(serviceToTry);
if (contentProviderWindow) {
// should close immediately
await userInteractionWithContentProvider(contentProviderWindow);
let success = await attemptImageWithToken(serviceToTry, requestedId);
if (success) return;
}
}
log("Looking for login pattern");
serviceToTry = first(services, s => s.profile === PROFILE_LOGIN);
if (serviceToTry) {
lastAttempted = serviceToTry;
let contentProviderWindow = await getContentProviderWindowFromModal(serviceToTry);
if (contentProviderWindow) {
// we expect the user to spend some time interacting
await userInteractionWithContentProvider(contentProviderWindow);
let success = await attemptImageWithToken(serviceToTry, requestedId);
if (success) return;
}
}
// nothing worked! Use the most recently tried service as the source of
// messages to show to the user.
showOutOfOptionsMessages(lastAttempted);
}
// determine the postMessage-style origin for a URL
function getOrigin(url) {
let urlHolder = window.location;
if (url) {
urlHolder = document.createElement('a');
urlHolder.href = url;
}
return urlHolder.protocol + "//" + urlHolder.hostname + (urlHolder.port ? ':' + urlHolder.port : '');
}
function* MessageIdGenerator() {
var messageId = 1; // don't start at 0, it's falsey
while (true) yield messageId++;
}
var messageIds = MessageIdGenerator();
function openTokenService(tokenService) {
// use a Promise across a postMessage call. Discuss...
return new Promise((resolve, reject) => {
// if necessary, the client can decide not to trust this origin
const serviceOrigin = getOrigin(tokenService["@id"]);
const messageId = messageIds.next().value;
messages[messageId] = {
"resolve": resolve,
"reject": reject,
"serviceOrigin": serviceOrigin
};
var tokenUrl = tokenService["@id"] + "?messageId=" + messageId + "&origin=" + getOrigin();
document.getElementById("commsFrame").src = tokenUrl;
// reject any unhandled messages after a configurable timeout
const postMessageTimeout = 5000;
setTimeout(() => {
if (messages[messageId]) {
messages[messageId].reject(
"Message unhandled after " + postMessageTimeout + "ms, rejecting");
delete messages[messageId];
}
}, postMessageTimeout);
});
}
// The event listener for postMessage. Needs to take care it only
// responds to messages initiated by openTokenService(..)
// Completes promises made in openTokenService(..)
function receiveMessage(event) {
log("event received, origin=" + event.origin);
log(JSON.stringify(event.data));
let rejectValue = "postMessage event received but rejected.";
if (event.data.hasOwnProperty("messageId")) {
log("recieved message with id " + event.data.messageId);
var message = messages[event.data.messageId];
if (message && event.origin == message.serviceOrigin) {
// Any message with a messageId is a success
log("We trust that we triggered this message, so resolve")
message.resolve(event.data);
delete messages[event.data.messageId];
return;
}
}
}
function userInteractionWithContentProvider(contentProviderWindow) {
return new Promise((resolve) => {
// What happens here is forever a mystery to a client application.
// It can but wait.
var poll = window.setInterval(() => {
if (contentProviderWindow.closed) {
log("cookie service window is now closed")
window.clearInterval(poll);
resolve();
}
}, 500);
});
}
function sanitise(s, allowHtml) {
// Unimplemented
// Viewers should already have an HTML sanitiser library, for metadata etc
if (allowHtml) {
// sanitise but allow permitted tags
return s;
}
// return text content only
return s;
}
function openContentProviderWindow(service) {
let cookieServiceUrl = service["@id"] + "?origin=" + getOrigin();
log("Opening content provider window: " + cookieServiceUrl);
return window.open(cookieServiceUrl);
}
function getContentProviderWindowFromModal(service) {
return new Promise(resolve => {
hideModals();
modal = document.getElementById("beforeOpenCookieServiceModal");
modal.querySelector(".close").onclick = (ev => {
hideModals();
resolve(null);
});
modal.querySelector("#csConfirm").onclick = (ev => {
log("Interacting with cookie service in new tab - " + service["@id"]);
let win = openContentProviderWindow(service);
hideModals();
resolve(win);
});
modal.querySelector("#csCancel").onclick = (ev => {
hideModals();
resolve(null);
});
if (service.label) {
modal.querySelector("#csLabel").innerText = sanitise(service.label);
}
if (service.header) {
modal.querySelector("#csHeader").innerText = sanitise(service.header);
}
if (service.description) {
modal.querySelector("#csDescription").innerText = sanitise(service.description, true);
}
if (service.confirmLabel) {
modal.querySelector("#csConfirm").innerText = sanitise(service.confirmLabel);
}
modal.style.display = "block";
});
}
function showOutOfOptionsMessages(service) {
hideModals();
modal = document.getElementById("failureModal");
modal.querySelector(".close").onclick = (ev => hideModals());
modal.querySelector("#failureClose").onclick = (ev => hideModals());
if (service.failureHeader) {
modal.querySelector("#failureHeader").innerText = sanitise(service.failureHeader);
}
if (service.failureDescription) {
modal.querySelector("#failureDescription").innerText = sanitise(service.failureDescription, true);
}
modal.style.display = "block";
}
function hideModals() {
let modals = document.querySelectorAll(".modal");
modals.forEach(m => {
m.style.display = "none";
m.querySelectorAll("*").forEach(el => {
el.onclick = null;
});
});
}
function log(text) {
var logDiv = document.querySelector("#usermessages");
var p = document.createElement("p");
p.innerText = text;
logDiv.appendChild(p);
logDiv.scrollTop = logDiv.scrollHeight;
console.log(text);
}
init();