@things-factory/survey 0.0.0-stage → 10.1.314
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/dist-client/index.d.ts +1 -0
- package/dist-client/index.js +2 -0
- package/dist-client/pages/my-surveys.d.ts +24 -0
- package/dist-client/pages/my-surveys.js +256 -0
- package/dist-client/pages/survey-editor.d.ts +62 -0
- package/dist-client/pages/survey-editor.js +668 -0
- package/dist-client/pages/survey-list.d.ts +15 -0
- package/dist-client/pages/survey-list.js +150 -0
- package/dist-client/pages/survey-trustee.d.ts +21 -0
- package/dist-client/pages/survey-trustee.js +170 -0
- package/dist-client/route.d.ts +1 -0
- package/dist-client/route.js +17 -0
- package/dist-client/utils/survey-api.d.ts +16 -0
- package/dist-client/utils/survey-api.js +46 -0
- package/dist-client/utils/survey-result.d.ts +4 -0
- package/dist-client/utils/survey-result.js +79 -0
- package/dist-client/utils/survey-secret.d.ts +40 -0
- package/dist-client/utils/survey-secret.js +154 -0
- package/dist-server/index.d.ts +2 -0
- package/dist-server/index.js +27 -0
- package/dist-server/role-tasks.d.ts +2 -0
- package/dist-server/role-tasks.js +16 -0
- package/dist-server/service/index.d.ts +16 -0
- package/dist-server/service/index.js +30 -0
- package/dist-server/service/refusal.d.ts +57 -0
- package/dist-server/service/refusal.js +66 -0
- package/dist-server/service/survey/ballot-route.d.ts +1 -0
- package/dist-server/service/survey/ballot-route.js +30 -0
- package/dist-server/service/survey/ballot-worker.d.ts +1 -0
- package/dist-server/service/survey/ballot-worker.js +19 -0
- package/dist-server/service/survey/index.d.ts +10 -0
- package/dist-server/service/survey/index.js +14 -0
- package/dist-server/service/survey/survey-answer.d.ts +23 -0
- package/dist-server/service/survey/survey-answer.js +99 -0
- package/dist-server/service/survey/survey-attributes.d.ts +16 -0
- package/dist-server/service/survey/survey-attributes.js +39 -0
- package/dist-server/service/survey/survey-ballot.d.ts +14 -0
- package/dist-server/service/survey/survey-ballot.js +61 -0
- package/dist-server/service/survey/survey-class-key.d.ts +20 -0
- package/dist-server/service/survey/survey-class-key.js +92 -0
- package/dist-server/service/survey/survey-question.d.ts +27 -0
- package/dist-server/service/survey/survey-question.js +113 -0
- package/dist-server/service/survey/survey-resolver.d.ts +37 -0
- package/dist-server/service/survey/survey-resolver.js +492 -0
- package/dist-server/service/survey/survey-respondent.d.ts +17 -0
- package/dist-server/service/survey/survey-respondent.js +81 -0
- package/dist-server/service/survey/survey-rules.d.ts +169 -0
- package/dist-server/service/survey/survey-rules.js +299 -0
- package/dist-server/service/survey/survey-secret.d.ts +133 -0
- package/dist-server/service/survey/survey-secret.js +347 -0
- package/dist-server/service/survey/survey-service.d.ts +83 -0
- package/dist-server/service/survey/survey-service.js +384 -0
- package/dist-server/service/survey/survey-trustee.d.ts +25 -0
- package/dist-server/service/survey/survey-trustee.js +119 -0
- package/dist-server/service/survey/survey-types.d.ts +91 -0
- package/dist-server/service/survey/survey-types.js +319 -0
- package/dist-server/service/survey/survey.d.ts +47 -0
- package/dist-server/service/survey/survey.js +214 -0
- package/dist-shared/ballot.d.ts +54 -0
- package/dist-shared/ballot.js +146 -0
- package/dist-shared/blind-rsa.d.ts +18 -0
- package/dist-shared/blind-rsa.js +127 -0
- package/dist-shared/elgamal.d.ts +20 -0
- package/dist-shared/elgamal.js +54 -0
- package/dist-shared/group.d.ts +22 -0
- package/dist-shared/group.js +112 -0
- package/dist-shared/proofs.d.ts +20 -0
- package/dist-shared/proofs.js +94 -0
- package/dist-shared/threshold.d.ts +39 -0
- package/dist-shared/threshold.js +98 -0
- package/dist-shared/verify.d.ts +13 -0
- package/dist-shared/verify.js +73 -0
- package/package.json +63 -4
- package/things-factory.config.js +15 -0
- package/translations/en.json +202 -0
- package/translations/es.json +202 -0
- package/translations/ja.json +202 -0
- package/translations/ko.json +202 -0
- package/translations/ms.json +202 -0
- package/translations/zh.json +202 -0
- package/README.md +0 -3
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.tallyContext = exports.ballotContext = exports.keyingContext = exports.ALL = void 0;
|
|
4
|
+
exports.startKeying = startKeying;
|
|
5
|
+
exports.postTransportKey = postTransportKey;
|
|
6
|
+
exports.postDealing = postDealing;
|
|
7
|
+
exports.confirmShares = confirmShares;
|
|
8
|
+
exports.openSecret = openSecret;
|
|
9
|
+
exports.ballotKitOf = ballotKitOf;
|
|
10
|
+
exports.issueBallot = issueBallot;
|
|
11
|
+
exports.acceptBallot = acceptBallot;
|
|
12
|
+
exports.beginSecretCount = beginSecretCount;
|
|
13
|
+
exports.postPartials = postPartials;
|
|
14
|
+
exports.bulletinOf = bulletinOf;
|
|
15
|
+
exports.receiptListed = receiptListed;
|
|
16
|
+
exports.trusteeViewOf = trusteeViewOf;
|
|
17
|
+
exports.myTrusteeSurveys = myTrusteeSurveys;
|
|
18
|
+
/*
|
|
19
|
+
* The secret level on the database (operato-survey design §3-2 · §6): key holders make the survey's key together, each
|
|
20
|
+
* person asked takes one blind-signed token, ballots come in without a sign-in, the count multiplies the ballots into
|
|
21
|
+
* one sum per cell, and t key holders open the sums - nothing else is ever opened.
|
|
22
|
+
*/
|
|
23
|
+
const crypto_1 = require("crypto");
|
|
24
|
+
const path_1 = require("path");
|
|
25
|
+
const worker_threads_1 = require("worker_threads");
|
|
26
|
+
const ballot_js_1 = require("@things-factory/survey/dist-shared/ballot.js");
|
|
27
|
+
const blind_rsa_js_1 = require("@things-factory/survey/dist-shared/blind-rsa.js");
|
|
28
|
+
const elgamal_js_1 = require("@things-factory/survey/dist-shared/elgamal.js");
|
|
29
|
+
const group_js_1 = require("@things-factory/survey/dist-shared/group.js");
|
|
30
|
+
const proofs_js_1 = require("@things-factory/survey/dist-shared/proofs.js");
|
|
31
|
+
const threshold_js_1 = require("@things-factory/survey/dist-shared/threshold.js");
|
|
32
|
+
const refusal_1 = require("../refusal");
|
|
33
|
+
const survey_1 = require("./survey");
|
|
34
|
+
const survey_ballot_1 = require("./survey-ballot");
|
|
35
|
+
const survey_class_key_1 = require("./survey-class-key");
|
|
36
|
+
const survey_respondent_1 = require("./survey-respondent");
|
|
37
|
+
const survey_rules_1 = require("./survey-rules");
|
|
38
|
+
const survey_service_1 = require("./survey-service");
|
|
39
|
+
const survey_trustee_1 = require("./survey-trustee");
|
|
40
|
+
/** The class name of an unweighted secret survey - one token key for everyone. */
|
|
41
|
+
exports.ALL = 'ALL';
|
|
42
|
+
const keyingContext = (survey) => `survey:${survey.id}|keying`;
|
|
43
|
+
exports.keyingContext = keyingContext;
|
|
44
|
+
const ballotContext = (survey, serial) => `survey:${survey.id}|ballot|${serial}`;
|
|
45
|
+
exports.ballotContext = ballotContext;
|
|
46
|
+
const tallyContext = (survey) => `survey:${survey.id}|tally`;
|
|
47
|
+
exports.tallyContext = tallyContext;
|
|
48
|
+
const sha256 = (text) => (0, crypto_1.createHash)('sha256').update(text).digest('hex');
|
|
49
|
+
const bigOf = (base64url) => BigInt('0x' + Buffer.from(base64url, 'base64url').toString('hex'));
|
|
50
|
+
async function secretOf(tx, domain, id, status) {
|
|
51
|
+
const survey = await (0, survey_service_1.surveyOf)(tx, domain, id);
|
|
52
|
+
if (survey.level !== 'SECRET')
|
|
53
|
+
throw (0, refusal_1.surveyRefusal)('survey-not-secret');
|
|
54
|
+
if (status && survey.status !== status)
|
|
55
|
+
throw (0, refusal_1.surveyRefusal)('survey-step-not-now', { step: status, status: survey.status });
|
|
56
|
+
return survey;
|
|
57
|
+
}
|
|
58
|
+
const trusteesOf = (tx, surveyId) => tx.getRepository(survey_trustee_1.SurveyTrustee).find({ where: { survey: { id: surveyId } }, order: { seq: 'ASC' } });
|
|
59
|
+
async function myTrustee(tx, survey, user) {
|
|
60
|
+
const mine = await tx.getRepository(survey_trustee_1.SurveyTrustee).findOne({ where: { survey: { id: survey.id }, user: { id: user.id } } });
|
|
61
|
+
if (!mine)
|
|
62
|
+
throw (0, refusal_1.surveyRefusal)('survey-not-trustee');
|
|
63
|
+
return mine;
|
|
64
|
+
}
|
|
65
|
+
/* ---- making the key together (design §3-2 step 2) */
|
|
66
|
+
/** A secret draft starts its key: its key holders are named; the questions are fixed from here on. */
|
|
67
|
+
async function startKeying(tx, domain, user, id, now = new Date()) {
|
|
68
|
+
const survey = await secretOf(tx, domain, id, 'DRAFT');
|
|
69
|
+
const trustees = survey.trusteeUserIds ?? [];
|
|
70
|
+
const t = survey.trusteeThreshold ?? 0;
|
|
71
|
+
if (!trustees.length || new Set(trustees).size !== trustees.length || !Number.isInteger(t) || t < 1 || t > trustees.length)
|
|
72
|
+
throw (0, refusal_1.surveyRefusal)('survey-trustees-invalid');
|
|
73
|
+
const questions = await (0, survey_service_1.questionsOf)(tx, id);
|
|
74
|
+
const asked = await (0, survey_service_1.askedUserIdsOf)(tx, domain, survey, now);
|
|
75
|
+
const problem = (0, survey_rules_1.openingProblem)({ level: survey.level, questions, audienceCount: asked.length, closesAt: survey.closesAt, resultReaders: survey.resultReaders }, now);
|
|
76
|
+
if (problem)
|
|
77
|
+
throw (0, refusal_1.surveyRefusal)(problem.code, problem.params ?? {});
|
|
78
|
+
const rows = tx.getRepository(survey_trustee_1.SurveyTrustee);
|
|
79
|
+
for (const [index, userId] of trustees.entries())
|
|
80
|
+
await rows.save({ domain, survey, user: { id: userId }, seq: index + 1, status: 'INVITED', creator: user, updater: user });
|
|
81
|
+
await tx.getRepository(survey_1.Survey).update(id, { status: 'KEYING', updater: user });
|
|
82
|
+
return await (0, survey_service_1.surveyOf)(tx, domain, id);
|
|
83
|
+
}
|
|
84
|
+
/** A key holder's transport key - shares for them are sealed to it. */
|
|
85
|
+
async function postTransportKey(tx, domain, user, id, key, proof) {
|
|
86
|
+
const survey = await secretOf(tx, domain, id, 'KEYING');
|
|
87
|
+
const mine = await myTrustee(tx, survey, user);
|
|
88
|
+
if (mine.status !== 'INVITED')
|
|
89
|
+
throw (0, refusal_1.surveyRefusal)('survey-trustee-step-done');
|
|
90
|
+
const y = (0, group_js_1.fromHex)(key);
|
|
91
|
+
if (!(0, group_js_1.isElement)(y) || !(0, proofs_js_1.verifyKnowsLog)(y, proof, `${(0, exports.keyingContext)(survey)}|transport|${mine.seq}`))
|
|
92
|
+
throw (0, refusal_1.surveyRefusal)('survey-trustee-proof-invalid');
|
|
93
|
+
await tx.getRepository(survey_trustee_1.SurveyTrustee).update(mine.id, { transportKey: key, transportProof: proof, status: 'KEYED', updater: user });
|
|
94
|
+
return (await tx.getRepository(survey_trustee_1.SurveyTrustee).findOne({ where: { id: mine.id } }));
|
|
95
|
+
}
|
|
96
|
+
/** A key holder's dealing: their commitments and a sealed share for every key holder - once all have transport keys. */
|
|
97
|
+
async function postDealing(tx, domain, user, id, dealing, sealed) {
|
|
98
|
+
const survey = await secretOf(tx, domain, id, 'KEYING');
|
|
99
|
+
const mine = await myTrustee(tx, survey, user);
|
|
100
|
+
const all = await trusteesOf(tx, id);
|
|
101
|
+
if (all.some(one => one.status === 'INVITED'))
|
|
102
|
+
throw (0, refusal_1.surveyRefusal)('survey-trustees-not-ready');
|
|
103
|
+
if (mine.status !== 'KEYED')
|
|
104
|
+
throw (0, refusal_1.surveyRefusal)('survey-trustee-step-done');
|
|
105
|
+
const commitments = (dealing?.commitments ?? []).map(group_js_1.fromHex);
|
|
106
|
+
if (!(0, threshold_js_1.dealingStands)(commitments, dealing?.proof, survey.trusteeThreshold, `${(0, exports.keyingContext)(survey)}|deal|${mine.seq}`))
|
|
107
|
+
throw (0, refusal_1.surveyRefusal)('survey-trustee-proof-invalid');
|
|
108
|
+
for (const one of all) {
|
|
109
|
+
const share = sealed?.[String(one.seq)];
|
|
110
|
+
if (!share || !(0, group_js_1.isElement)((0, group_js_1.fromHex)(share.u)) || !/^[0-9a-f]+$/.test(share.v))
|
|
111
|
+
throw (0, refusal_1.surveyRefusal)('survey-trustee-proof-invalid');
|
|
112
|
+
}
|
|
113
|
+
await tx.getRepository(survey_trustee_1.SurveyTrustee).update(mine.id, { dealing: { commitments: dealing.commitments, proof: dealing.proof }, sealedShares: sealed, status: 'DEALT', updater: user });
|
|
114
|
+
return (await tx.getRepository(survey_trustee_1.SurveyTrustee).findOne({ where: { id: mine.id } }));
|
|
115
|
+
}
|
|
116
|
+
/** A key holder says every share sealed to them matched its dealer's commitments - their browser checked. */
|
|
117
|
+
async function confirmShares(tx, domain, user, id) {
|
|
118
|
+
const survey = await secretOf(tx, domain, id, 'KEYING');
|
|
119
|
+
const mine = await myTrustee(tx, survey, user);
|
|
120
|
+
const all = await trusteesOf(tx, id);
|
|
121
|
+
if (all.some(one => one.status === 'INVITED' || one.status === 'KEYED'))
|
|
122
|
+
throw (0, refusal_1.surveyRefusal)('survey-trustees-not-ready');
|
|
123
|
+
if (mine.status !== 'DEALT')
|
|
124
|
+
throw (0, refusal_1.surveyRefusal)('survey-trustee-step-done');
|
|
125
|
+
await tx.getRepository(survey_trustee_1.SurveyTrustee).update(mine.id, { status: 'CONFIRMED', updater: user });
|
|
126
|
+
return (await tx.getRepository(survey_trustee_1.SurveyTrustee).findOne({ where: { id: mine.id } }));
|
|
127
|
+
}
|
|
128
|
+
/* ---- opening (design §3-2 step 3) */
|
|
129
|
+
/** Opens a keyed secret survey: its key is the key holders' together; each class gets its own token key. */
|
|
130
|
+
async function openSecret(tx, domain, user, survey, now) {
|
|
131
|
+
const trustees = await trusteesOf(tx, survey.id);
|
|
132
|
+
if (!trustees.length || trustees.some(one => one.status !== 'CONFIRMED'))
|
|
133
|
+
throw (0, refusal_1.surveyRefusal)('survey-keying-incomplete');
|
|
134
|
+
const asked = await (0, survey_service_1.askedUserIdsOf)(tx, domain, survey, now);
|
|
135
|
+
const questions = await (0, survey_service_1.questionsOf)(tx, survey.id);
|
|
136
|
+
const problem = (0, survey_rules_1.openingProblem)({ level: survey.level, questions, audienceCount: asked.length, closesAt: survey.closesAt, resultReaders: survey.resultReaders }, now);
|
|
137
|
+
if (problem)
|
|
138
|
+
throw (0, refusal_1.surveyRefusal)(problem.code, problem.params ?? {});
|
|
139
|
+
const classes = await (0, survey_service_1.classesOf)(tx, domain, survey, asked);
|
|
140
|
+
if (!classes.byUser.size && asked.length < (survey.minGroup ?? 0))
|
|
141
|
+
throw (0, refusal_1.surveyRefusal)('survey-weight-class-small', { class: exports.ALL, size: asked.length, min: survey.minGroup ?? 0 });
|
|
142
|
+
const publicKey = (0, threshold_js_1.publicKeyOf)(trustees.map(one => one.dealing.commitments.map(group_js_1.fromHex)));
|
|
143
|
+
const respondents = tx.getRepository(survey_respondent_1.SurveyRespondent);
|
|
144
|
+
for (const userId of asked)
|
|
145
|
+
await respondents.save({ domain, survey, user: { id: userId }, weightClass: classes.byUser.get(userId) ?? exports.ALL, taken: false, creator: user });
|
|
146
|
+
const used = new Set(asked.map(userId => classes.byUser.get(userId) ?? exports.ALL));
|
|
147
|
+
for (const weightClass of used) {
|
|
148
|
+
const { privateKey } = (0, crypto_1.generateKeyPairSync)('rsa', { modulusLength: 2048, publicExponent: 65537 });
|
|
149
|
+
const jwk = privateKey.export({ format: 'jwk' });
|
|
150
|
+
await tx.getRepository(survey_class_key_1.SurveyClassKey).save({ domain, survey, weightClass, modulus: (0, group_js_1.hex)(bigOf(jwk.n)), exponent: (0, group_js_1.hex)(bigOf(jwk.e)), privateExponent: (0, group_js_1.hex)(bigOf(jwk.d)), creator: user, updater: user });
|
|
151
|
+
}
|
|
152
|
+
await tx.getRepository(survey_1.Survey).update(survey.id, { status: 'OPEN', openedAt: now, askedCount: asked.length, publicKey: (0, group_js_1.hex)(publicKey), updater: user });
|
|
153
|
+
}
|
|
154
|
+
/** What a person's browser needs to seal a ballot: the survey's key, their class and its token key. */
|
|
155
|
+
async function ballotKitOf(tx, domain, user, id) {
|
|
156
|
+
const survey = await secretOf(tx, domain, id);
|
|
157
|
+
const respondent = await tx.getRepository(survey_respondent_1.SurveyRespondent).findOne({ where: { survey: { id }, user: { id: user.id } } });
|
|
158
|
+
if (!respondent)
|
|
159
|
+
throw (0, refusal_1.surveyRefusal)('survey-not-asked');
|
|
160
|
+
const key = await tx.getRepository(survey_class_key_1.SurveyClassKey).findOne({ where: { survey: { id }, weightClass: respondent.weightClass } });
|
|
161
|
+
if (!key || !survey.publicKey)
|
|
162
|
+
throw (0, refusal_1.surveyRefusal)('survey-step-not-now', { step: 'ballot', status: survey.status });
|
|
163
|
+
return { surveyId: id, publicKey: survey.publicKey, weightClass: respondent.weightClass, modulus: key.modulus, exponent: key.exponent, taken: respondent.taken };
|
|
164
|
+
}
|
|
165
|
+
/** Signs a person's blinded token - once. The server sees the blinded value only; it never learns the serial. */
|
|
166
|
+
async function issueBallot(tx, domain, user, id, blinded, now = new Date()) {
|
|
167
|
+
const survey = await secretOf(tx, domain, id);
|
|
168
|
+
if (survey.status !== 'OPEN' || (0, survey_rules_1.closeDue)(survey, now))
|
|
169
|
+
throw (0, refusal_1.surveyRefusal)('survey-step-not-now', { step: 'issue', status: survey.status });
|
|
170
|
+
const respondent = await tx.getRepository(survey_respondent_1.SurveyRespondent).findOne({ where: { survey: { id }, user: { id: user.id } } });
|
|
171
|
+
if (!respondent)
|
|
172
|
+
throw (0, refusal_1.surveyRefusal)('survey-not-asked');
|
|
173
|
+
const key = await tx.getRepository(survey_class_key_1.SurveyClassKey).findOne({ where: { survey: { id }, weightClass: respondent.weightClass } });
|
|
174
|
+
if (!key)
|
|
175
|
+
throw (0, refusal_1.surveyRefusal)('survey-not-asked');
|
|
176
|
+
const taken = await tx.getRepository(survey_respondent_1.SurveyRespondent).update({ id: respondent.id, taken: false }, { taken: true });
|
|
177
|
+
if (!taken.affected)
|
|
178
|
+
throw (0, refusal_1.surveyRefusal)('survey-answered');
|
|
179
|
+
let value;
|
|
180
|
+
try {
|
|
181
|
+
value = (0, group_js_1.fromHex)(blinded);
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
throw (0, refusal_1.surveyRefusal)('survey-ballot-invalid');
|
|
185
|
+
}
|
|
186
|
+
return (0, group_js_1.hex)((0, blind_rsa_js_1.blindSign)({ n: (0, group_js_1.fromHex)(key.modulus), e: (0, group_js_1.fromHex)(key.exponent), d: (0, group_js_1.fromHex)(key.privateExponent) }, value));
|
|
187
|
+
}
|
|
188
|
+
function checkInWorker(data) {
|
|
189
|
+
return new Promise((resolve, reject) => {
|
|
190
|
+
const worker = new worker_threads_1.Worker((0, path_1.join)(__dirname, 'ballot-worker.js'), { workerData: data });
|
|
191
|
+
worker.once('message', message => resolve(message.problem));
|
|
192
|
+
worker.once('error', reject);
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
const SERIAL = /^[0-9a-f]{64}$/;
|
|
196
|
+
const receiptOf = (one) => sha256(JSON.stringify({ serial: one.serial, sealed: one.sealed }));
|
|
197
|
+
/**
|
|
198
|
+
* A ballot that comes in without a sign-in (design §6-4): the token's signature under its class's key, a serial not used
|
|
199
|
+
* before, every proof - then kept, and its receipt returned. Sent twice, the same ballot answers with the same receipt.
|
|
200
|
+
*/
|
|
201
|
+
async function acceptBallot(tx, domain, submission, now = new Date()) {
|
|
202
|
+
const survey = await secretOf(tx, domain, submission?.surveyId);
|
|
203
|
+
if (survey.status !== 'OPEN' || (0, survey_rules_1.closeDue)(survey, now))
|
|
204
|
+
throw (0, refusal_1.surveyRefusal)('survey-step-not-now', { step: 'submit', status: survey.status });
|
|
205
|
+
const { weightClass, serial, signature, sealed } = submission;
|
|
206
|
+
if (!SERIAL.test(String(serial)) || typeof signature !== 'string')
|
|
207
|
+
throw (0, refusal_1.surveyRefusal)('survey-ballot-invalid');
|
|
208
|
+
const key = await tx.getRepository(survey_class_key_1.SurveyClassKey).findOne({ where: { survey: { id: survey.id }, weightClass: String(weightClass) } });
|
|
209
|
+
if (!key)
|
|
210
|
+
throw (0, refusal_1.surveyRefusal)('survey-ballot-invalid');
|
|
211
|
+
let signed = false;
|
|
212
|
+
try {
|
|
213
|
+
signed = (0, blind_rsa_js_1.verifyToken)({ n: (0, group_js_1.fromHex)(key.modulus), e: (0, group_js_1.fromHex)(key.exponent) }, (0, blind_rsa_js_1.tokenMessage)(survey.id, serial), (0, group_js_1.fromHex)(signature));
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
signed = false;
|
|
217
|
+
}
|
|
218
|
+
if (!signed)
|
|
219
|
+
throw (0, refusal_1.surveyRefusal)('survey-ballot-invalid');
|
|
220
|
+
const receipt = receiptOf({ serial, sealed });
|
|
221
|
+
const there = await tx.getRepository(survey_ballot_1.SurveyBallot).findOne({ where: { survey: { id: survey.id }, serial } });
|
|
222
|
+
if (there) {
|
|
223
|
+
if (there.receipt === receipt)
|
|
224
|
+
return receipt;
|
|
225
|
+
throw (0, refusal_1.surveyRefusal)('survey-ballot-used');
|
|
226
|
+
}
|
|
227
|
+
const questions = await (0, survey_service_1.questionsOf)(tx, survey.id);
|
|
228
|
+
const problem = await checkInWorker({ h: survey.publicKey, questions: questions.map(plainQuestion), sealed, context: (0, exports.ballotContext)(survey, serial) });
|
|
229
|
+
if (problem)
|
|
230
|
+
throw (0, refusal_1.surveyRefusal)('survey-ballot-invalid');
|
|
231
|
+
await tx.getRepository(survey_ballot_1.SurveyBallot).insert({ domain: { id: survey.domainId }, survey: { id: survey.id }, weightClass: key.weightClass, serial, signature, sealed, receipt });
|
|
232
|
+
return receipt;
|
|
233
|
+
}
|
|
234
|
+
const plainQuestion = (one) => ({ id: one.id, kind: one.kind, options: one.options, maxPicks: one.maxPicks, scaleMin: one.scaleMin, scaleMax: one.scaleMax, allocateTotal: one.allocateTotal });
|
|
235
|
+
/* ---- counting (design §3-2 steps 6 · 7) */
|
|
236
|
+
/**
|
|
237
|
+
* Fixes the bulletin and multiplies its ballots into one sum per cell - weighted or not, as the survey publishes - then
|
|
238
|
+
* waits for the key holders. No class may hold more ballots than tokens were issued to it.
|
|
239
|
+
*/
|
|
240
|
+
async function beginSecretCount(tx, domain, user, survey) {
|
|
241
|
+
const questions = (await (0, survey_service_1.questionsOf)(tx, survey.id)).map(plainQuestion);
|
|
242
|
+
const ballots = (await tx.getRepository(survey_ballot_1.SurveyBallot).find({ where: { survey: { id: survey.id } } })).sort((a, b) => a.receipt.localeCompare(b.receipt));
|
|
243
|
+
const respondents = await tx.getRepository(survey_respondent_1.SurveyRespondent).find({ where: { survey: { id: survey.id }, taken: true } });
|
|
244
|
+
const issued = {};
|
|
245
|
+
for (const one of respondents)
|
|
246
|
+
issued[one.weightClass ?? exports.ALL] = (issued[one.weightClass ?? exports.ALL] ?? 0) + 1;
|
|
247
|
+
const cast = {};
|
|
248
|
+
for (const one of ballots)
|
|
249
|
+
cast[one.weightClass] = (cast[one.weightClass] ?? 0) + 1;
|
|
250
|
+
const over = Object.entries(cast).find(([key, count]) => count > (issued[key] ?? 0));
|
|
251
|
+
if (over)
|
|
252
|
+
throw (0, refusal_1.surveyRefusal)('survey-ballots-exceed-issued', { class: over[0] });
|
|
253
|
+
const weighted = survey.publishedFigure === 'WEIGHTED' && !!survey.weighting?.classes?.length;
|
|
254
|
+
const rateFor = (weightClass) => (weighted ? (0, survey_service_1.rateOf)(survey.weighting, weightClass) : 1);
|
|
255
|
+
const sums = (0, ballot_js_1.weightedSums)(ballots.map(one => ({ rate: rateFor(one.weightClass), cells: (0, ballot_js_1.cellsOfChecked)(questions, one.sealed) })), questions).map(cells => cells.map(elgamal_js_1.cipherJson));
|
|
256
|
+
const maxRate = Math.max(1, ...ballots.map(one => rateFor(one.weightClass)));
|
|
257
|
+
const facts = { issued, cast, figure: weighted ? 'WEIGHTED' : 'UNWEIGHTED', rates: weighted ? Object.fromEntries((survey.weighting.classes ?? []).map((one) => [one.key, one.rate])) : null, ballots: ballots.length, maxRate };
|
|
258
|
+
const bulletinHash = sha256(JSON.stringify({ publicKey: survey.publicKey, facts, ballots: ballots.map(({ weightClass, serial, signature, sealed, receipt }) => ({ weightClass, serial, signature, sealed, receipt })) }));
|
|
259
|
+
await tx.getRepository(survey_1.Survey).update(survey.id, { status: 'DECRYPTING', sums, bulletinFacts: facts, bulletinHash, updater: user });
|
|
260
|
+
}
|
|
261
|
+
/** A key holder's partial decryptions of every sum, each with its proof - checked against their verification key. */
|
|
262
|
+
async function postPartials(tx, domain, user, id, partials) {
|
|
263
|
+
const survey = await secretOf(tx, domain, id, 'DECRYPTING');
|
|
264
|
+
const mine = await myTrustee(tx, survey, user);
|
|
265
|
+
if (mine.status !== 'CONFIRMED')
|
|
266
|
+
throw (0, refusal_1.surveyRefusal)('survey-trustee-step-done');
|
|
267
|
+
const all = await trusteesOf(tx, id);
|
|
268
|
+
const verificationKey = (0, threshold_js_1.verificationKeyOf)(all.map(one => one.dealing.commitments.map(group_js_1.fromHex)), mine.seq);
|
|
269
|
+
const sums = survey.sums;
|
|
270
|
+
const fits = Array.isArray(partials) &&
|
|
271
|
+
partials.length === sums.length &&
|
|
272
|
+
sums.every((cells, n) => partials[n]?.length === cells.length && cells.every((cell, k) => partials[n][k]?.index === mine.seq && (0, threshold_js_1.partialStands)((0, elgamal_js_1.cipherOf)(cell), partials[n][k], verificationKey, (0, exports.tallyContext)(survey))));
|
|
273
|
+
if (!fits)
|
|
274
|
+
throw (0, refusal_1.surveyRefusal)('survey-trustee-proof-invalid');
|
|
275
|
+
await tx.getRepository(survey_trustee_1.SurveyTrustee).update(mine.id, { partials, status: 'DECRYPTED', updater: user });
|
|
276
|
+
const done = (await trusteesOf(tx, id)).filter(one => one.status === 'DECRYPTED');
|
|
277
|
+
if (done.length >= survey.trusteeThreshold)
|
|
278
|
+
await finishSecretCount(tx, survey, done.slice(0, survey.trusteeThreshold), user);
|
|
279
|
+
return await (0, survey_service_1.surveyOf)(tx, domain, id);
|
|
280
|
+
}
|
|
281
|
+
async function finishSecretCount(tx, survey, trustees, user) {
|
|
282
|
+
const questions = await (0, survey_service_1.questionsOf)(tx, survey.id);
|
|
283
|
+
const facts = survey.bulletinFacts;
|
|
284
|
+
const counts = questions.map((question, n) => {
|
|
285
|
+
const plain = plainQuestion(question);
|
|
286
|
+
const keys = (0, ballot_js_1.cellsOf)(plain);
|
|
287
|
+
const out = {};
|
|
288
|
+
keys.forEach((key, k) => {
|
|
289
|
+
const value = (0, elgamal_js_1.discreteLog)((0, threshold_js_1.combine)((0, elgamal_js_1.cipherOf)(survey.sums[n][k]), trustees.map(one => one.partials[n][k])), (0, ballot_js_1.boundOf)(plain, facts.ballots, facts.maxRate));
|
|
290
|
+
if (value === undefined)
|
|
291
|
+
throw (0, refusal_1.surveyRefusal)('survey-decrypt-failed');
|
|
292
|
+
out[key] = value;
|
|
293
|
+
});
|
|
294
|
+
const sum = question.kind === 'SCALE' ? keys.reduce((total, key) => total + Number(key) * out[key], 0) : undefined;
|
|
295
|
+
return { questionId: question.id, seq: question.seq, kind: question.kind, counts: out, ...(sum === undefined ? {} : { sum }) };
|
|
296
|
+
});
|
|
297
|
+
const result = facts.figure === 'WEIGHTED' ? { responded: facts.ballots, unweighted: [], weighted: counts } : { responded: facts.ballots, unweighted: counts };
|
|
298
|
+
await tx.getRepository(survey_1.Survey).update(survey.id, { status: 'COUNTED', result, updater: user });
|
|
299
|
+
}
|
|
300
|
+
/* ---- reading (design §6-5) */
|
|
301
|
+
/** Everything the count can be checked from - ciphertexts, proofs, keys, sums and partials; no person. */
|
|
302
|
+
async function bulletinOf(tx, domain, id) {
|
|
303
|
+
const survey = await secretOf(tx, domain, id);
|
|
304
|
+
const ballots = (await tx.getRepository(survey_ballot_1.SurveyBallot).find({ where: { survey: { id } } })).sort((a, b) => a.receipt.localeCompare(b.receipt));
|
|
305
|
+
const keys = await tx.getRepository(survey_class_key_1.SurveyClassKey).find({ where: { survey: { id } } });
|
|
306
|
+
const trustees = await trusteesOf(tx, id);
|
|
307
|
+
return {
|
|
308
|
+
surveyId: id,
|
|
309
|
+
publicKey: survey.publicKey,
|
|
310
|
+
threshold: survey.trusteeThreshold,
|
|
311
|
+
trustees: trustees.map(one => ({ seq: one.seq, status: one.status, transportKey: one.transportKey, dealing: one.dealing, partials: one.partials ?? null })),
|
|
312
|
+
classKeys: keys.map(one => ({ weightClass: one.weightClass, modulus: one.modulus, exponent: one.exponent })),
|
|
313
|
+
questions: (await (0, survey_service_1.questionsOf)(tx, id)).map(plainQuestion),
|
|
314
|
+
ballots: ballots.map(({ weightClass, serial, signature, sealed, receipt }) => ({ weightClass, serial, signature, sealed, receipt })),
|
|
315
|
+
facts: survey.bulletinFacts ?? null,
|
|
316
|
+
sums: survey.sums ?? null,
|
|
317
|
+
bulletinHash: survey.bulletinHash ?? null,
|
|
318
|
+
result: ['COUNTED', 'PUBLISHED'].includes(survey.status) ? survey.result : null
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
/** Whether a receipt is on the survey's ballots - a person checks their own without seeing the others. */
|
|
322
|
+
async function receiptListed(tx, domain, id, receipt) {
|
|
323
|
+
const survey = await secretOf(tx, domain, id);
|
|
324
|
+
return (await tx.getRepository(survey_ballot_1.SurveyBallot).count({ where: { survey: { id: survey.id }, receipt: String(receipt) } })) > 0;
|
|
325
|
+
}
|
|
326
|
+
/** A key holder's own view: the survey's key-making facts, and every share sealed to them. */
|
|
327
|
+
async function trusteeViewOf(tx, domain, user, id) {
|
|
328
|
+
const survey = await secretOf(tx, domain, id);
|
|
329
|
+
const mine = await myTrustee(tx, survey, user);
|
|
330
|
+
const all = await trusteesOf(tx, id);
|
|
331
|
+
return {
|
|
332
|
+
surveyId: id,
|
|
333
|
+
name: survey.name,
|
|
334
|
+
status: survey.status,
|
|
335
|
+
threshold: survey.trusteeThreshold,
|
|
336
|
+
seq: mine.seq,
|
|
337
|
+
myStatus: mine.status,
|
|
338
|
+
trustees: all.map(one => ({ seq: one.seq, status: one.status, transportKey: one.transportKey ?? null, commitments: one.dealing?.commitments ?? null })),
|
|
339
|
+
sharesForMe: all.filter(one => one.sealedShares).map(one => ({ dealer: one.seq, sealed: one.sealedShares[String(mine.seq)] })),
|
|
340
|
+
sums: survey.status === 'DECRYPTING' ? survey.sums : null
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
async function myTrusteeSurveys(tx, domain, user) {
|
|
344
|
+
const rows = await tx.getRepository(survey_trustee_1.SurveyTrustee).find({ where: { domain: { id: domain.id }, user: { id: user.id } }, relations: ['survey'] });
|
|
345
|
+
return rows.filter(one => one.survey && one.survey.status !== 'CANCELLED').map(one => ({ surveyId: one.survey.id, name: one.survey.name, status: one.survey.status, myStatus: one.status, seq: one.seq }));
|
|
346
|
+
}
|
|
347
|
+
//# sourceMappingURL=survey-secret.js.map
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { EntityManager } from 'typeorm';
|
|
2
|
+
import { Domain } from '@things-factory/shell';
|
|
3
|
+
import { Survey } from './survey';
|
|
4
|
+
import { SurveyQuestion } from './survey-question';
|
|
5
|
+
import { type AnswerValue, type QuestionFacts, type Weighting } from './survey-rules';
|
|
6
|
+
type Who = {
|
|
7
|
+
id: string;
|
|
8
|
+
};
|
|
9
|
+
export declare function surveyOf(tx: EntityManager, domain: Partial<Domain>, id: string): Promise<Survey>;
|
|
10
|
+
export interface SurveyPatchFacts {
|
|
11
|
+
name?: string;
|
|
12
|
+
description?: string | null;
|
|
13
|
+
level?: string;
|
|
14
|
+
audience?: {
|
|
15
|
+
scope: string;
|
|
16
|
+
targetId: string;
|
|
17
|
+
}[] | null;
|
|
18
|
+
excludedUserIds?: string[] | null;
|
|
19
|
+
basisDate?: string | null;
|
|
20
|
+
closesAt?: Date | null;
|
|
21
|
+
resultReaders?: string | null;
|
|
22
|
+
publishedFigure?: string | null;
|
|
23
|
+
minGroup?: number | null;
|
|
24
|
+
weighting?: Weighting | null;
|
|
25
|
+
trusteeUserIds?: string[] | null;
|
|
26
|
+
trusteeThreshold?: number | null;
|
|
27
|
+
publishTop?: number | null;
|
|
28
|
+
publishTopFigures?: boolean | null;
|
|
29
|
+
followsSurveyId?: string | null;
|
|
30
|
+
carryTop?: number | null;
|
|
31
|
+
successionDepth?: number | null;
|
|
32
|
+
withdrawnKeys?: string[] | null;
|
|
33
|
+
}
|
|
34
|
+
export declare function createSurvey(tx: EntityManager, domain: Domain, user: Who, patch: SurveyPatchFacts): Promise<Survey>;
|
|
35
|
+
export declare function updateSurvey(tx: EntityManager, domain: Domain, user: Who, id: string, patch: SurveyPatchFacts): Promise<Survey>;
|
|
36
|
+
export declare function deleteSurvey(tx: EntityManager, domain: Domain, id: string): Promise<boolean>;
|
|
37
|
+
/** Replaces a draft's questions with `questions`, in their order. */
|
|
38
|
+
export declare function setSurveyQuestions(tx: EntityManager, domain: Domain, user: Who, id: string, questions: Omit<QuestionFacts, 'seq'>[]): Promise<SurveyQuestion[]>;
|
|
39
|
+
export declare const questionsOf: (tx: EntityManager, surveyId: string) => Promise<SurveyQuestion[]>;
|
|
40
|
+
/** The people a survey asks now: those its audience names who work here today, less those left out. */
|
|
41
|
+
export declare function askedUserIdsOf(tx: EntityManager, domain: Domain, survey: Survey, now?: Date): Promise<string[]>;
|
|
42
|
+
export interface ClassFill {
|
|
43
|
+
byUser: Map<string, string>;
|
|
44
|
+
sizes: Record<string, number>;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Each person's weight class on the basis day (design §5) - refused when the weighting does not stand, someone fits no
|
|
48
|
+
* class, or a class with anyone in it holds fewer than the smallest group. An unweighted survey has no classes.
|
|
49
|
+
*/
|
|
50
|
+
export declare function classesOf(tx: EntityManager, domain: Domain, survey: Survey, userIds: string[], check?: boolean): Promise<ClassFill>;
|
|
51
|
+
/** How many people each class would hold if the draft opened now - for the operator, before opening; sizes only. */
|
|
52
|
+
export declare function classPreviewOf(tx: EntityManager, domain: Domain, id: string, now?: Date): Promise<Record<string, number>>;
|
|
53
|
+
/** Opens a draft: the list of people asked is made once, now, and kept (design §3-1 step 2). */
|
|
54
|
+
export declare function openSurvey(tx: EntityManager, domain: Domain, user: Who, id: string, now?: Date): Promise<Survey>;
|
|
55
|
+
/** One person's answers to a named survey - every question, once (design §3-1 step 3). */
|
|
56
|
+
export declare function answerSurvey(tx: EntityManager, domain: Domain, user: Who, id: string, answers: {
|
|
57
|
+
questionId: string;
|
|
58
|
+
value: AnswerValue;
|
|
59
|
+
}[], now?: Date): Promise<boolean>;
|
|
60
|
+
export declare function closeSurvey(tx: EntityManager, domain: Domain, user: Who, id: string, now?: Date): Promise<Survey>;
|
|
61
|
+
/** The rate of a weight class - 1 when the survey is not weighted. */
|
|
62
|
+
export declare function rateOf(weighting: any, weightClass?: string | null): number;
|
|
63
|
+
/** Counts a closed named survey; the count is the operators' until published (design §3-1 step 5). */
|
|
64
|
+
export declare function countSurvey(tx: EntityManager, domain: Domain, user: Who, id: string): Promise<Survey>;
|
|
65
|
+
/** Publishes what may be published (design §4) - the readers chosen when it was made read it. */
|
|
66
|
+
export declare function publishSurvey(tx: EntityManager, domain: Domain, user: Who, id: string, now?: Date): Promise<Survey>;
|
|
67
|
+
export declare function cancelSurvey(tx: EntityManager, domain: Domain, user: Who, id: string, reason?: string | null): Promise<Survey>;
|
|
68
|
+
/** Closes the open surveys whose time has come - each by one update while it is still open, so two servers close it once. */
|
|
69
|
+
export declare function closeDueSurveys(now?: Date): Promise<number>;
|
|
70
|
+
/** Checked every minute, as a proposal's vote is (ADR-0197 decision 5). */
|
|
71
|
+
export declare function scheduleSurveyClosing(): void;
|
|
72
|
+
/** The choices of the round before - their labels only, for marking who withdrew; never their ranks (design §7). */
|
|
73
|
+
export declare function previousChoicesOf(tx: EntityManager, domain: Domain, id: string): Promise<{
|
|
74
|
+
key: string;
|
|
75
|
+
label: string;
|
|
76
|
+
}[]>;
|
|
77
|
+
/**
|
|
78
|
+
* Takes this draft's choices from the round before (design §7): its first question's top `carryTop` among those not
|
|
79
|
+
* withdrawn, no further down than `successionDepth`. The round before must be counted. The draft's first question takes
|
|
80
|
+
* the round before's prompt unless it has one of its own; it is a pick-one.
|
|
81
|
+
*/
|
|
82
|
+
export declare function carryForward(tx: EntityManager, domain: Domain, user: Who, id: string): Promise<SurveyQuestion[]>;
|
|
83
|
+
export {};
|