forked from mozilla/openbadges-backpack
/
badge.js
310 lines (267 loc) · 9.19 KB
/
badge.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
var mysql = require('../lib/mysql');
var regex = require('../lib/regex');
var crypto = require('crypto');
var Base = require('./mysql-base');
function sha256(value) {
var sum = crypto.createHash('sha256');
sum.update(value);
return sum.digest('hex');
}
function generateColor(str) {
var sum = crypto.createHash('md5');
sum.update(str);
return '#' + sum.digest('hex').substr(0,6);
}
function isDarkColor(color, cutoff) {
var rgb, r, g, b, brightness;
if (!(rgb = color.match(/^#?(?:([0-9a-f])([0-9a-f])([0-9a-f])|([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2}))$/)))
return null;
r = parseInt(rgb[1] || rgb[4] || 0, 16);
g = parseInt(rgb[2] || rgb[5] || 0, 16);
b = parseInt(rgb[3] || rgb[6] || 0, 16);
brightness = Math.sqrt(
r * r * 0.241 +
g * g * 0.691 +
b * b * 0.068
);
return brightness < (cutoff || 130);
}
var Badge = function (attributes) {
if (attributes) {
try {
var issuer = attributes.body.badge.issuer;
if (issuer && !issuer.color) {
var color = generateColor(attributes.body.badge.issuer.name);
attributes.body.badge.issuer.color = {
value: color,
dark: isDarkColor(color)
}
}
} catch (ex) {
// Do nothing - color is not that important
}
}
this.attributes = attributes;
};
Base.apply(Badge, 'badge');
Badge.prototype.presave = function () {
if (!this.get('id')) {
this.set('body_hash', sha256(JSON.stringify(this.get('body'))));
}
};
Badge.confirmRecipient = function confirmRecipient(assertion, email) {
// can't validate if not given an assertion
if (!assertion)
return false;
const recipient = assertion.recipient;
const salt = assertion.salt || '';
if (!recipient || !email)
return false;
if (typeof recipient !== 'string')
return false
// if it's an email address, do a straight comparison
if (/@/.test(recipient))
return recipient === email;
// if it's not an email address, it must have an alg and dollar sign.
if (!(recipient.match(/\w+(\d+)?\$.+/)))
return false;
const parts = recipient.split('$');
const algorithm = parts[0];
const expect = parts[1];
var hasher;
try {
hasher = crypto.createHash(algorithm);
} catch(e) {
// #TODO: should probably actually throw an error here.
return false;
}
// if there are more than 2 parts, it's an algorithm with options
// #TODO: support algorithms with options, throw instead of just
// returning false here.
if (parts.length !== 2)
return false;
const value = hasher.update(email + salt).digest('hex');
return value.toLowerCase() === expect.toLowerCase();
};
Badge.prototype.share = function share(callback) {
if (this.get('public_path'))
return callback(null, this);
this.presave();
this.set('public_path', this.get('body_hash'));
this.save(callback);
};
Badge.prototype.confirmRecipient = function confirmRecipient(email) {
return Badge.confirmRecipient(this.get('body'), email);
};
Badge.prototype.checkHash = function checkHash() {
return sha256(JSON.stringify(this.get('body'))) === this.get('body_hash');
};
// Validators called by `save()` (see mysql-base) in preparation for saving.
// A valid pass returns nothing (or a falsy value); an invalid pass returns a
// message about why a thing was invalid.
// #TODO: return either null or Error objects with more information about
// what's going on.
// TODO: make these errors more than strings so we don't have to parse
// them to figure out how to handle the error
Badge.validators = {
type: function (value, attributes) {
var valid = ['signed', 'hosted'];
if (valid.indexOf(value) === -1) {
return "Unknown type: " + value;
}
if (value === 'hosted' && !attributes.endpoint) {
return "If type is hosted, endpoint must be set";
}
if (value === 'signed' && !attributes.jwt) {
return "If type is signed, jwt must be set";
}
if (value === 'signed' && !attributes.public_key) {
return "If type is signed, public_key must be set";
}
},
endpoint: function (value, attributes) {
if (!value && attributes.type === 'hosted') {
return "If type is hosted, endpoint must be set";
}
},
jwt: function (value, attributes) {
if (!value && attributes.type === 'signed') {
return "If type is signed, jwt must be set";
}
},
public_key: function (value, attributes) {
if (!value && attributes.type === 'signed') {
return "If type is signed, public_key must be set";
}
},
image_path: function (value) {
if (!value) { return "Must have an image_path."; }
},
body: function (value) {
if (!value) { return "Must have a body."; }
if (String(value) !== '[object Object]') { return "body must be an object"; }
if (Badge.validateBody(value) instanceof Error) { return "invalid body"; }
}
};
Badge.findByUrl = function (url, callback) {
Badge.findOne({public_path: url}, callback);
};
// Prepare a field as it goes into or comes out of the database.
Badge.prepare = {
'in': { body: function (value) { return JSON.stringify(value); } },
'out': { body: function (value) { return JSON.parse(value); } }
};
// Virtual finders. By default, `find()` will take the keys of the criteria
// and create WHERE statements based on those. This object provides more
// nuanced control over how the query is formed and also allows creation
// of finders that don't map directly to a column name.
Badge.finders = {
email: function (value, callback) {
var query = "SELECT * FROM `badge` WHERE `user_id` = (SELECT `id` FROM `user` WHERE `email` = ?)";
mysql.client.query(query, [value], callback);
}
};
// Validate the structure and values of the body field, which contains the
// badge assertion as received from the issuer. Returns an error object with a
// `fields` attribute describing the errors if invalid, and `undefined` if
// valid.
Badge.validateBody = function (body) {
var err = new Error('Invalid badge assertion');
err.fields = {};
var internalClass = Object.prototype.toString.call(body);
if (!body || internalClass !== '[object Object]') {
err.message = 'Invalid badge assertion: invalid body';
return err
}
function fieldFromDottedString (str, obj) {
var fields = str.split('.');
var current = obj;
var previous = null;
fields.forEach(function (f) {
previous = current;
current = current[f];
});
return previous[fields.pop()];
}
var test = {
missing: function (fieldStr) {
var field = fieldFromDottedString(fieldStr, body);
if (!field) {
err.fields[fieldStr] = 'missing required field: `' + fieldStr + '`';
}
},
regexp: function (fieldStr, type) {
var field = fieldFromDottedString(fieldStr, body);
if (field && !regex[type].test(field)) {
err.fields[fieldStr] = 'invalid ' + type + ' for `' + fieldStr + '`';
}
},
length: function (fieldStr, maxlength) {
var field = fieldFromDottedString(fieldStr, body);
if (field && field.length > maxlength) {
err.fields[fieldStr] = 'invalid value for `' + fieldStr + '`: too long, maximum length should be ' + maxlength;
}
}
};
// begin tests
test.missing('recipient');
test.regexp('recipient', 'emailOrHash');
test.regexp('evidence', 'url');
test.regexp('expires', 'date');
test.regexp('issued_on', 'date');
if (!body.badge) {
err.fields['badge'] = 'missing required field `badge`';
} else {
test.missing('badge.version');
test.missing('badge.name');
test.missing('badge.description');
test.missing('badge.criteria');
test.missing('badge.image');
test.regexp('badge.version', 'version');
test.regexp('badge.image', 'url');
test.regexp('badge.criteria', 'url');
test.length('badge.name', 128);
test.length('badge.description', 128);
if (!body.badge.issuer) {
err.fields['badge.issuer'] = 'missing required field `badge.issuer`';
} else {
test.missing('badge.issuer.origin');
test.missing('badge.issuer.name');
test.regexp('badge.issuer.origin', 'origin');
test.regexp('badge.issuer.contact', 'email');
test.length('badge.issuer.org', 128);
test.length('badge.issuer.name', 128);
}
}
if (Object.keys(err.fields).length) { return err; }
return null;
};
// callback has the signature callback(err, {totalPerIssuer: ['issuer':1], totalBadges:1})
Badge.stats = function (callback) {
var totalBadges = 0;
var issuers = {};
Badge.findAll(function(err, badges) {
if (err) {
return callback(err);
}
totalBadges = badges.length;
badges.forEach(function (badge) {
var assertion = badge.get('body').badge;
if (!assertion.issuer) return;
var name = assertion.issuer.name;
var url = assertion.issuer.origin;
issuers[url] = issuers[url] || { name: name, total: 0 };
issuers[url].total++;
});
var urls = Object.keys(issuers);
var totalPerIssuer = urls.map(function (url) {
var issuer = issuers[url];
return { url: url, total: issuer.total, name: issuer.name }
});
totalPerIssuer.sort(function(issuer1, issuer2) {
return issuer2.total - issuer1.total
});
return callback(null, {totalPerIssuer: totalPerIssuer, totalBadges: totalBadges} );
});
}
module.exports = Badge;