@vue-skuilder/express 0.2.24 → 0.2.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -43,6 +43,164 @@ function(newDoc, oldDoc, userCtx, secObj) {
|
|
|
43
43
|
|
|
44
44
|
return;
|
|
45
45
|
}
|
|
46
|
+
|
|
47
|
+
// ---------------------------------------------------------------------------
|
|
48
|
+
// Dynamic card ELO: any authenticated user may update an existing CARD doc
|
|
49
|
+
// iff the ONLY thing that changed is 'elo', and the 'elo' change is a
|
|
50
|
+
// single bounded ELO step (see isBoundedEloStep below). This is what lets
|
|
51
|
+
// content difficulty settle from live study traffic without giving learners
|
|
52
|
+
// write access to anything else on the card.
|
|
53
|
+
//
|
|
54
|
+
// ES5 only (CouchDB SpiderMonkey): no let/const/arrow/for-of/Object.entries.
|
|
55
|
+
// ---------------------------------------------------------------------------
|
|
56
|
+
var ELO_MAX_STEP = 64; // must match K_MAX in @vue-skuilder/common elo.ts
|
|
57
|
+
|
|
58
|
+
function isPlainObject(x) {
|
|
59
|
+
return x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Structural deep equality. Key order is irrelevant (a client round-trip
|
|
63
|
+
// does not preserve it), so never compare serialized JSON.
|
|
64
|
+
function deepEqual(a, b) {
|
|
65
|
+
if (a === b) return true;
|
|
66
|
+
if (typeof a !== typeof b) return false;
|
|
67
|
+
if (a === null || b === null) return false;
|
|
68
|
+
if (typeof a !== 'object') {
|
|
69
|
+
// NaN !== NaN; treat two NaNs as equal for robustness
|
|
70
|
+
return a !== a && b !== b;
|
|
71
|
+
}
|
|
72
|
+
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
73
|
+
if (Array.isArray(a)) {
|
|
74
|
+
if (a.length !== b.length) return false;
|
|
75
|
+
for (var i = 0; i < a.length; i++) {
|
|
76
|
+
if (!deepEqual(a[i], b[i])) return false;
|
|
77
|
+
}
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
var ka = Object.keys(a);
|
|
81
|
+
var kb = Object.keys(b);
|
|
82
|
+
if (ka.length !== kb.length) return false;
|
|
83
|
+
for (var j = 0; j < ka.length; j++) {
|
|
84
|
+
var k = ka[j];
|
|
85
|
+
if (!Object.prototype.hasOwnProperty.call(b, k)) return false;
|
|
86
|
+
if (!deepEqual(a[k], b[k])) return false;
|
|
87
|
+
}
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function isEloRank(r) {
|
|
92
|
+
return isPlainObject(r) && typeof r.score === 'number' && typeof r.count === 'number';
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function isCourseElo(e) {
|
|
96
|
+
return isPlainObject(e) && isEloRank(e.global) && isPlainObject(e.tags);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Compare an EloRank 'n' against its predecessor 'o'. Returns null if OK,
|
|
100
|
+
// else a reason string. 'label' names the rank for the message.
|
|
101
|
+
// - unchanged (score & count equal, other fields equal) -> OK
|
|
102
|
+
// - one step: count === old.count + 1, |score delta| <= ELO_MAX_STEP,
|
|
103
|
+
// every field other than score/count deep-equal -> OK
|
|
104
|
+
function checkRankStep(label, o, n) {
|
|
105
|
+
if (!isEloRank(n)) return label + ' must have numeric score and count';
|
|
106
|
+
if (!isEloRank(o)) return label + ' has no valid prior rank to step from';
|
|
107
|
+
// Non-bounded fields must be identical
|
|
108
|
+
var keys = Object.keys(n).concat(Object.keys(o));
|
|
109
|
+
for (var i = 0; i < keys.length; i++) {
|
|
110
|
+
var k = keys[i];
|
|
111
|
+
if (k === 'score' || k === 'count') continue;
|
|
112
|
+
if (!deepEqual(o[k], n[k])) return label + ': only score and count may change (field "' + k + '")';
|
|
113
|
+
}
|
|
114
|
+
if (n.count === o.count && n.score === o.score) return null; // untouched
|
|
115
|
+
if (n.count !== o.count + 1) {
|
|
116
|
+
return label + ': count must increment by exactly 1 (was ' + o.count + ', got ' + n.count + ')';
|
|
117
|
+
}
|
|
118
|
+
if (Math.abs(n.score - o.score) > ELO_MAX_STEP) {
|
|
119
|
+
return label + ': score may move at most ' + ELO_MAX_STEP + ' per update (was ' + o.score + ', got ' + n.score + ')';
|
|
120
|
+
}
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Compare a tag entry that does not exist on the old doc. The framework
|
|
125
|
+
// initialises a new card-side tag rank at the card's (old) global score
|
|
126
|
+
// with count 0, then applies one step.
|
|
127
|
+
function checkNewRank(label, baseScore, n) {
|
|
128
|
+
if (!isEloRank(n)) return label + ' must have numeric score and count';
|
|
129
|
+
var keys = Object.keys(n);
|
|
130
|
+
for (var i = 0; i < keys.length; i++) {
|
|
131
|
+
if (keys[i] !== 'score' && keys[i] !== 'count') {
|
|
132
|
+
return label + ': a new tag rank may only carry score and count (field "' + keys[i] + '")';
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (n.count !== 1) return label + ': a new tag rank must have count 1 (got ' + n.count + ')';
|
|
136
|
+
if (Math.abs(n.score - baseScore) > ELO_MAX_STEP) {
|
|
137
|
+
return label + ': a new tag rank must start within ' + ELO_MAX_STEP + ' of the card global score ' + baseScore + ' (got ' + n.score + ')';
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function isBoundedEloStep(oldElo, newElo) {
|
|
143
|
+
if (!isCourseElo(newElo)) return 'elo must have the CourseElo shape {global:{score,count}, tags:{...}}';
|
|
144
|
+
if (!isCourseElo(oldElo)) return 'existing elo is not CourseElo-shaped; cannot apply a bounded step';
|
|
145
|
+
|
|
146
|
+
// Top-level elo keys other than global/tags must be unchanged (e.g. misc)
|
|
147
|
+
var topKeys = Object.keys(newElo).concat(Object.keys(oldElo));
|
|
148
|
+
for (var t = 0; t < topKeys.length; t++) {
|
|
149
|
+
var tk = topKeys[t];
|
|
150
|
+
if (tk === 'global' || tk === 'tags') continue;
|
|
151
|
+
if (!deepEqual(oldElo[tk], newElo[tk])) return 'elo.' + tk + ' may not change';
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
var reason = checkRankStep('elo.global', oldElo.global, newElo.global);
|
|
155
|
+
if (reason) return reason;
|
|
156
|
+
|
|
157
|
+
// No tag deletions
|
|
158
|
+
var oldTags = Object.keys(oldElo.tags);
|
|
159
|
+
for (var d = 0; d < oldTags.length; d++) {
|
|
160
|
+
if (!Object.prototype.hasOwnProperty.call(newElo.tags, oldTags[d])) {
|
|
161
|
+
return 'elo.tags["' + oldTags[d] + '"] may not be removed';
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
var newTags = Object.keys(newElo.tags);
|
|
166
|
+
for (var n = 0; n < newTags.length; n++) {
|
|
167
|
+
var tag = newTags[n];
|
|
168
|
+
var label = 'elo.tags["' + tag + '"]';
|
|
169
|
+
if (Object.prototype.hasOwnProperty.call(oldElo.tags, tag)) {
|
|
170
|
+
reason = checkRankStep(label, oldElo.tags[tag], newElo.tags[tag]);
|
|
171
|
+
} else {
|
|
172
|
+
reason = checkNewRank(label, oldElo.global.score, newElo.tags[tag]);
|
|
173
|
+
}
|
|
174
|
+
if (reason) return reason;
|
|
175
|
+
}
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (newDoc.docType === 'CARD' && oldDoc.docType === 'CARD') {
|
|
180
|
+
if (!userCtx.name) {
|
|
181
|
+
throw({forbidden: "You must be logged in to update card elo"});
|
|
182
|
+
}
|
|
183
|
+
if (newDoc._id !== oldDoc._id) {
|
|
184
|
+
throw({forbidden: "Card elo update: _id may not change"});
|
|
185
|
+
}
|
|
186
|
+
// Every field except elo and revision metadata must be unchanged.
|
|
187
|
+
// _attachments (stubs) IS compared. _rev/_revisions/_conflicts etc. are
|
|
188
|
+
// couch bookkeeping the client may or may not echo back, so skip them.
|
|
189
|
+
var allKeys = Object.keys(newDoc).concat(Object.keys(oldDoc));
|
|
190
|
+
for (var f = 0; f < allKeys.length; f++) {
|
|
191
|
+
var field = allKeys[f];
|
|
192
|
+
if (field === 'elo') continue;
|
|
193
|
+
if (field.charAt(0) === '_' && field !== '_id' && field !== '_attachments') continue;
|
|
194
|
+
if (!deepEqual(oldDoc[field], newDoc[field])) {
|
|
195
|
+
throw({forbidden: 'Card elo update: only the elo field may change (field "' + field + '" differs)'});
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
var eloReason = isBoundedEloStep(oldDoc.elo, newDoc.elo);
|
|
199
|
+
if (eloReason) {
|
|
200
|
+
throw({forbidden: 'Card elo update rejected: ' + eloReason});
|
|
201
|
+
}
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
46
204
|
|
|
47
205
|
// For updates to existing documents, deny if not the original author
|
|
48
206
|
if (oldDoc && oldDoc.author && oldDoc.author !== userCtx.name) {
|
|
@@ -54,4 +212,4 @@ function(newDoc, oldDoc, userCtx, secObj) {
|
|
|
54
212
|
if (newDoc._id.indexOf('_design/') === 0) {
|
|
55
213
|
throw({forbidden: "Only admins can modify design documents"});
|
|
56
214
|
}
|
|
57
|
-
}
|
|
215
|
+
}
|
|
@@ -43,6 +43,164 @@ function(newDoc, oldDoc, userCtx, secObj) {
|
|
|
43
43
|
|
|
44
44
|
return;
|
|
45
45
|
}
|
|
46
|
+
|
|
47
|
+
// ---------------------------------------------------------------------------
|
|
48
|
+
// Dynamic card ELO: any authenticated user may update an existing CARD doc
|
|
49
|
+
// iff the ONLY thing that changed is 'elo', and the 'elo' change is a
|
|
50
|
+
// single bounded ELO step (see isBoundedEloStep below). This is what lets
|
|
51
|
+
// content difficulty settle from live study traffic without giving learners
|
|
52
|
+
// write access to anything else on the card.
|
|
53
|
+
//
|
|
54
|
+
// ES5 only (CouchDB SpiderMonkey): no let/const/arrow/for-of/Object.entries.
|
|
55
|
+
// ---------------------------------------------------------------------------
|
|
56
|
+
var ELO_MAX_STEP = 64; // must match K_MAX in @vue-skuilder/common elo.ts
|
|
57
|
+
|
|
58
|
+
function isPlainObject(x) {
|
|
59
|
+
return x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Structural deep equality. Key order is irrelevant (a client round-trip
|
|
63
|
+
// does not preserve it), so never compare serialized JSON.
|
|
64
|
+
function deepEqual(a, b) {
|
|
65
|
+
if (a === b) return true;
|
|
66
|
+
if (typeof a !== typeof b) return false;
|
|
67
|
+
if (a === null || b === null) return false;
|
|
68
|
+
if (typeof a !== 'object') {
|
|
69
|
+
// NaN !== NaN; treat two NaNs as equal for robustness
|
|
70
|
+
return a !== a && b !== b;
|
|
71
|
+
}
|
|
72
|
+
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
73
|
+
if (Array.isArray(a)) {
|
|
74
|
+
if (a.length !== b.length) return false;
|
|
75
|
+
for (var i = 0; i < a.length; i++) {
|
|
76
|
+
if (!deepEqual(a[i], b[i])) return false;
|
|
77
|
+
}
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
var ka = Object.keys(a);
|
|
81
|
+
var kb = Object.keys(b);
|
|
82
|
+
if (ka.length !== kb.length) return false;
|
|
83
|
+
for (var j = 0; j < ka.length; j++) {
|
|
84
|
+
var k = ka[j];
|
|
85
|
+
if (!Object.prototype.hasOwnProperty.call(b, k)) return false;
|
|
86
|
+
if (!deepEqual(a[k], b[k])) return false;
|
|
87
|
+
}
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function isEloRank(r) {
|
|
92
|
+
return isPlainObject(r) && typeof r.score === 'number' && typeof r.count === 'number';
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function isCourseElo(e) {
|
|
96
|
+
return isPlainObject(e) && isEloRank(e.global) && isPlainObject(e.tags);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Compare an EloRank 'n' against its predecessor 'o'. Returns null if OK,
|
|
100
|
+
// else a reason string. 'label' names the rank for the message.
|
|
101
|
+
// - unchanged (score & count equal, other fields equal) -> OK
|
|
102
|
+
// - one step: count === old.count + 1, |score delta| <= ELO_MAX_STEP,
|
|
103
|
+
// every field other than score/count deep-equal -> OK
|
|
104
|
+
function checkRankStep(label, o, n) {
|
|
105
|
+
if (!isEloRank(n)) return label + ' must have numeric score and count';
|
|
106
|
+
if (!isEloRank(o)) return label + ' has no valid prior rank to step from';
|
|
107
|
+
// Non-bounded fields must be identical
|
|
108
|
+
var keys = Object.keys(n).concat(Object.keys(o));
|
|
109
|
+
for (var i = 0; i < keys.length; i++) {
|
|
110
|
+
var k = keys[i];
|
|
111
|
+
if (k === 'score' || k === 'count') continue;
|
|
112
|
+
if (!deepEqual(o[k], n[k])) return label + ': only score and count may change (field "' + k + '")';
|
|
113
|
+
}
|
|
114
|
+
if (n.count === o.count && n.score === o.score) return null; // untouched
|
|
115
|
+
if (n.count !== o.count + 1) {
|
|
116
|
+
return label + ': count must increment by exactly 1 (was ' + o.count + ', got ' + n.count + ')';
|
|
117
|
+
}
|
|
118
|
+
if (Math.abs(n.score - o.score) > ELO_MAX_STEP) {
|
|
119
|
+
return label + ': score may move at most ' + ELO_MAX_STEP + ' per update (was ' + o.score + ', got ' + n.score + ')';
|
|
120
|
+
}
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Compare a tag entry that does not exist on the old doc. The framework
|
|
125
|
+
// initialises a new card-side tag rank at the card's (old) global score
|
|
126
|
+
// with count 0, then applies one step.
|
|
127
|
+
function checkNewRank(label, baseScore, n) {
|
|
128
|
+
if (!isEloRank(n)) return label + ' must have numeric score and count';
|
|
129
|
+
var keys = Object.keys(n);
|
|
130
|
+
for (var i = 0; i < keys.length; i++) {
|
|
131
|
+
if (keys[i] !== 'score' && keys[i] !== 'count') {
|
|
132
|
+
return label + ': a new tag rank may only carry score and count (field "' + keys[i] + '")';
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (n.count !== 1) return label + ': a new tag rank must have count 1 (got ' + n.count + ')';
|
|
136
|
+
if (Math.abs(n.score - baseScore) > ELO_MAX_STEP) {
|
|
137
|
+
return label + ': a new tag rank must start within ' + ELO_MAX_STEP + ' of the card global score ' + baseScore + ' (got ' + n.score + ')';
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function isBoundedEloStep(oldElo, newElo) {
|
|
143
|
+
if (!isCourseElo(newElo)) return 'elo must have the CourseElo shape {global:{score,count}, tags:{...}}';
|
|
144
|
+
if (!isCourseElo(oldElo)) return 'existing elo is not CourseElo-shaped; cannot apply a bounded step';
|
|
145
|
+
|
|
146
|
+
// Top-level elo keys other than global/tags must be unchanged (e.g. misc)
|
|
147
|
+
var topKeys = Object.keys(newElo).concat(Object.keys(oldElo));
|
|
148
|
+
for (var t = 0; t < topKeys.length; t++) {
|
|
149
|
+
var tk = topKeys[t];
|
|
150
|
+
if (tk === 'global' || tk === 'tags') continue;
|
|
151
|
+
if (!deepEqual(oldElo[tk], newElo[tk])) return 'elo.' + tk + ' may not change';
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
var reason = checkRankStep('elo.global', oldElo.global, newElo.global);
|
|
155
|
+
if (reason) return reason;
|
|
156
|
+
|
|
157
|
+
// No tag deletions
|
|
158
|
+
var oldTags = Object.keys(oldElo.tags);
|
|
159
|
+
for (var d = 0; d < oldTags.length; d++) {
|
|
160
|
+
if (!Object.prototype.hasOwnProperty.call(newElo.tags, oldTags[d])) {
|
|
161
|
+
return 'elo.tags["' + oldTags[d] + '"] may not be removed';
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
var newTags = Object.keys(newElo.tags);
|
|
166
|
+
for (var n = 0; n < newTags.length; n++) {
|
|
167
|
+
var tag = newTags[n];
|
|
168
|
+
var label = 'elo.tags["' + tag + '"]';
|
|
169
|
+
if (Object.prototype.hasOwnProperty.call(oldElo.tags, tag)) {
|
|
170
|
+
reason = checkRankStep(label, oldElo.tags[tag], newElo.tags[tag]);
|
|
171
|
+
} else {
|
|
172
|
+
reason = checkNewRank(label, oldElo.global.score, newElo.tags[tag]);
|
|
173
|
+
}
|
|
174
|
+
if (reason) return reason;
|
|
175
|
+
}
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (newDoc.docType === 'CARD' && oldDoc.docType === 'CARD') {
|
|
180
|
+
if (!userCtx.name) {
|
|
181
|
+
throw({forbidden: "You must be logged in to update card elo"});
|
|
182
|
+
}
|
|
183
|
+
if (newDoc._id !== oldDoc._id) {
|
|
184
|
+
throw({forbidden: "Card elo update: _id may not change"});
|
|
185
|
+
}
|
|
186
|
+
// Every field except elo and revision metadata must be unchanged.
|
|
187
|
+
// _attachments (stubs) IS compared. _rev/_revisions/_conflicts etc. are
|
|
188
|
+
// couch bookkeeping the client may or may not echo back, so skip them.
|
|
189
|
+
var allKeys = Object.keys(newDoc).concat(Object.keys(oldDoc));
|
|
190
|
+
for (var f = 0; f < allKeys.length; f++) {
|
|
191
|
+
var field = allKeys[f];
|
|
192
|
+
if (field === 'elo') continue;
|
|
193
|
+
if (field.charAt(0) === '_' && field !== '_id' && field !== '_attachments') continue;
|
|
194
|
+
if (!deepEqual(oldDoc[field], newDoc[field])) {
|
|
195
|
+
throw({forbidden: 'Card elo update: only the elo field may change (field "' + field + '" differs)'});
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
var eloReason = isBoundedEloStep(oldDoc.elo, newDoc.elo);
|
|
199
|
+
if (eloReason) {
|
|
200
|
+
throw({forbidden: 'Card elo update rejected: ' + eloReason});
|
|
201
|
+
}
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
46
204
|
|
|
47
205
|
// For updates to existing documents, deny if not the original author
|
|
48
206
|
if (oldDoc && oldDoc.author && oldDoc.author !== userCtx.name) {
|
|
@@ -54,4 +212,4 @@ function(newDoc, oldDoc, userCtx, secObj) {
|
|
|
54
212
|
if (newDoc._id.indexOf('_design/') === 0) {
|
|
55
213
|
throw({forbidden: "Only admins can modify design documents"});
|
|
56
214
|
}
|
|
57
|
-
}
|
|
215
|
+
}
|
package/eslint.config.js
CHANGED
|
@@ -3,7 +3,7 @@ import backendConfig from '../../eslint.config.backend.mjs';
|
|
|
3
3
|
export default [
|
|
4
4
|
...backendConfig,
|
|
5
5
|
{
|
|
6
|
-
ignores: ['node_modules/**', 'dist/**', 'coverage/**', 'eslint.config.js', 'assets/**', 'babel.config.js', 'vitest.config.ts', 'test/**'],
|
|
6
|
+
ignores: ['node_modules/**', 'dist/**', 'coverage/**', 'eslint.config.js', 'assets/**', 'scripts/**', 'babel.config.js', 'vitest.config.ts', 'test/**'],
|
|
7
7
|
},
|
|
8
8
|
{
|
|
9
9
|
languageOptions: {
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "0.2.
|
|
6
|
+
"version": "0.2.25",
|
|
7
7
|
"description": "an API",
|
|
8
8
|
"main": "dist/index.js",
|
|
9
9
|
"type": "module",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"test": "vitest run",
|
|
27
27
|
"test:watch": "vitest",
|
|
28
28
|
"test:coverage": "vitest run --coverage",
|
|
29
|
+
"test:validator": "tsx scripts/test-course-validator.ts",
|
|
29
30
|
"lint": "npx eslint .",
|
|
30
31
|
"lint:fix": "npx eslint . --fix",
|
|
31
32
|
"lint:check": "npx eslint . --max-warnings 0",
|
|
@@ -35,8 +36,8 @@
|
|
|
35
36
|
"author": "Colin Kennedy",
|
|
36
37
|
"license": "GPL-3.0-or-later",
|
|
37
38
|
"dependencies": {
|
|
38
|
-
"@vue-skuilder/common": "^0.2.
|
|
39
|
-
"@vue-skuilder/db": "^0.2.
|
|
39
|
+
"@vue-skuilder/common": "^0.2.25",
|
|
40
|
+
"@vue-skuilder/db": "^0.2.25",
|
|
40
41
|
"axios": "^1.12.0",
|
|
41
42
|
"cookie-parser": "^1.4.7",
|
|
42
43
|
"cors": "^2.8.5",
|
|
@@ -77,5 +78,5 @@
|
|
|
77
78
|
"typescript-eslint": "^8.48.1",
|
|
78
79
|
"vitest": "^4.1.0"
|
|
79
80
|
},
|
|
80
|
-
"stableVersion": "0.2.
|
|
81
|
+
"stableVersion": "0.2.25"
|
|
81
82
|
}
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Test matrix for assets/courseValidateDocUpdate.js against a REAL CouchDB.
|
|
3
|
+
*
|
|
4
|
+
* The validate_doc_update function runs inside CouchDB's SpiderMonkey (ES5),
|
|
5
|
+
* so unit-testing it in Node proves little. This script creates a scratch
|
|
6
|
+
* course DB on the local dev couch, installs the validator, seeds a CARD doc
|
|
7
|
+
* as admin, then exercises the dynamic-card-ELO rules as a non-admin user.
|
|
8
|
+
*
|
|
9
|
+
* Prereqs: a couch with admin `admin`/`password` (local: `yarn couchdb:start`
|
|
10
|
+
* at repo root). The non-admin user `test`/`test` is created if missing.
|
|
11
|
+
* Runs in CI (ci-pkg-express.yml) against the workflow's couch.
|
|
12
|
+
*
|
|
13
|
+
* Usage (from packages/express):
|
|
14
|
+
* npx tsx scripts/test-course-validator.ts
|
|
15
|
+
*
|
|
16
|
+
* Env overrides: COUCH_URL, COUCH_ADMIN, COUCH_ADMIN_PW, COUCH_USER, COUCH_USER_PW
|
|
17
|
+
*/
|
|
18
|
+
import { readFileSync } from 'fs';
|
|
19
|
+
import { dirname, join } from 'path';
|
|
20
|
+
import { fileURLToPath } from 'url';
|
|
21
|
+
|
|
22
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
23
|
+
|
|
24
|
+
const COUCH_URL = process.env.COUCH_URL ?? 'http://localhost:5984';
|
|
25
|
+
const ADMIN = { name: process.env.COUCH_ADMIN ?? 'admin', pw: process.env.COUCH_ADMIN_PW ?? 'password' };
|
|
26
|
+
const USER = { name: process.env.COUCH_USER ?? 'test', pw: process.env.COUCH_USER_PW ?? 'test' };
|
|
27
|
+
const DB = 'coursedb-validator-test';
|
|
28
|
+
|
|
29
|
+
const validatorSource = readFileSync(join(__dirname, '..', 'assets', 'courseValidateDocUpdate.js'), 'utf-8');
|
|
30
|
+
|
|
31
|
+
type Cred = { name: string; pw: string };
|
|
32
|
+
type Doc = Record<string, unknown> & { _id: string; _rev?: string };
|
|
33
|
+
|
|
34
|
+
async function req(cred: Cred, method: string, path: string, body?: unknown) {
|
|
35
|
+
const res = await fetch(`${COUCH_URL}/${path}`, {
|
|
36
|
+
method,
|
|
37
|
+
headers: {
|
|
38
|
+
Authorization: 'Basic ' + Buffer.from(`${cred.name}:${cred.pw}`).toString('base64'),
|
|
39
|
+
'Content-Type': 'application/json',
|
|
40
|
+
},
|
|
41
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
42
|
+
});
|
|
43
|
+
let json: any = null;
|
|
44
|
+
try {
|
|
45
|
+
json = await res.json();
|
|
46
|
+
} catch {
|
|
47
|
+
/* no body */
|
|
48
|
+
}
|
|
49
|
+
return { status: res.status, json };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function getDoc(cred: Cred, id: string): Promise<Doc> {
|
|
53
|
+
const r = await req(cred, 'GET', `${DB}/${encodeURIComponent(id)}`);
|
|
54
|
+
if (r.status !== 200) throw new Error(`GET ${id} -> ${r.status} ${JSON.stringify(r.json)}`);
|
|
55
|
+
return r.json as Doc;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function put(cred: Cred, doc: Doc) {
|
|
59
|
+
return req(cred, 'PUT', `${DB}/${encodeURIComponent(doc._id)}`, doc);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ---- fixtures ---------------------------------------------------------------
|
|
63
|
+
|
|
64
|
+
const CARD_ID = 'c-test-card-1';
|
|
65
|
+
const TAG_A = 'gpc:exercise:a-AE';
|
|
66
|
+
const TAG_B = 'ui:missing-letters';
|
|
67
|
+
|
|
68
|
+
function freshCard(): Doc {
|
|
69
|
+
return {
|
|
70
|
+
_id: CARD_ID,
|
|
71
|
+
course: 'ExampleCourse',
|
|
72
|
+
docType: 'CARD',
|
|
73
|
+
id_displayable_data: ['dd-test-card-1'],
|
|
74
|
+
id_view: 'ExampleCourse.question.MissingLetters.MissingLettersView',
|
|
75
|
+
elo: {
|
|
76
|
+
global: { score: 1405, count: 3 },
|
|
77
|
+
tags: {
|
|
78
|
+
[TAG_A]: { score: 1404, count: 3 },
|
|
79
|
+
[TAG_B]: { score: 1408, count: 0 },
|
|
80
|
+
},
|
|
81
|
+
misc: {},
|
|
82
|
+
},
|
|
83
|
+
seedElo: {
|
|
84
|
+
global: { score: 1405, count: 0 },
|
|
85
|
+
tags: {
|
|
86
|
+
[TAG_A]: { score: 1404, count: 0 },
|
|
87
|
+
[TAG_B]: { score: 1408, count: 0 },
|
|
88
|
+
},
|
|
89
|
+
misc: {},
|
|
90
|
+
},
|
|
91
|
+
author: 'content-pipeline-v1',
|
|
92
|
+
sourceRef: 'gen:content-pipeline-v1',
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const clone = <T>(x: T): T => JSON.parse(JSON.stringify(x));
|
|
97
|
+
|
|
98
|
+
// ---- harness ----------------------------------------------------------------
|
|
99
|
+
|
|
100
|
+
type Expect = { status: number; reasonIncludes?: string };
|
|
101
|
+
const results: { name: string; pass: boolean; detail: string }[] = [];
|
|
102
|
+
|
|
103
|
+
async function check(name: string, run: () => Promise<{ status: number; json: any }>, expect: Expect) {
|
|
104
|
+
const r = await run();
|
|
105
|
+
const reason: string = r.json?.reason ?? '';
|
|
106
|
+
let pass = r.status === expect.status;
|
|
107
|
+
if (pass && expect.reasonIncludes) pass = reason.includes(expect.reasonIncludes);
|
|
108
|
+
results.push({
|
|
109
|
+
name,
|
|
110
|
+
pass,
|
|
111
|
+
detail: `${r.status}${reason ? ' ' + reason : ''}${pass ? '' : ` (expected ${expect.status}${expect.reasonIncludes ? ' ~ "' + expect.reasonIncludes + '"' : ''})`}`,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Reset the card as admin so each case starts from a known state. */
|
|
116
|
+
async function resetCard(): Promise<Doc> {
|
|
117
|
+
const existing = await req(ADMIN, 'GET', `${DB}/${encodeURIComponent(CARD_ID)}`);
|
|
118
|
+
const doc = freshCard();
|
|
119
|
+
if (existing.status === 200) doc._rev = (existing.json as Doc)._rev;
|
|
120
|
+
const r = await put(ADMIN, doc);
|
|
121
|
+
if (r.status !== 201) throw new Error(`admin reset failed: ${r.status} ${JSON.stringify(r.json)}`);
|
|
122
|
+
return getDoc(USER, CARD_ID);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** A realistic one-step elo update touching global + TAG_A (TAG_B untouched). */
|
|
126
|
+
function stepped(doc: Doc, dScore = -12): Doc {
|
|
127
|
+
const d = clone(doc);
|
|
128
|
+
const elo: any = d.elo;
|
|
129
|
+
elo.global = { score: elo.global.score + dScore, count: elo.global.count + 1 };
|
|
130
|
+
elo.tags[TAG_A] = { score: elo.tags[TAG_A].score + dScore, count: elo.tags[TAG_A].count + 1 };
|
|
131
|
+
return d;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function main() {
|
|
135
|
+
// Ensure the non-admin user exists (CI couch starts with only the admin).
|
|
136
|
+
// A fresh CouchDB 2.x has no `_users` database until cluster setup runs,
|
|
137
|
+
// so create it first (201 new, 412 exists). Then the user (409 = exists).
|
|
138
|
+
const mkUsersDb = await req(ADMIN, 'PUT', '_users');
|
|
139
|
+
if (mkUsersDb.status !== 201 && mkUsersDb.status !== 412) {
|
|
140
|
+
throw new Error(`could not ensure _users db: ${mkUsersDb.status} ${JSON.stringify(mkUsersDb.json)}`);
|
|
141
|
+
}
|
|
142
|
+
const userDocId = `_users/org.couchdb.user:${USER.name}`;
|
|
143
|
+
const mk = await req(ADMIN, 'PUT', userDocId, {
|
|
144
|
+
name: USER.name,
|
|
145
|
+
password: USER.pw,
|
|
146
|
+
roles: [],
|
|
147
|
+
type: 'user',
|
|
148
|
+
});
|
|
149
|
+
if (mk.status !== 201 && mk.status !== 409) {
|
|
150
|
+
throw new Error(`could not create non-admin user ${USER.name}: ${mk.status} ${JSON.stringify(mk.json)}`);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// sanity: non-admin user must authenticate and not be admin
|
|
154
|
+
const sess = await req(USER, 'GET', '_session');
|
|
155
|
+
if (sess.status !== 200 || sess.json?.userCtx?.name !== USER.name) {
|
|
156
|
+
throw new Error(`non-admin user ${USER.name} cannot authenticate: ${sess.status} ${JSON.stringify(sess.json)}`);
|
|
157
|
+
}
|
|
158
|
+
if ((sess.json.userCtx.roles as string[]).includes('_admin')) throw new Error(`${USER.name} is an admin; test is meaningless`);
|
|
159
|
+
|
|
160
|
+
// scratch DB
|
|
161
|
+
await req(ADMIN, 'DELETE', DB);
|
|
162
|
+
const create = await req(ADMIN, 'PUT', DB);
|
|
163
|
+
if (create.status !== 201) throw new Error(`create ${DB}: ${create.status} ${JSON.stringify(create.json)}`);
|
|
164
|
+
// members: [] => any authenticated user can read/write (matches LP prod _security)
|
|
165
|
+
await req(ADMIN, 'PUT', `${DB}/_security`, {
|
|
166
|
+
admins: { names: [], roles: ['_admin'] },
|
|
167
|
+
members: { names: [], roles: [] },
|
|
168
|
+
});
|
|
169
|
+
const dd = await put(ADMIN, { _id: '_design/_auth', validate_doc_update: validatorSource });
|
|
170
|
+
if (dd.status !== 201) throw new Error(`install validator: ${dd.status} ${JSON.stringify(dd.json)}`);
|
|
171
|
+
|
|
172
|
+
try {
|
|
173
|
+
// 1. elo-only write within bounds -> 201
|
|
174
|
+
let doc = await resetCard();
|
|
175
|
+
await check('1. elo-only bounded step (global + one tag, other tag untouched)', () => put(USER, stepped(doc)), { status: 201 });
|
|
176
|
+
|
|
177
|
+
// 1b. max-magnitude step (exactly 64) -> 201
|
|
178
|
+
doc = await resetCard();
|
|
179
|
+
await check('1b. score delta exactly 64', () => put(USER, stepped(doc, 64)), { status: 201 });
|
|
180
|
+
|
|
181
|
+
// 1c. key order shuffled on the round trip -> 201
|
|
182
|
+
doc = await resetCard();
|
|
183
|
+
{
|
|
184
|
+
const s = stepped(doc);
|
|
185
|
+
const shuffled: Doc = { _id: s._id } as Doc;
|
|
186
|
+
for (const k of Object.keys(s).reverse()) shuffled[k] = s[k];
|
|
187
|
+
await check('1c. elo-only step with reversed key order', () => put(USER, shuffled), { status: 201 });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// 2. elo + another field changed -> forbidden (elo-only message, not the author rule)
|
|
191
|
+
doc = await resetCard();
|
|
192
|
+
{
|
|
193
|
+
const s = stepped(doc);
|
|
194
|
+
s.sourceRef = 'tampered';
|
|
195
|
+
await check('2a. elo step + sourceRef changed', () => put(USER, s), {
|
|
196
|
+
status: 403,
|
|
197
|
+
reasonIncludes: 'only the elo field may change (field "sourceRef"',
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
doc = await resetCard();
|
|
201
|
+
{
|
|
202
|
+
const s = stepped(doc);
|
|
203
|
+
(s.seedElo as any).global.score = 1;
|
|
204
|
+
await check('2b. elo step + seedElo changed', () => put(USER, s), {
|
|
205
|
+
status: 403,
|
|
206
|
+
reasonIncludes: 'only the elo field may change (field "seedElo"',
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
doc = await resetCard();
|
|
210
|
+
{
|
|
211
|
+
const s = stepped(doc);
|
|
212
|
+
s.author = USER.name; // try to claim authorship
|
|
213
|
+
await check('2c. elo step + author changed to self', () => put(USER, s), {
|
|
214
|
+
status: 403,
|
|
215
|
+
reasonIncludes: 'only the elo field may change (field "author"',
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
doc = await resetCard();
|
|
219
|
+
{
|
|
220
|
+
const s = stepped(doc);
|
|
221
|
+
s.extraField = 1;
|
|
222
|
+
await check('2d. elo step + new field added', () => put(USER, s), {
|
|
223
|
+
status: 403,
|
|
224
|
+
reasonIncludes: 'only the elo field may change (field "extraField"',
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
doc = await resetCard();
|
|
228
|
+
{
|
|
229
|
+
const s = clone(doc);
|
|
230
|
+
s.sourceRef = 'tampered'; // no elo change at all
|
|
231
|
+
await check('2e. non-elo field changed, elo untouched', () => put(USER, s), {
|
|
232
|
+
status: 403,
|
|
233
|
+
reasonIncludes: 'only the elo field may change',
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// 3. score delta 65 -> forbidden
|
|
238
|
+
doc = await resetCard();
|
|
239
|
+
await check('3. global score delta 65', () => put(USER, stepped(doc, 65)), {
|
|
240
|
+
status: 403,
|
|
241
|
+
reasonIncludes: 'elo.global: score may move at most 64',
|
|
242
|
+
});
|
|
243
|
+
doc = await resetCard();
|
|
244
|
+
{
|
|
245
|
+
const s = stepped(doc);
|
|
246
|
+
(s.elo as any).tags[TAG_A].score += 100;
|
|
247
|
+
await check('3b. tag score delta > 64', () => put(USER, s), {
|
|
248
|
+
status: 403,
|
|
249
|
+
reasonIncludes: `elo.tags["${TAG_A}"]: score may move at most 64`,
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// 4. count +2 -> forbidden
|
|
254
|
+
doc = await resetCard();
|
|
255
|
+
{
|
|
256
|
+
const s = stepped(doc);
|
|
257
|
+
(s.elo as any).global.count += 1;
|
|
258
|
+
await check('4. global count +2', () => put(USER, s), {
|
|
259
|
+
status: 403,
|
|
260
|
+
reasonIncludes: 'elo.global: count must increment by exactly 1',
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// 5. count unchanged, score moved (stale retry after lost MVCC race) -> forbidden
|
|
265
|
+
doc = await resetCard();
|
|
266
|
+
{
|
|
267
|
+
const s = stepped(doc);
|
|
268
|
+
(s.elo as any).global.count -= 1;
|
|
269
|
+
await check('5. global score moved, count unchanged (stale retry)', () => put(USER, s), {
|
|
270
|
+
status: 403,
|
|
271
|
+
reasonIncludes: 'elo.global: count must increment by exactly 1',
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// 6. new tag entry with count 1 -> 201; count 3 -> forbidden; far from global -> forbidden
|
|
276
|
+
doc = await resetCard();
|
|
277
|
+
{
|
|
278
|
+
const s = stepped(doc);
|
|
279
|
+
(s.elo as any).tags['gpc:exercise:t-T'] = { score: (doc.elo as any).global.score + 20, count: 1 };
|
|
280
|
+
await check('6a. new tag entry count 1, near global', () => put(USER, s), { status: 201 });
|
|
281
|
+
}
|
|
282
|
+
doc = await resetCard();
|
|
283
|
+
{
|
|
284
|
+
const s = stepped(doc);
|
|
285
|
+
(s.elo as any).tags['gpc:exercise:t-T'] = { score: (doc.elo as any).global.score + 20, count: 3 };
|
|
286
|
+
await check('6b. new tag entry count 3', () => put(USER, s), {
|
|
287
|
+
status: 403,
|
|
288
|
+
reasonIncludes: 'a new tag rank must have count 1',
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
doc = await resetCard();
|
|
292
|
+
{
|
|
293
|
+
const s = stepped(doc);
|
|
294
|
+
(s.elo as any).tags['gpc:exercise:t-T'] = { score: 1000, count: 1 };
|
|
295
|
+
await check('6c. new tag entry count 1 but 405 from global', () => put(USER, s), {
|
|
296
|
+
status: 403,
|
|
297
|
+
reasonIncludes: 'must start within 64 of the card global score',
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// 7. removing a tag entry -> forbidden
|
|
302
|
+
doc = await resetCard();
|
|
303
|
+
{
|
|
304
|
+
const s = stepped(doc);
|
|
305
|
+
delete (s.elo as any).tags[TAG_B];
|
|
306
|
+
await check('7. tag entry removed', () => put(USER, s), {
|
|
307
|
+
status: 403,
|
|
308
|
+
reasonIncludes: `elo.tags["${TAG_B}"] may not be removed`,
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// 7b. misc changed -> forbidden
|
|
313
|
+
doc = await resetCard();
|
|
314
|
+
{
|
|
315
|
+
const s = stepped(doc);
|
|
316
|
+
(s.elo as any).misc = { x: { score: 1, count: 1 } };
|
|
317
|
+
await check('7b. elo.misc changed', () => put(USER, s), { status: 403, reasonIncludes: 'elo.misc may not change' });
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// 7c. extra field on an existing tag rank -> forbidden
|
|
321
|
+
doc = await resetCard();
|
|
322
|
+
{
|
|
323
|
+
const s = stepped(doc);
|
|
324
|
+
(s.elo as any).tags[TAG_A].recent = [];
|
|
325
|
+
await check('7c. extra field added to a tag rank', () => put(USER, s), {
|
|
326
|
+
status: 403,
|
|
327
|
+
reasonIncludes: 'only score and count may change (field "recent")',
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// 7d. malformed elo (number) -> forbidden
|
|
332
|
+
doc = await resetCard();
|
|
333
|
+
{
|
|
334
|
+
const s = clone(doc);
|
|
335
|
+
s.elo = 1400;
|
|
336
|
+
await check('7d. elo replaced by a number', () => put(USER, s), {
|
|
337
|
+
status: 403,
|
|
338
|
+
reasonIncludes: 'must have the CourseElo shape',
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// 8. non-CARD doc elo-only write -> forbidden (author rule)
|
|
343
|
+
{
|
|
344
|
+
const tag: Doc = {
|
|
345
|
+
_id: 'TAG-gpc:exercise:a-AE',
|
|
346
|
+
course: 'x',
|
|
347
|
+
docType: 'TAG',
|
|
348
|
+
name: TAG_A,
|
|
349
|
+
taggedCards: [CARD_ID],
|
|
350
|
+
author: 'content-pipeline-v1',
|
|
351
|
+
elo: { global: { score: 1000, count: 0 }, tags: {}, misc: {} },
|
|
352
|
+
};
|
|
353
|
+
const r = await put(ADMIN, tag);
|
|
354
|
+
if (r.status !== 201) throw new Error('seed TAG failed');
|
|
355
|
+
const t = await getDoc(USER, tag._id);
|
|
356
|
+
(t.elo as any).global = { score: 1010, count: 1 };
|
|
357
|
+
await check('8. non-CARD (TAG) doc, elo-only bounded step', () => put(USER, t), {
|
|
358
|
+
status: 403,
|
|
359
|
+
reasonIncludes: 'You can only modify your own documents',
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// 8b. non-admin creating a card with someone else's author -> forbidden (unchanged rule)
|
|
364
|
+
await check(
|
|
365
|
+
'8b. non-admin creates doc with foreign author',
|
|
366
|
+
() => put(USER, { ...freshCard(), _id: 'c-new-card' }),
|
|
367
|
+
{ status: 403, reasonIncludes: 'Document author must match your username' }
|
|
368
|
+
);
|
|
369
|
+
|
|
370
|
+
// 9. admin writes anything -> 201
|
|
371
|
+
doc = await resetCard();
|
|
372
|
+
{
|
|
373
|
+
const s = clone(doc);
|
|
374
|
+
s.sourceRef = 'admin-edit';
|
|
375
|
+
(s.elo as any).global = { score: 5, count: 99 };
|
|
376
|
+
delete (s.elo as any).tags[TAG_B];
|
|
377
|
+
await check('9. admin: arbitrary edit incl. wild elo', () => put(ADMIN, s), { status: 201 });
|
|
378
|
+
}
|
|
379
|
+
} finally {
|
|
380
|
+
const del = await req(ADMIN, 'DELETE', DB);
|
|
381
|
+
console.log(`\ncleanup: DELETE ${DB} -> ${del.status}`);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// ---- report
|
|
385
|
+
const width = Math.max(...results.map((r) => r.name.length));
|
|
386
|
+
let failed = 0;
|
|
387
|
+
for (const r of results) {
|
|
388
|
+
if (!r.pass) failed++;
|
|
389
|
+
console.log(`${r.pass ? 'PASS' : 'FAIL'} ${r.name.padEnd(width)} ${r.detail}`);
|
|
390
|
+
}
|
|
391
|
+
console.log(`\n${results.length - failed}/${results.length} passed`);
|
|
392
|
+
process.exit(failed ? 1 : 0);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
main().catch((e) => {
|
|
396
|
+
console.error(e);
|
|
397
|
+
process.exit(2);
|
|
398
|
+
});
|