openid.js
42.8 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
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
/* OpenID for node.js
*
* http://ox.no/software/node-openid
* http://github.com/havard/node-openid
*
* Copyright (C) 2010 by Håvard Stranden
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*
* -*- Mode: JS; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set sw=2 ts=2 et tw=80 :
*/
var convert = require('./lib/convert'),
crypto = require('crypto'),
http = require('http'),
https = require('https'),
querystring = require('querystring'),
url = require('url'),
xrds = require('./lib/xrds');
var _associations = {};
var _discoveries = {};
var openid = exports;
openid.RelyingParty = function(returnUrl, realm, stateless, strict, extensions)
{
this.returnUrl = returnUrl;
this.realm = realm || null;
this.stateless = stateless;
this.strict = strict;
this.extensions = extensions;
}
openid.RelyingParty.prototype.authenticate = function(identifier, immediate, callback)
{
openid.authenticate(identifier, this.returnUrl, this.realm,
immediate, this.stateless, callback, this.extensions, this.strict);
}
openid.RelyingParty.prototype.verifyAssertion = function(requestOrUrl, callback)
{
openid.verifyAssertion(requestOrUrl, callback, this.stateless, this.extensions, this.strict);
}
var _isDef = function(e)
{
var undefined;
return e !== undefined;
}
var _toBase64 = function(binary)
{
return convert.base64.encode(convert.btwoc(binary));
}
var _fromBase64 = function(str)
{
return convert.unbtwoc(convert.base64.decode(str));
}
var _xor = function(a, b)
{
if(a.length != b.length)
{
throw new Error('Length must match for xor');
}
var r = '';
for(var i = 0; i < a.length; ++i)
{
r += String.fromCharCode(a.charCodeAt(i) ^ b.charCodeAt(i));
}
return r;
}
openid.saveAssociation = function(provider, type, handle, secret, expiry_time_in_seconds, callback)
{
setTimeout(function() {
openid.removeAssociation(handle);
}, expiry_time_in_seconds * 1000);
_associations[handle] = {provider: provider, type : type, secret: secret};
callback(null); // Custom implementations may report error as first argument
}
openid.loadAssociation = function(handle, callback)
{
if(_isDef(_associations[handle]))
{
callback(null, _associations[handle]);
}
else
{
callback(null, null);
}
}
openid.removeAssociation = function(handle)
{
delete _associations[handle];
return true;
}
openid.saveDiscoveredInformation = function(key, provider, callback)
{
_discoveries[key] = provider;
return callback(null);
}
openid.loadDiscoveredInformation = function(key, callback)
{
if(!_isDef(_discoveries[key]))
{
return callback(null, null);
}
return callback(null, _discoveries[key]);
}
var _buildUrl = function(theUrl, params)
{
theUrl = url.parse(theUrl, true);
delete theUrl['search'];
if(params)
{
if(!theUrl.query)
{
theUrl.query = params;
}
else
{
for(var key in params)
{
if(params.hasOwnProperty(key))
{
theUrl.query[key] = params[key];
}
}
}
}
return url.format(theUrl);
}
var _proxyRequest = function(protocol, options)
{
/*
If process.env['HTTP_PROXY_HOST'] and the env variable `HTTP_PROXY_POST`
are set, make sure path and the header Host are set to target url.
Similarly, `HTTPS_PROXY_HOST` and `HTTPS_PROXY_PORT` can be used
to proxy HTTPS traffic.
Proxies Example:
export HTTP_PROXY_HOST=localhost
export HTTP_PROXY_PORT=8080
export HTTPS_PROXY_HOST=localhost
export HTTPS_PROXY_PORT=8442
Function returns protocol which should be used for network request, one of
http: or https:
*/
var targetHost = options.host;
var newProtocol = protocol;
if (!targetHost) return;
var updateOptions = function (envPrefix) {
var proxyHostname = process.env[envPrefix + '_PROXY_HOST'].trim();
var proxyPort = parseInt(process.env[envPrefix + '_PROXY_PORT'], 10);
if (proxyHostname.length > 0 && ! isNaN(proxyPort)) {
if (! options.headers) options.headers = {};
var targetHostAndPort = targetHost + ':' + options.port;
options.host = proxyHostname;
options.port = proxyPort;
options.path = protocol + '//' + targetHostAndPort + options.path;
options.headers['Host'] = targetHostAndPort;
}
};
if ('https:' === protocol &&
!! process.env['HTTPS_PROXY_HOST'] &&
!! process.env['HTTPS_PROXY_PORT']) {
updateOptions('HTTPS');
// Proxy server request must be done via http... it is responsible for
// Making the https request...
newProtocol = 'http:';
} else if (!! process.env['HTTP_PROXY_HOST'] &&
!! process.env['HTTP_PROXY_PORT']) {
updateOptions('HTTP');
}
return newProtocol;
}
var _get = function(getUrl, params, callback, redirects)
{
redirects = redirects || 5;
getUrl = url.parse(_buildUrl(getUrl, params));
var path = getUrl.pathname || '/';
if(getUrl.query)
{
path += '?' + getUrl.query;
}
var options =
{
host: getUrl.hostname,
port: _isDef(getUrl.port) ? parseInt(getUrl.port, 10) :
(getUrl.protocol == 'https:' ? 443 : 80),
headers: { 'Accept' : 'application/xrds+xml,text/html,text/plain,*/*' },
path: path
};
var protocol = _proxyRequest(getUrl.protocol, options);
(protocol == 'https:' ? https : http).get(options, function(res)
{
var data = '';
res.on('data', function(chunk)
{
data += chunk;
});
var isDone = false;
var done = function()
{
if (isDone) return;
isDone = true;
if(res.headers.location && --redirects)
{
var redirectUrl = res.headers.location;
if(redirectUrl.indexOf('http') !== 0)
{
redirectUrl = getUrl.protocol + '//' + getUrl.hostname + ':' + options.port + (redirectUrl.indexOf('/') === 0 ? redirectUrl : '/' + redirectUrl);
}
_get(redirectUrl, params, callback, redirects);
}
else
{
callback(data, res.headers, res.statusCode);
}
}
res.on('end', function() { done(); });
res.on('close', function() { done(); });
}).on('error', function(error)
{
return callback(error);
});
}
var _post = function(postUrl, data, callback, redirects)
{
redirects = redirects || 5;
postUrl = url.parse(postUrl);
var path = postUrl.pathname || '/';
if(postUrl.query)
{
path += '?' + postUrl.query;
}
var encodedData = _encodePostData(data);
var options =
{
host: postUrl.hostname,
path: path,
port: _isDef(postUrl.port) ? postUrl.port :
(postUrl.protocol == 'https:' ? 443 : 80),
headers:
{
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': encodedData.length
},
method: 'POST'
};
var protocol = _proxyRequest(postUrl.protocol, options);
(protocol == 'https:' ? https : http).request(options, function(res)
{
var data = '';
res.on('data', function(chunk)
{
data += chunk;
});
var isDone = false;
var done = function()
{
if (isDone) return;
isDone = true;
if(res.headers.location && --redirects)
{
_post(res.headers.location, data, callback, redirects);
}
else
{
callback(data, res.headers, res.statusCode);
}
}
res.on('end', function() { done(); });
res.on('close', function() { done(); });
}).on('error', function(error)
{
return callback(error);
}).end(encodedData);
}
var _encodePostData = function(data)
{
var encoded = querystring.stringify(data);
return encoded;
}
var _decodePostData = function(data)
{
var lines = data.split('\n');
var result = {};
for (var i = 0; i < lines.length ; i++) {
var line = lines[i];
if (line.length > 0 && line[line.length - 1] == '\r') {
line = line.substring(0, line.length - 1);
}
var colon = line.indexOf(':');
if (colon === -1)
{
continue;
}
var key = line.substr(0, line.indexOf(':'));
var value = line.substr(line.indexOf(':') + 1);
result[key] = value;
}
return result;
}
var _normalizeIdentifier = function(identifier)
{
identifier = identifier.replace(/^\s+|\s+$/g, '');
if(!identifier)
return null;
if(identifier.indexOf('xri://') === 0)
{
identifier = identifier.substring(6);
}
if(/^[(=@\+\$!]/.test(identifier))
{
return identifier;
}
if(identifier.indexOf('http') === 0)
{
return identifier;
}
return 'http://' + identifier;
}
var _parseXrds = function(xrdsUrl, xrdsData)
{
var services = xrds.parse(xrdsData);
if(services == null)
{
return null;
}
var providers = [];
for(var i = 0, len = services.length; i < len; ++i)
{
var service = services[i];
var provider = {};
provider.endpoint = service.uri;
if(/https?:\/\/xri./.test(xrdsUrl))
{
provider.claimedIdentifier = service.id;
}
if(service.type == 'http://specs.openid.net/auth/2.0/signon')
{
provider.version = 'http://specs.openid.net/auth/2.0';
provider.localIdentifier = service.id;
}
else if(service.type == 'http://specs.openid.net/auth/2.0/server')
{
provider.version = 'http://specs.openid.net/auth/2.0';
}
else if(service.type == 'http://openid.net/signon/1.0' ||
service.type == 'http://openid.net/signon/1.1')
{
provider.version = service.type;
provider.localIdentifier = service.delegate;
}
else
{
continue;
}
providers.push(provider);
}
return providers;
}
var _matchMetaTag = function(html)
{
var metaTagMatches = /<meta\s+.*?http-equiv="x-xrds-location"\s+(.*?)>/ig.exec(html);
if(!metaTagMatches || metaTagMatches.length < 2)
{
return null;
}
var contentMatches = /content="(.*?)"/ig.exec(metaTagMatches[1]);
if(!contentMatches || contentMatches.length < 2)
{
return null;
}
return contentMatches[1];
}
var _matchLinkTag = function(html, rel)
{
var providerLinkMatches = new RegExp('<link\\s+.*?rel=["\'][^"\']*?' + rel + '[^"\']*?["\'].*?>', 'ig').exec(html);
if(!providerLinkMatches || providerLinkMatches.length < 1)
{
return null;
}
var href = /href=["'](.*?)["']/ig.exec(providerLinkMatches[0]);
if(!href || href.length < 2)
{
return null;
}
return href[1];
}
var _parseHtml = function(htmlUrl, html, callback, hops)
{
var metaUrl = _matchMetaTag(html);
if(metaUrl != null)
{
return _resolveXri(metaUrl, callback, hops + 1);
}
var provider = _matchLinkTag(html, 'openid2.provider');
if(provider == null)
{
provider = _matchLinkTag(html, 'openid.server');
if(provider == null)
{
callback(null);
}
else
{
var localId = _matchLinkTag(html, 'openid.delegate');
callback([{
version: 'http://openid.net/signon/1.1',
endpoint: provider,
claimedIdentifier: htmlUrl,
localIdentifier : localId
}]);
}
}
else
{
var localId = _matchLinkTag(html, 'openid2.local_id');
callback([{
version: 'http://specs.openid.net/auth/2.0/signon',
endpoint: provider,
claimedIdentifier: htmlUrl,
localIdentifier : localId
}]);
}
}
var _parseHostMeta = function(hostMeta, callback)
{
var match = /^Link: <([^\n\r]+)>;/.exec(hostMeta);
if(match != null)
{
var xriUrl = match[0].slice(7,match.length - 4);
_resolveXri(xriUrl, callback);
}
else
{
callback(null)
}
}
var _resolveXri = function(xriUrl, callback, hops)
{
if(!hops)
{
hops = 1;
}
else if(hops >= 5)
{
return callback(null);
}
_get(xriUrl, null, function(data, headers, statusCode)
{
if(statusCode != 200)
{
return callback(null);
}
var xrdsLocation = headers['x-xrds-location'];
if(_isDef(xrdsLocation))
{
_get(xrdsLocation, null, function(data, headers, statusCode)
{
if(statusCode != 200 || data == null)
{
callback(null);
}
else
{
callback(_parseXrds(xrdsLocation, data));
}
});
}
else if(data != null)
{
var contentType = headers['content-type'];
// text/xml is not compliant, but some hosting providers refuse header
// changes, so text/xml is encountered
if(contentType && (contentType.indexOf('application/xrds+xml') === 0 || contentType.indexOf('text/xml') === 0))
{
return callback(_parseXrds(xriUrl, data));
}
else
{
return _resolveHtml(xriUrl, callback, hops + 1, data);
}
}
});
}
var _resolveHtml = function(identifier, callback, hops, data)
{
if(!hops)
{
hops = 1;
}
else if(hops >= 5)
{
return callback(null);
}
if(data == null)
{
_get(identifier, null, function(data, headers, statusCode)
{
if(statusCode != 200 || data == null)
{
callback(null);
}
else
{
_parseHtml(identifier, data, callback, hops + 1);
}
});
}
else
{
_parseHtml(identifier, data, callback, hops);
}
}
var _resolveHostMeta = function(identifier, strict, callback, fallBackToProxy)
{
var host = url.parse(identifier);
var hostMetaUrl;
if(fallBackToProxy && !strict)
{
hostMetaUrl = 'https://www.google.com/accounts/o8/.well-known/host-meta?hd=' + host.host
}
else
{
hostMetaUrl = host.protocol + '//' + host.host + '/.well-known/host-meta';
}
if(!hostMetaUrl)
{
callback(null);
}
else
{
_get(hostMetaUrl, null, function(data, headers, statusCode)
{
if(statusCode != 200 || data == null)
{
if(!fallBackToProxy && !strict){
_resolveHostMeta(identifier, strict, callback, true);
}
else{
callback(null);
}
}
else
{
//Attempt to parse the data but if this fails it may be because
//the response to hostMetaUrl was some other http/html resource.
//Therefore fallback to the proxy if no providers are found.
_parseHostMeta(data, function(providers){
if((providers == null || providers.length == 0) && !fallBackToProxy && !strict){
_resolveHostMeta(identifier, strict, callback, true);
}
else{
callback(providers);
}
});
}
});
}
}
openid.discover = function(identifier, strict, callback)
{
identifier = _normalizeIdentifier(identifier);
if(!identifier)
{
return callback({ message: 'Invalid identifier' }, null);
}
if(identifier.indexOf('http') !== 0)
{
// XRDS
identifier = 'https://xri.net/' + identifier + '?_xrd_r=application/xrds%2Bxml';
}
// Try XRDS/Yadis discovery
_resolveXri(identifier, function(providers)
{
if(providers == null || providers.length == 0)
{
// Fallback to HTML discovery
_resolveHtml(identifier, function(providers)
{
if(providers == null || providers.length == 0){
_resolveHostMeta(identifier, strict, function(providers){
callback(null, providers);
});
}
else{
callback(null, providers);
}
});
}
else
{
// Add claimed identifier to providers with local identifiers
// and OpenID 1.0/1.1 providers to ensure correct resolution
// of identities and services
for(var i = 0, len = providers.length; i < len; ++i)
{
var provider = providers[i];
if(!provider.claimedIdentifier &&
(provider.localIdentifier || provider.version.indexOf('2.0') === -1))
{
provider.claimedIdentifier = identifier;
}
}
callback(null, providers);
}
});
}
var _createDiffieHellmanKeyExchange = function(algorithm)
{
var defaultPrime = 'ANz5OguIOXLsDhmYmsWizjEOHTdxfo2Vcbt2I3MYZuYe91ouJ4mLBX+YkcLiemOcPym2CBRYHNOyyjmG0mg3BVd9RcLn5S3IHHoXGHblzqdLFEi/368Ygo79JRnxTkXjgmY0rxlJ5bU1zIKaSDuKdiI+XUkKJX8Fvf8W8vsixYOr';
var dh = crypto.createDiffieHellman(defaultPrime, 'base64');
dh.generateKeys();
return dh;
}
openid.associate = function(provider, callback, strict, algorithm)
{
var params = _generateAssociationRequestParameters(provider.version, algorithm);
if(!_isDef(algorithm))
{
algorithm = 'DH-SHA256';
}
var dh = null;
if(algorithm.indexOf('no-encryption') === -1)
{
dh = _createDiffieHellmanKeyExchange(algorithm);
params['openid.dh_modulus'] = _toBase64(dh.getPrime('binary'));
params['openid.dh_gen'] = _toBase64(dh.getGenerator('binary'));
params['openid.dh_consumer_public'] = _toBase64(dh.getPublicKey('binary'));
}
_post(provider.endpoint, params, function(data, headers, statusCode)
{
if ((statusCode != 200 && statusCode != 400) || data === null)
{
return callback({
message: 'HTTP request failed'
}, {
error: 'HTTP request failed',
error_code: '' + statusCode,
ns: 'http://specs.openid.net/auth/2.0'
});
}
data = _decodePostData(data);
if(data.error_code == 'unsupported-type' || !_isDef(data.ns))
{
if(algorithm == 'DH-SHA1')
{
if(strict && provider.endpoint.toLowerCase().indexOf('https:') !== 0)
{
return callback({ message: 'Channel is insecure and no encryption method is supported by provider' }, null);
}
else
{
return openid.associate(provider, callback, strict, 'no-encryption-256');
}
}
else if(algorithm == 'no-encryption-256')
{
if(strict && provider.endpoint.toLowerCase().indexOf('https:') !== 0)
{
return callback('Channel is insecure and no encryption method is supported by provider', null);
}
/*else if(provider.version.indexOf('2.0') === -1)
{
// 2011-07-22: This is an OpenID 1.0/1.1 provider which means
// HMAC-SHA1 has already been attempted with a blank session
// type as per the OpenID 1.0/1.1 specification.
// (See http://openid.net/specs/openid-authentication-1_1.html#mode_associate)
// However, providers like wordpress.com don't follow the
// standard and reject these requests, but accept OpenID 2.0
// style requests without a session type, so we have to give
// those a shot as well.
callback({ message: 'Provider is OpenID 1.0/1.1 and does not support OpenID 1.0/1.1 association.' });
}*/
else
{
return openid.associate(provider, callback, strict, 'no-encryption');
}
}
else if(algorithm == 'DH-SHA256')
{
return openid.associate(provider, callback, strict, 'DH-SHA1');
}
}
if (data.error)
{
callback({ message: data.error }, data);
}
else
{
var secret = null;
var hashAlgorithm = algorithm.indexOf('256') !== -1 ? 'sha256' : 'sha1';
if(algorithm.indexOf('no-encryption') !== -1)
{
secret = data.mac_key;
}
else
{
var serverPublic = _fromBase64(data.dh_server_public);
var sharedSecret = convert.btwoc(dh.computeSecret(serverPublic, 'binary', 'binary'));
var hash = crypto.createHash(hashAlgorithm);
hash.update(sharedSecret);
sharedSecret = hash.digest('binary');
var encMacKey = convert.base64.decode(data.enc_mac_key);
secret = convert.base64.encode(_xor(encMacKey, sharedSecret));
}
if (!_isDef(data.assoc_handle)) {
return callback({ message: 'OpenID provider does not seem to support association; you need to use stateless mode'}, null);
}
openid.saveAssociation(provider, hashAlgorithm,
data.assoc_handle, secret, data.expires_in * 1, function(error)
{
if(error)
{
return callback(error);
}
callback(null, data);
});
}
});
}
var _generateAssociationRequestParameters = function(version, algorithm)
{
var params = {
'openid.mode' : 'associate',
};
if(version.indexOf('2.0') !== -1)
{
params['openid.ns'] = 'http://specs.openid.net/auth/2.0';
}
if(algorithm == 'DH-SHA1')
{
params['openid.assoc_type'] = 'HMAC-SHA1';
params['openid.session_type'] = 'DH-SHA1';
}
else if(algorithm == 'no-encryption-256')
{
if(version.indexOf('2.0') === -1)
{
params['openid.session_type'] = ''; // OpenID 1.0/1.1 requires blank
params['openid.assoc_type'] = 'HMAC-SHA1';
}
else
{
params['openid.session_type'] = 'no-encryption';
params['openid.assoc_type'] = 'HMAC-SHA256';
}
}
else if(algorithm == 'no-encryption')
{
if(version.indexOf('2.0') !== -1)
{
params['openid.session_type'] = 'no-encryption';
}
params['openid.assoc_type'] = 'HMAC-SHA1';
}
else
{
params['openid.assoc_type'] = 'HMAC-SHA256';
params['openid.session_type'] = 'DH-SHA256';
}
return params;
}
openid.authenticate = function(identifier, returnUrl, realm, immediate, stateless, callback, extensions, strict)
{
openid.discover(identifier, strict, function(error, providers)
{
if(error)
{
return callback(error);
}
if(!providers || providers.length === 0)
{
return callback({ message: 'No providers found for the given identifier' }, null);
}
var providerIndex = -1;
(function chooseProvider(error, authUrl)
{
if(!error && authUrl)
{
var provider = providers[providerIndex];
if(provider.claimedIdentifier)
{
var useLocalIdentifierAsKey = provider.version.indexOf('2.0') === -1 && provider.localIdentifier && provider.claimedIdentifier != provider.localIdentifier;
return openid.saveDiscoveredInformation(useLocalIdentifierAsKey ? provider.localIdentifier : provider.claimedIdentifier,
provider, function(error)
{
if(error)
{
return callback(error);
}
return callback(null, authUrl);
});
}
else if(provider.version.indexOf('2.0') !== -1)
{
return callback(null, authUrl);
}
else
{
chooseProvider({ message: 'OpenID 1.0/1.1 provider cannot be used without a claimed identifier' });
}
}
if(++providerIndex >= providers.length)
{
return callback({ message: 'No usable providers found for the given identifier' }, null);
}
var currentProvider = providers[providerIndex];
if(stateless)
{
_requestAuthentication(currentProvider, null, returnUrl,
realm, immediate, extensions || {}, chooseProvider);
}
else
{
openid.associate(currentProvider, function(error, answer)
{
if(error || !answer || answer.error)
{
chooseProvider(error || answer.error, null);
}
else
{
_requestAuthentication(currentProvider, answer.assoc_handle, returnUrl,
realm, immediate, extensions || {}, chooseProvider);
}
});
}
})();
});
}
var _requestAuthentication = function(provider, assoc_handle, returnUrl, realm, immediate, extensions, callback)
{
var params = {
'openid.mode' : immediate ? 'checkid_immediate' : 'checkid_setup'
};
if(provider.version.indexOf('2.0') !== -1)
{
params['openid.ns'] = 'http://specs.openid.net/auth/2.0';
}
for (var i in extensions)
{
if(!extensions.hasOwnProperty(i))
{
continue;
}
var extension = extensions[i];
for (var key in extension.requestParams)
{
if (!extension.requestParams.hasOwnProperty(key)) { continue; }
params[key] = extension.requestParams[key];
}
}
if(provider.claimedIdentifier)
{
params['openid.claimed_id'] = provider.claimedIdentifier;
if(provider.localIdentifier)
{
params['openid.identity'] = provider.localIdentifier;
}
else
{
params['openid.identity'] = provider.claimedIdentifier;
}
}
else if(provider.version.indexOf('2.0') !== -1)
{
params['openid.claimed_id'] = params['openid.identity'] =
'http://specs.openid.net/auth/2.0/identifier_select';
}
else {
return callback({ message: 'OpenID 1.0/1.1 provider cannot be used without a claimed identifier' });
}
if(assoc_handle)
{
params['openid.assoc_handle'] = assoc_handle;
}
if(returnUrl)
{
// Value should be missing if RP does not want
// user to be sent back
params['openid.return_to'] = returnUrl;
}
if(realm)
{
if(provider.version.indexOf('2.0') !== -1) {
params['openid.realm'] = realm;
}
else {
params['openid.trust_root'] = realm;
}
}
else if(!returnUrl)
{
return callback({ message: 'No return URL or realm specified' });
}
callback(null, _buildUrl(provider.endpoint, params));
}
openid.verifyAssertion = function(requestOrUrl, callback, stateless, extensions, strict)
{
extensions = extensions || {};
var assertionUrl = requestOrUrl;
if(typeof(requestOrUrl) !== typeof(''))
{
if(requestOrUrl.method == 'POST') {
if((requestOrUrl.headers['content-type'] || '').toLowerCase().indexOf('application/x-www-form-urlencoded') === 0) {
// POST response received
var data = '';
requestOrUrl.on('data', function(chunk) {
data += chunk;
});
requestOrUrl.on('end', function() {
var params = querystring.parse(data);
return _verifyAssertionData(params, callback, stateless, extensions, strict);
});
}
else {
return callback({ message: 'Invalid POST response from OpenID provider' });
}
return; // Avoid falling through to GET method assertion
}
else if(requestOrUrl.method != 'GET') {
return callback({ message: 'Invalid request method from OpenID provider' });
}
assertionUrl = requestOrUrl.url;
}
assertionUrl = url.parse(assertionUrl, true);
var params = assertionUrl.query;
return _verifyAssertionData(params, callback, stateless, extensions, strict);
}
var _verifyAssertionData = function(params, callback, stateless, extensions, strict) {
var assertionError = _getAssertionError(params);
if(assertionError)
{
return callback({ message: assertionError }, { authenticated: false });
}
if (!_invalidateAssociationHandleIfRequested(params)) {
return callback({ message: 'Unable to invalidate association handle'});
}
// TODO: Check nonce if OpenID 2.0
_verifyDiscoveredInformation(params, stateless, extensions, strict, function(error, result)
{
return callback(error, result);
});
};
var _getAssertionError = function(params)
{
if(!_isDef(params))
{
return 'Assertion request is malformed';
}
else if(params['openid.mode'] == 'error')
{
return params['openid.error'];
}
else if(params['openid.mode'] == 'cancel')
{
return 'Authentication cancelled';
}
return null;
}
var _invalidateAssociationHandleIfRequested = function(params)
{
if (params['is_valid'] == 'true' && _isDef(params['openid.invalidate_handle'])) {
if(!openid.removeAssociation(params['openid.invalidate_handle'])) {
return false;
}
}
return true;
}
var _verifyDiscoveredInformation = function(params, stateless, extensions, strict, callback)
{
var claimedIdentifier = params['openid.claimed_id'];
var useLocalIdentifierAsKey = false;
if(!_isDef(claimedIdentifier))
{
if(!_isDef(params['openid.ns']))
{
// OpenID 1.0/1.1 response without a claimed identifier
// We need to load discovered information using the
// local identifier
useLocalIdentifierAsKey = true;
}
else {
// OpenID 2.0+:
// If there is no claimed identifier, then the
// assertion is not about an identity
return callback(null, { authenticated: false });
}
}
if (useLocalIdentifierAsKey) {
claimedIdentifier = params['openid.identity'];
}
claimedIdentifier = _getCanonicalClaimedIdentifier(claimedIdentifier);
openid.loadDiscoveredInformation(claimedIdentifier, function(error, provider)
{
if(error)
{
return callback({ message: 'An error occured when loading previously discovered information about the claimed identifier' });
}
if(provider)
{
return _verifyAssertionAgainstProviders([provider], params, stateless, extensions, callback);
}
else if (useLocalIdentifierAsKey) {
return callback({ message: 'OpenID 1.0/1.1 response received, but no information has been discovered about the provider. It is likely that this is a fraudulent authentication response.' });
}
openid.discover(claimedIdentifier, strict, function(error, providers)
{
if(error)
{
return callback(error);
}
if(!providers || !providers.length)
{
return callback({ message: 'No OpenID provider was discovered for the asserted claimed identifier' });
}
_verifyAssertionAgainstProviders(providers, params, stateless, extensions, callback);
});
});
}
var _verifyAssertionAgainstProviders = function(providers, params, stateless, extensions, callback)
{
for(var i = 0; i < providers.length; ++i)
{
var provider = providers[i];
if(!!params['openid.ns'] && (!provider.version || provider.version.indexOf(params['openid.ns']) !== 0))
{
continue;
}
if(!!provider.version && provider.version.indexOf('2.0') !== -1)
{
var endpoint = params['openid.op_endpoint'];
if (provider.endpoint != endpoint)
{
continue;
}
if(provider.claimedIdentifier) {
var claimedIdentifier = _getCanonicalClaimedIdentifier(params['openid.claimed_id']);
if(provider.claimedIdentifier != claimedIdentifier) {
return callback({ message: 'Claimed identifier in assertion response does not match discovered claimed identifier' });
}
}
}
if(!!provider.localIdentifier && provider.localIdentifier != params['openid.identity'])
{
return callback({ message: 'Identity in assertion response does not match discovered local identifier' });
}
return _checkSignature(params, provider, stateless, function(error, result)
{
if(error)
{
return callback(error);
}
if(extensions && result.authenticated)
{
for(var ext in extensions)
{
if (!extensions.hasOwnProperty(ext))
{
continue;
}
var instance = extensions[ext];
instance.fillResult(params, result);
}
}
return callback(null, result);
});
}
callback({ message: 'No valid providers were discovered for the asserted claimed identifier' });
}
var _checkSignature = function(params, provider, stateless, callback)
{
if(!_isDef(params['openid.signed']) ||
!_isDef(params['openid.sig']))
{
return callback({ message: 'No signature in response' }, { authenticated: false });
}
if(stateless)
{
_checkSignatureUsingProvider(params, provider, callback);
}
else
{
_checkSignatureUsingAssociation(params, callback);
}
}
var _checkSignatureUsingAssociation = function(params, callback)
{
if (!_isDef(params['openid.assoc_handle']))
{
return callback({ message: 'No association handle in provider response. Find out whether the provider supports associations and/or use stateless mode.' });
}
openid.loadAssociation(params['openid.assoc_handle'], function(error, association)
{
if(error)
{
return callback({ message: 'Error loading association' }, { authenticated: false });
}
if(!association)
{
return callback({ message:'Invalid association handle' }, { authenticated: false });
}
if(association.provider.version.indexOf('2.0') !== -1 && association.provider.endpoint !== params['openid.op_endpoint'])
{
return callback({ message:'Association handle does not match provided endpoint' }, {authenticated: false});
}
var message = '';
var signedParams = params['openid.signed'].split(',');
for(var i = 0; i < signedParams.length; i++)
{
var param = signedParams[i];
var value = params['openid.' + param];
if(!_isDef(value))
{
return callback({ message: 'At least one parameter referred in signature is not present in response' }, { authenticated: false });
}
message += param + ':' + value + '\n';
}
var hmac = crypto.createHmac(association.type, convert.base64.decode(association.secret));
hmac.update(message, 'utf8');
var ourSignature = hmac.digest('base64');
if(ourSignature == params['openid.sig'])
{
callback(null, { authenticated: true, claimedIdentifier: association.provider.version.indexOf('2.0') !== -1 ? params['openid.claimed_id'] : association.provider.claimedIdentifier });
}
else
{
callback({ message: 'Invalid signature' }, { authenticated: false });
}
});
}
var _checkSignatureUsingProvider = function(params, provider, callback)
{
var requestParams =
{
'openid.mode' : 'check_authentication'
};
for(var key in params)
{
if(params.hasOwnProperty(key) && key != 'openid.mode')
{
requestParams[key] = params[key];
}
}
_post(_isDef(params['openid.ns']) ? (params['openid.op_endpoint'] || provider.endpoint) : provider.endpoint, requestParams, function(data, headers, statusCode)
{
if(statusCode != 200 || data == null)
{
return callback({ message: 'Invalid assertion response from provider' }, { authenticated: false });
}
else
{
data = _decodePostData(data);
if(data['is_valid'] == 'true')
{
return callback(null, { authenticated: true, claimedIdentifier: provider.version.indexOf('2.0') !== -1 ? params['openid.claimed_id'] : params['openid.identity'] });
}
else
{
return callback({ message: 'Invalid signature' }, { authenticated: false });
}
}
});
}
var _getCanonicalClaimedIdentifier = function(claimedIdentifier) {
if(!claimedIdentifier) {
return claimedIdentifier;
}
var index = claimedIdentifier.indexOf('#');
if (index !== -1) {
return claimedIdentifier.substring(0, index);
}
return claimedIdentifier;
};
/* ==================================================================
* Extensions
* ==================================================================
*/
var _getExtensionAlias = function(params, ns)
{
for (var k in params)
if (params[k] == ns)
return k.replace("openid.ns.", "");
}
/*
* Simple Registration Extension
* http://openid.net/specs/openid-simple-registration-extension-1_1-01.html
*/
var sreg_keys = ['nickname', 'email', 'fullname', 'dob', 'gender', 'postcode', 'country', 'language', 'timezone'];
openid.SimpleRegistration = function SimpleRegistration(options)
{
this.requestParams = {'openid.ns.sreg': 'http://openid.net/extensions/sreg/1.1'};
if (options.policy_url)
this.requestParams['openid.sreg.policy_url'] = options.policy_url;
var required = [];
var optional = [];
for (var i = 0; i < sreg_keys.length; i++)
{
var key = sreg_keys[i];
if (options[key])
{
if (options[key] == 'required')
{
required.push(key);
}
else
{
optional.push(key);
}
}
if (required.length)
{
this.requestParams['openid.sreg.required'] = required.join(',');
}
if (optional.length)
{
this.requestParams['openid.sreg.optional'] = optional.join(',');
}
}
};
openid.SimpleRegistration.prototype.fillResult = function(params, result)
{
var extension = _getExtensionAlias(params, 'http://openid.net/extensions/sreg/1.1') || 'sreg';
for (var i = 0; i < sreg_keys.length; i++)
{
var key = sreg_keys[i];
if (params['openid.' + extension + '.' + key])
{
result[key] = params['openid.' + extension + '.' + key];
}
}
};
/*
* User Interface Extension
* http://svn.openid.net/repos/specifications/user_interface/1.0/trunk/openid-user-interface-extension-1_0.html
*/
openid.UserInterface = function UserInterface(options)
{
if (typeof(options) != 'object')
{
options = { mode: options || 'popup' };
}
this.requestParams = {'openid.ns.ui': 'http://specs.openid.net/extensions/ui/1.0'};
for (var k in options)
{
this.requestParams['openid.ui.' + k] = options[k];
}
};
openid.UserInterface.prototype.fillResult = function(params, result)
{
// TODO: Fill results
}
/*
* Attribute Exchange Extension
* http://openid.net/specs/openid-attribute-exchange-1_0.html
* Also see:
* - http://www.axschema.org/types/
* - http://code.google.com/intl/en-US/apis/accounts/docs/OpenID.html#Parameters
*/
// TODO: count handling
var attributeMapping =
{
'http://axschema.org/contact/country/home': 'country'
, 'http://axschema.org/contact/email': 'email'
, 'http://axschema.org/namePerson/first': 'firstname'
, 'http://axschema.org/pref/language': 'language'
, 'http://axschema.org/namePerson/last': 'lastname'
// The following are not in the Google document:
, 'http://axschema.org/namePerson/friendly': 'nickname'
, 'http://axschema.org/namePerson': 'fullname'
};
openid.AttributeExchange = function AttributeExchange(options)
{
this.requestParams = {'openid.ns.ax': 'http://openid.net/srv/ax/1.0',
'openid.ax.mode' : 'fetch_request'};
var required = [];
var optional = [];
for (var ns in options)
{
if (!options.hasOwnProperty(ns)) { continue; }
if (options[ns] == 'required')
{
required.push(ns);
}
else
{
optional.push(ns);
}
}
var self = this;
required = required.map(function(ns, i)
{
var attr = attributeMapping[ns] || 'req' + i;
self.requestParams['openid.ax.type.' + attr] = ns;
return attr;
});
optional = optional.map(function(ns, i)
{
var attr = attributeMapping[ns] || 'opt' + i;
self.requestParams['openid.ax.type.' + attr] = ns;
return attr;
});
if (required.length)
{
this.requestParams['openid.ax.required'] = required.join(',');
}
if (optional.length)
{
this.requestParams['openid.ax.if_available'] = optional.join(',');
}
}
openid.AttributeExchange.prototype.fillResult = function(params, result)
{
var extension = _getExtensionAlias(params, 'http://openid.net/srv/ax/1.0') || 'ax';
var regex = new RegExp('^openid\\.' + extension + '\\.(value|type)\\.(\\w+)$');
var aliases = {};
var values = {};
for (var k in params)
{
if (!params.hasOwnProperty(k)) { continue; }
var matches = k.match(regex);
if (!matches)
{
continue;
}
if (matches[1] == 'type')
{
aliases[params[k]] = matches[2];
}
else
{
values[matches[2]] = params[k];
}
}
for (var ns in aliases)
{
if (aliases[ns] in values)
{
result[aliases[ns]] = values[aliases[ns]];
result[ns] = values[aliases[ns]];
}
}
}
openid.OAuthHybrid = function(options)
{
this.requestParams = {
'openid.ns.oauth' : 'http://specs.openid.net/extensions/oauth/1.0',
'openid.oauth.consumer' : options['consumerKey'],
'openid.oauth.scope' : options['scope']};
}
openid.OAuthHybrid.prototype.fillResult = function(params, result)
{
var extension = _getExtensionAlias(params, 'http://specs.openid.net/extensions/oauth/1.0') || 'oauth'
, token_attr = 'openid.' + extension + '.request_token';
if(params[token_attr] !== undefined)
{
result['request_token'] = params[token_attr];
}
};
/*
* Provider Authentication Policy Extension (PAPE)
* http://openid.net/specs/openid-provider-authentication-policy-extension-1_0.html
*
* Note that this extension does not validate that the provider is obeying the
* authentication request, it only allows the request to be made.
*
* TODO: verify requested 'max_auth_age' against response 'auth_time'
* TODO: verify requested 'auth_level.ns.<cust>' (etc) against response 'auth_level.ns.<cust>'
* TODO: verify requested 'preferred_auth_policies' against response 'auth_policies'
*
*/
/* Just the keys that aren't open to customisation */
var pape_request_keys = ['max_auth_age', 'preferred_auth_policies', 'preferred_auth_level_types' ];
var pape_response_keys = ['auth_policies', 'auth_time']
/* Some short-hand mappings for auth_policies */
var papePolicyNameMap =
{
'phishing-resistant': 'http://schemas.openid.net/pape/policies/2007/06/phishing-resistant',
'multi-factor': 'http://schemas.openid.net/pape/policies/2007/06/multi-factor',
'multi-factor-physical': 'http://schemas.openid.net/pape/policies/2007/06/multi-factor-physical',
'none' : 'http://schemas.openid.net/pape/policies/2007/06/none'
}
openid.PAPE = function PAPE(options)
{
this.requestParams = {'openid.ns.pape': 'http://specs.openid.net/extensions/pape/1.0'};
for (var k in options)
{
if (k === 'preferred_auth_policies') {
this.requestParams['openid.pape.' + k] = _getLongPolicyName(options[k]);
} else {
this.requestParams['openid.pape.' + k] = options[k];
}
}
var util = require('util');
};
/* you can express multiple pape 'preferred_auth_policies', so replace each
* with the full policy URI as per papePolicyNameMapping.
*/
var _getLongPolicyName = function(policyNames) {
var policies = policyNames.split(' ');
for (var i=0; i<policies.length; i++) {
if (policies[i] in papePolicyNameMap) {
policies[i] = papePolicyNameMap[policies[i]];
}
}
return policies.join(' ');
}
var _getShortPolicyName = function(policyNames) {
var policies = policyNames.split(' ');
for (var i=0; i<policies.length; i++) {
for (shortName in papePolicyNameMap) {
if (papePolicyNameMap[shortName] === policies[i]) {
policies[i] = shortName;
}
}
}
return policies.join(' ');
}
openid.PAPE.prototype.fillResult = function(params, result)
{
var extension = _getExtensionAlias(params, 'http://specs.openid.net/extensions/pape/1.0') || 'pape';
var paramString = 'openid.' + extension + '.';
var thisParam;
for (var p in params) {
if (params.hasOwnProperty(p)) {
if (p.substr(0, paramString.length) === paramString) {
thisParam = p.substr(paramString.length);
if (thisParam === 'auth_policies') {
result[thisParam] = _getShortPolicyName(params[p]);
} else {
result[thisParam] = params[p];
}
}
}
}
}