@vue-skuilder/express 0.2.24 → 0.2.26
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.
- package/.env.development +4 -0
- package/assets/courseValidateDocUpdate.js +159 -1
- package/dist/assets/courseValidateDocUpdate.js +159 -1
- package/dist/couchdb/identityAssertion.d.ts +49 -0
- package/dist/couchdb/identityAssertion.d.ts.map +1 -0
- package/dist/couchdb/identityAssertion.js +90 -0
- package/dist/couchdb/identityAssertion.js.map +1 -0
- package/dist/couchdb/sessionCookie.d.ts +28 -0
- package/dist/couchdb/sessionCookie.d.ts.map +1 -0
- package/dist/couchdb/sessionCookie.js +101 -0
- package/dist/couchdb/sessionCookie.js.map +1 -0
- package/dist/couchdb/userDesignDocs.d.ts +3 -1
- package/dist/couchdb/userDesignDocs.d.ts.map +1 -1
- package/dist/couchdb/userDesignDocs.js +7 -5
- package/dist/couchdb/userDesignDocs.js.map +1 -1
- package/dist/couchdb/userLookup.d.ts +6 -0
- package/dist/couchdb/userLookup.d.ts.map +1 -1
- package/dist/couchdb/userLookup.js +29 -2
- package/dist/couchdb/userLookup.js.map +1 -1
- package/dist/routes/auth.d.ts.map +1 -1
- package/dist/routes/auth.js +124 -14
- package/dist/routes/auth.js.map +1 -1
- package/dist/utils/email.d.ts +11 -0
- package/dist/utils/email.d.ts.map +1 -0
- package/dist/utils/email.js +13 -0
- package/dist/utils/email.js.map +1 -0
- package/eslint.config.js +1 -1
- package/package.json +5 -4
- package/scripts/test-course-validator.ts +398 -0
- package/src/couchdb/identityAssertion.ts +163 -0
- package/src/couchdb/sessionCookie.ts +135 -0
- package/src/couchdb/userDesignDocs.ts +7 -5
- package/src/couchdb/userLookup.ts +29 -2
- package/src/routes/auth.ts +130 -14
- package/src/utils/email.ts +12 -0
package/.env.development
CHANGED
|
@@ -13,3 +13,7 @@ VERSION=localdev
|
|
|
13
13
|
# Shared secret for payment webhook authorization (Stripe → /express/permissions)
|
|
14
14
|
# Must match PERMISSIONS_SECRET in business backend .env
|
|
15
15
|
PERMISSIONS_SECRET=dev-permissions-secret-12345
|
|
16
|
+
|
|
17
|
+
# Enables POST /auth/assert-identity (server-to-server; mints sessions).
|
|
18
|
+
# DEV-ONLY value, committed on purpose; prod sets a real secret via EXPRESS_ENV.
|
|
19
|
+
IDENTITY_ASSERTION_SECRET=dev-only-identity-assertion-secret-not-for-prod
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Identity assertion: "a trusted caller vouches that this person controls this
|
|
3
|
+
* email" → the account that email belongs to, created if need be.
|
|
4
|
+
*
|
|
5
|
+
* The provider-agnostic core of third-party sign-in (Google, Apple, SSO, magic
|
|
6
|
+
* links). Provider token verification lives with the caller; this module owns
|
|
7
|
+
* the `_users` rules, which must stay in one place alongside /verify,
|
|
8
|
+
* /resolve-login and reset:
|
|
9
|
+
*
|
|
10
|
+
* Resolution order (mirrors /resolve-login's candidates):
|
|
11
|
+
* 1. the account that has *verified* this email;
|
|
12
|
+
* 2. the account whose username IS the email (unless its recovery address
|
|
13
|
+
* has since been changed to something else — then the name is just an
|
|
14
|
+
* opaque id and the address is no longer the owner's);
|
|
15
|
+
* 3. accounts with this email saved but unverified (first by name, so the
|
|
16
|
+
* pick is deterministic);
|
|
17
|
+
* 4. none: create a verified account named after the email.
|
|
18
|
+
*
|
|
19
|
+
* Rules:
|
|
20
|
+
* - Accounts with any role are never resolved. App users carry `roles: []`;
|
|
21
|
+
* a role means a privileged account, which must stay password-only, or it
|
|
22
|
+
* is only as secure as the third-party account sharing its address.
|
|
23
|
+
* - Linking an existing account (1–3) requires `authoritative: true`: the
|
|
24
|
+
* asserter must be authoritative for the address, not merely have checked
|
|
25
|
+
* it once. Otherwise a lapsed-then-reregistered address would open someone
|
|
26
|
+
* else's account. Creating a *new* account needs no such guarantee.
|
|
27
|
+
* - Linking an unverified account (2–3) marks it verified and rotates its
|
|
28
|
+
* password to a random one. The rotation regenerates the salt CouchDB signs
|
|
29
|
+
* session cookies with, killing any squatter's sessions; the legitimate
|
|
30
|
+
* owner can get a password back through reset.
|
|
31
|
+
* - Linking a verified account (1) mutates nothing.
|
|
32
|
+
*/
|
|
33
|
+
export interface IdentityAssertion {
|
|
34
|
+
email: string;
|
|
35
|
+
/** Free-form provider tag, for logs and the `_users` doc. */
|
|
36
|
+
provider: string;
|
|
37
|
+
/** Whether the asserter is authoritative for this address right now. */
|
|
38
|
+
authoritative: boolean;
|
|
39
|
+
}
|
|
40
|
+
export type IdentityResolution = {
|
|
41
|
+
ok: true;
|
|
42
|
+
username: string;
|
|
43
|
+
outcome: 'existing' | 'linked' | 'created';
|
|
44
|
+
} | {
|
|
45
|
+
ok: false;
|
|
46
|
+
code: 'privileged_account' | 'link_requires_authoritative' | 'username_conflict';
|
|
47
|
+
};
|
|
48
|
+
export declare function resolveAssertedIdentity(assertion: IdentityAssertion): Promise<IdentityResolution>;
|
|
49
|
+
//# sourceMappingURL=identityAssertion.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identityAssertion.d.ts","sourceRoot":"","sources":["../../src/couchdb/identityAssertion.ts"],"names":[],"mappings":"AAaA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,6DAA6D;IAC7D,QAAQ,EAAE,MAAM,CAAC;IACjB,wEAAwE;IACxE,aAAa,EAAE,OAAO,CAAC;CACxB;AAED,MAAM,MAAM,kBAAkB,GAC1B;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,UAAU,GAAG,QAAQ,GAAG,SAAS,CAAA;CAAE,GAC1E;IACE,EAAE,EAAE,KAAK,CAAC;IACV,IAAI,EAAE,oBAAoB,GAAG,6BAA6B,GAAG,mBAAmB,CAAC;CAClF,CAAC;AAkBN,wBAAsB,uBAAuB,CAC3C,SAAS,EAAE,iBAAiB,GAC3B,OAAO,CAAC,kBAAkB,CAAC,CA0E7B"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { getCouchDB } from './index.js';
|
|
2
|
+
import { findUserByUsername, findUsernamesByEmail, findVerifiedUserByEmail, updateUserDoc, } from './userLookup.js';
|
|
3
|
+
import { generateSecureToken } from '../utils/tokens.js';
|
|
4
|
+
import { normalizeEmail } from '../utils/email.js';
|
|
5
|
+
import { isNanoError } from '../utils/types.js';
|
|
6
|
+
import logger from '../logger.js';
|
|
7
|
+
function isPrivileged(doc) {
|
|
8
|
+
return Array.isArray(doc.roles) && doc.roles.length > 0;
|
|
9
|
+
}
|
|
10
|
+
function withProvider(doc, provider) {
|
|
11
|
+
const existing = Array.isArray(doc.linkedProviders) ? doc.linkedProviders : [];
|
|
12
|
+
return existing.includes(provider) ? existing : [...existing, provider];
|
|
13
|
+
}
|
|
14
|
+
export async function resolveAssertedIdentity(assertion) {
|
|
15
|
+
const email = normalizeEmail(assertion.email);
|
|
16
|
+
const { provider, authoritative } = assertion;
|
|
17
|
+
// 1. Verified owner of the address.
|
|
18
|
+
const verified = (await findVerifiedUserByEmail(email));
|
|
19
|
+
if (verified) {
|
|
20
|
+
if (isPrivileged(verified))
|
|
21
|
+
return refuse('privileged_account', verified.name, provider);
|
|
22
|
+
if (!authoritative)
|
|
23
|
+
return refuse('link_requires_authoritative', verified.name, provider);
|
|
24
|
+
return { ok: true, username: verified.name, outcome: 'existing' };
|
|
25
|
+
}
|
|
26
|
+
// 2 + 3. Unverified claims on the address.
|
|
27
|
+
const byName = (await findUserByUsername(email));
|
|
28
|
+
const nameCandidate = byName && (!byName.email || byName.email === email) ? byName : null;
|
|
29
|
+
let target = nameCandidate;
|
|
30
|
+
if (!target) {
|
|
31
|
+
const names = (await findUsernamesByEmail(email, 10)).sort();
|
|
32
|
+
if (names.length > 1) {
|
|
33
|
+
logger.warn(`[identity] ${names.length} unverified accounts claim ${email}; linking ${names[0]}`);
|
|
34
|
+
}
|
|
35
|
+
if (names.length > 0)
|
|
36
|
+
target = (await findUserByUsername(names[0]));
|
|
37
|
+
}
|
|
38
|
+
if (target) {
|
|
39
|
+
if (isPrivileged(target))
|
|
40
|
+
return refuse('privileged_account', target.name, provider);
|
|
41
|
+
if (!authoritative)
|
|
42
|
+
return refuse('link_requires_authoritative', target.name, provider);
|
|
43
|
+
// Already verified for this address: step 1 should have found it, but the
|
|
44
|
+
// by_verified_email lookup fails open while its view is missing. Never
|
|
45
|
+
// rotate a verified owner's password.
|
|
46
|
+
if (target.status === 'verified' && target.email === email) {
|
|
47
|
+
return { ok: true, username: target.name, outcome: 'existing' };
|
|
48
|
+
}
|
|
49
|
+
target.email = email;
|
|
50
|
+
target.status = 'verified';
|
|
51
|
+
target.verificationToken = null;
|
|
52
|
+
target.verificationTokenExpiresAt = null;
|
|
53
|
+
target.password = generateSecureToken();
|
|
54
|
+
target.linkedProviders = withProvider(target, provider);
|
|
55
|
+
await updateUserDoc(target);
|
|
56
|
+
logger.info(`[identity] linked ${target.name} via ${provider} (verified, password rotated)`);
|
|
57
|
+
return { ok: true, username: target.name, outcome: 'linked' };
|
|
58
|
+
}
|
|
59
|
+
// 4. New account. The name is taken only if an account named after this
|
|
60
|
+
// address moved its recovery email elsewhere (skipped in step 2).
|
|
61
|
+
if (byName)
|
|
62
|
+
return refuse('username_conflict', byName.name, provider);
|
|
63
|
+
const newDoc = {
|
|
64
|
+
_id: `org.couchdb.user:${email}`,
|
|
65
|
+
name: email,
|
|
66
|
+
type: 'user',
|
|
67
|
+
roles: [],
|
|
68
|
+
password: generateSecureToken(),
|
|
69
|
+
email,
|
|
70
|
+
status: 'verified',
|
|
71
|
+
linkedProviders: [provider],
|
|
72
|
+
};
|
|
73
|
+
try {
|
|
74
|
+
await getCouchDB().use('_users').insert(newDoc);
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
if (isNanoError(error) && error.statusCode === 409) {
|
|
78
|
+
// Raced a concurrent signup for the same address.
|
|
79
|
+
return refuse('username_conflict', email, provider);
|
|
80
|
+
}
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
logger.info(`[identity] created ${email} via ${provider}`);
|
|
84
|
+
return { ok: true, username: email, outcome: 'created' };
|
|
85
|
+
}
|
|
86
|
+
function refuse(code, username, provider) {
|
|
87
|
+
logger.warn(`[identity] refused ${provider} assertion for ${username}: ${code}`);
|
|
88
|
+
return { ok: false, code };
|
|
89
|
+
}
|
|
90
|
+
//# sourceMappingURL=identityAssertion.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identityAssertion.js","sourceRoot":"","sources":["../../src/couchdb/identityAssertion.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EACpB,uBAAuB,EACvB,aAAa,GACd,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,MAAM,MAAM,cAAc,CAAC;AAyDlC,SAAS,YAAY,CAAC,GAAY;IAChC,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;AAC1D,CAAC;AAED,SAAS,YAAY,CAAC,GAAY,EAAE,QAAgB;IAClD,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,CAAC;IAC/E,OAAO,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,GAAG,QAAQ,EAAE,QAAQ,CAAC,CAAC;AAC1E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{
|
|
2
|
+
name: 'AuthSession';
|
|
3
|
+
value: string;
|
|
4
|
+
/** Seconds, when CouchDB issues persistent cookies; null = session cookie. */
|
|
5
|
+
maxAge: number | null;
|
|
6
|
+
}
|
|
7
|
+
export interface CookieParams {
|
|
8
|
+
username: string;
|
|
9
|
+
secret: string;
|
|
10
|
+
salt: string;
|
|
11
|
+
/** Node crypto hash name, e.g. 'sha256'. */
|
|
12
|
+
hash: string;
|
|
13
|
+
/** Seconds since the epoch. */
|
|
14
|
+
timestamp: number;
|
|
15
|
+
}
|
|
16
|
+
/** Pure cookie-value computation (exported for tests). */
|
|
17
|
+
export declare function computeAuthSessionValue(p: CookieParams): string;
|
|
18
|
+
export interface CookieConfig {
|
|
19
|
+
secret: string;
|
|
20
|
+
/** Node crypto hash name used to sign new cookies. */
|
|
21
|
+
hash: string;
|
|
22
|
+
timeout: number;
|
|
23
|
+
persistent: boolean;
|
|
24
|
+
}
|
|
25
|
+
/** The server's cookie-signing config, resolved the way CouchDB resolves it. */
|
|
26
|
+
export declare function readCookieConfig(): Promise<CookieConfig>;
|
|
27
|
+
export declare function mintAuthSessionCookie(username: string): Promise<MintedSessionCookie>;
|
|
28
|
+
//# sourceMappingURL=sessionCookie.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sessionCookie.d.ts","sourceRoot":"","sources":["../../src/couchdb/sessionCookie.ts"],"names":[],"mappings":"AAiCA,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,aAAa,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,8EAA8E;IAC9E,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB;AA2BD,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,4CAA4C;IAC5C,IAAI,EAAE,MAAM,CAAC;IACb,+BAA+B;IAC/B,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,0DAA0D;AAC1D,wBAAgB,uBAAuB,CAAC,CAAC,EAAE,YAAY,GAAG,MAAM,CAQ/D;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,sDAAsD;IACtD,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,OAAO,CAAC;CACrB;AAED,gFAAgF;AAChF,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,YAAY,CAAC,CAiB9D;AAED,wBAAsB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAoB1F"}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import { getCouchDB } from './index.js';
|
|
3
|
+
import { findUserByUsername } from './userLookup.js';
|
|
4
|
+
import { isNanoError } from '../utils/types.js';
|
|
5
|
+
/**
|
|
6
|
+
* Server-side minting of CouchDB `AuthSession` cookies.
|
|
7
|
+
*
|
|
8
|
+
* Lets express establish a session for a user whose identity was proven some
|
|
9
|
+
* other way (see identityAssertion.ts) — there is no password to hand to
|
|
10
|
+
* `_session`. The cookie is byte-for-byte what CouchDB itself issues:
|
|
11
|
+
*
|
|
12
|
+
* base64url( "<name>:<TIMESTAMP_HEX>:" ++ HMAC(alg, secret ++ salt, "<name>:<TIMESTAMP_HEX>") )
|
|
13
|
+
*
|
|
14
|
+
* - alg: the FIRST entry of `[chttpd_auth] hash_algorithms` (3.3+, default
|
|
15
|
+
* "sha256, sha"); CouchDB 2.x has no such key and always uses SHA1.
|
|
16
|
+
* - secret: `[chttpd_auth] secret`, falling back to the legacy
|
|
17
|
+
* `[couch_httpd_auth]` section, as CouchDB itself does.
|
|
18
|
+
* - salt: the user's `_users` doc `salt`. Changing a user's password
|
|
19
|
+
* regenerates it, which invalidates every outstanding cookie for them.
|
|
20
|
+
*
|
|
21
|
+
* Config is read from the server's `_node/_local/_config` on every mint (admin
|
|
22
|
+
* creds), so the secret never lives in env files and a rotation takes effect
|
|
23
|
+
* immediately.
|
|
24
|
+
*
|
|
25
|
+
* Tied to CouchDB's cookie format: test/identityAssertion.test.ts compares minted
|
|
26
|
+
* cookies byte for byte with CouchDB-issued ones; run it against the production
|
|
27
|
+
* CouchDB version after any upgrade.
|
|
28
|
+
*/
|
|
29
|
+
/** CouchDB's defaults for the keys we read. */
|
|
30
|
+
const DEFAULT_TIMEOUT_SECONDS = 600;
|
|
31
|
+
async function readConfig(section, key) {
|
|
32
|
+
try {
|
|
33
|
+
const value = await getCouchDB().request({
|
|
34
|
+
path: `_node/_local/_config/${section}/${key}`,
|
|
35
|
+
});
|
|
36
|
+
return typeof value === 'string' ? value : null;
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (isNanoError(error) && error.statusCode === 404)
|
|
40
|
+
return null;
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** chttpd_auth first, then the legacy couch_httpd_auth section. */
|
|
45
|
+
async function readAuthConfig(key) {
|
|
46
|
+
return (await readConfig('chttpd_auth', key)) ?? (await readConfig('couch_httpd_auth', key));
|
|
47
|
+
}
|
|
48
|
+
/** Map a CouchDB (Erlang) hash name to a Node crypto one. */
|
|
49
|
+
function nodeHashName(couchName) {
|
|
50
|
+
const name = couchName.trim().toLowerCase();
|
|
51
|
+
if (name === 'sha')
|
|
52
|
+
return 'sha1';
|
|
53
|
+
if (['sha224', 'sha256', 'sha384', 'sha512'].includes(name))
|
|
54
|
+
return name;
|
|
55
|
+
throw new Error(`Unsupported CouchDB cookie hash algorithm: ${couchName}`);
|
|
56
|
+
}
|
|
57
|
+
/** Pure cookie-value computation (exported for tests). */
|
|
58
|
+
export function computeAuthSessionValue(p) {
|
|
59
|
+
const sessionData = `${p.username}:${p.timestamp.toString(16).toUpperCase()}`;
|
|
60
|
+
const mac = crypto
|
|
61
|
+
.createHmac(p.hash, p.secret + p.salt) // string keys are UTF-8
|
|
62
|
+
.update(sessionData, 'utf8')
|
|
63
|
+
.digest();
|
|
64
|
+
// Spread to bytes: Buffer.concat trips this package's Buffer/Uint8Array typings.
|
|
65
|
+
return Buffer.from([...Buffer.from(sessionData + ':', 'utf8'), ...mac]).toString('base64url');
|
|
66
|
+
}
|
|
67
|
+
/** The server's cookie-signing config, resolved the way CouchDB resolves it. */
|
|
68
|
+
export async function readCookieConfig() {
|
|
69
|
+
const secret = await readAuthConfig('secret');
|
|
70
|
+
if (!secret) {
|
|
71
|
+
throw new Error('Cannot mint session: CouchDB auth secret is not configured');
|
|
72
|
+
}
|
|
73
|
+
const algorithms = await readConfig('chttpd_auth', 'hash_algorithms');
|
|
74
|
+
const hash = algorithms ? nodeHashName(algorithms.split(',')[0]) : 'sha1';
|
|
75
|
+
const timeoutRaw = await readAuthConfig('timeout');
|
|
76
|
+
const timeout = timeoutRaw ? parseInt(timeoutRaw, 10) : DEFAULT_TIMEOUT_SECONDS;
|
|
77
|
+
// Default true since CouchDB 3.0.
|
|
78
|
+
const persistentRaw = await readAuthConfig('allow_persistent_cookies');
|
|
79
|
+
const persistent = persistentRaw === null ? true : persistentRaw === 'true';
|
|
80
|
+
return { secret, hash, timeout, persistent };
|
|
81
|
+
}
|
|
82
|
+
export async function mintAuthSessionCookie(username) {
|
|
83
|
+
const userDoc = await findUserByUsername(username);
|
|
84
|
+
const salt = userDoc?.salt;
|
|
85
|
+
if (!userDoc || typeof salt !== 'string' || !salt) {
|
|
86
|
+
throw new Error(`Cannot mint session for ${username}: no user or no salt`);
|
|
87
|
+
}
|
|
88
|
+
const { secret, hash, timeout, persistent } = await readCookieConfig();
|
|
89
|
+
return {
|
|
90
|
+
name: 'AuthSession',
|
|
91
|
+
value: computeAuthSessionValue({
|
|
92
|
+
username,
|
|
93
|
+
secret,
|
|
94
|
+
salt,
|
|
95
|
+
hash,
|
|
96
|
+
timestamp: Math.floor(Date.now() / 1000),
|
|
97
|
+
}),
|
|
98
|
+
maxAge: persistent ? timeout : null,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
//# sourceMappingURL=sessionCookie.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sessionCookie.js","sourceRoot":"","sources":["../../src/couchdb/sessionCookie.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,+CAA+C;AAC/C,MAAM,uBAAuB,GAAG,GAAG,CAAC;AASpC,KAAK,UAAU,UAAU,CAAC,OAAe,EAAE,GAAW;IACpD,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,MAAM,UAAU,EAAE,CAAC,OAAO,CAAC;YACvC,IAAI,EAAE,wBAAwB,OAAO,IAAI,GAAG,EAAE;SAC/C,CAAC,CAAC;QACH,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;IAClD,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,IAAI,WAAW,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,UAAU,KAAK,GAAG;YAAE,OAAO,IAAI,CAAC;QAChE,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,mEAAmE;AACnE,KAAK,UAAU,cAAc,CAAC,GAAW;IACvC,OAAO,CAAC,MAAM,UAAU,CAAC,aAAa,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,UAAU,CAAC,kBAAkB,EAAE,GAAG,CAAC,CAAC,CAAC;AAC/F,CAAC;AAED,6DAA6D;AAC7D,SAAS,YAAY,CAAC,SAAiB;IACrC,MAAM,IAAI,GAAG,SAAS,C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,OAAO,CAAC,CAAC,CAAC,IAAI;KACpC,CAAC;AACJ,CAAC"}
|
|
@@ -9,7 +9,9 @@ export declare const usersDesignDoc: {
|
|
|
9
9
|
_id: string;
|
|
10
10
|
views: {
|
|
11
11
|
/**
|
|
12
|
-
* Index users by email address.
|
|
12
|
+
* Index users by email address. Keys are normalized (trim + lowercase, see
|
|
13
|
+
* utils/email.ts normalizeEmail) so lookups are case-insensitive even for
|
|
14
|
+
* addresses stored before normalization was introduced.
|
|
13
15
|
*/
|
|
14
16
|
by_email: {
|
|
15
17
|
map: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"userDesignDocs.d.ts","sourceRoot":"","sources":["../../src/couchdb/userDesignDocs.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAOH;;GAEG;AACH,eAAO,MAAM,cAAc;;;QAGvB
|
|
1
|
+
{"version":3,"file":"userDesignDocs.d.ts","sourceRoot":"","sources":["../../src/couchdb/userDesignDocs.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAOH;;GAEG;AACH,eAAO,MAAM,cAAc;;;QAGvB;;;;WAIG;;;;QAQH;;;;;WAKG;;;;;QASH;;WAEG;;;;QAQH;;WAEG;;;;;;CAUN,CAAC;AAEF;;;GAGG;AACH,wBAAsB,oBAAoB,IAAI,OAAO,CAAC,IAAI,CAAC,CA6B1D"}
|