@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.
Files changed (81) hide show
  1. package/dist-client/index.d.ts +1 -0
  2. package/dist-client/index.js +2 -0
  3. package/dist-client/pages/my-surveys.d.ts +24 -0
  4. package/dist-client/pages/my-surveys.js +256 -0
  5. package/dist-client/pages/survey-editor.d.ts +62 -0
  6. package/dist-client/pages/survey-editor.js +668 -0
  7. package/dist-client/pages/survey-list.d.ts +15 -0
  8. package/dist-client/pages/survey-list.js +150 -0
  9. package/dist-client/pages/survey-trustee.d.ts +21 -0
  10. package/dist-client/pages/survey-trustee.js +170 -0
  11. package/dist-client/route.d.ts +1 -0
  12. package/dist-client/route.js +17 -0
  13. package/dist-client/utils/survey-api.d.ts +16 -0
  14. package/dist-client/utils/survey-api.js +46 -0
  15. package/dist-client/utils/survey-result.d.ts +4 -0
  16. package/dist-client/utils/survey-result.js +79 -0
  17. package/dist-client/utils/survey-secret.d.ts +40 -0
  18. package/dist-client/utils/survey-secret.js +154 -0
  19. package/dist-server/index.d.ts +2 -0
  20. package/dist-server/index.js +27 -0
  21. package/dist-server/role-tasks.d.ts +2 -0
  22. package/dist-server/role-tasks.js +16 -0
  23. package/dist-server/service/index.d.ts +16 -0
  24. package/dist-server/service/index.js +30 -0
  25. package/dist-server/service/refusal.d.ts +57 -0
  26. package/dist-server/service/refusal.js +66 -0
  27. package/dist-server/service/survey/ballot-route.d.ts +1 -0
  28. package/dist-server/service/survey/ballot-route.js +30 -0
  29. package/dist-server/service/survey/ballot-worker.d.ts +1 -0
  30. package/dist-server/service/survey/ballot-worker.js +19 -0
  31. package/dist-server/service/survey/index.d.ts +10 -0
  32. package/dist-server/service/survey/index.js +14 -0
  33. package/dist-server/service/survey/survey-answer.d.ts +23 -0
  34. package/dist-server/service/survey/survey-answer.js +99 -0
  35. package/dist-server/service/survey/survey-attributes.d.ts +16 -0
  36. package/dist-server/service/survey/survey-attributes.js +39 -0
  37. package/dist-server/service/survey/survey-ballot.d.ts +14 -0
  38. package/dist-server/service/survey/survey-ballot.js +61 -0
  39. package/dist-server/service/survey/survey-class-key.d.ts +20 -0
  40. package/dist-server/service/survey/survey-class-key.js +92 -0
  41. package/dist-server/service/survey/survey-question.d.ts +27 -0
  42. package/dist-server/service/survey/survey-question.js +113 -0
  43. package/dist-server/service/survey/survey-resolver.d.ts +37 -0
  44. package/dist-server/service/survey/survey-resolver.js +492 -0
  45. package/dist-server/service/survey/survey-respondent.d.ts +17 -0
  46. package/dist-server/service/survey/survey-respondent.js +81 -0
  47. package/dist-server/service/survey/survey-rules.d.ts +169 -0
  48. package/dist-server/service/survey/survey-rules.js +299 -0
  49. package/dist-server/service/survey/survey-secret.d.ts +133 -0
  50. package/dist-server/service/survey/survey-secret.js +347 -0
  51. package/dist-server/service/survey/survey-service.d.ts +83 -0
  52. package/dist-server/service/survey/survey-service.js +384 -0
  53. package/dist-server/service/survey/survey-trustee.d.ts +25 -0
  54. package/dist-server/service/survey/survey-trustee.js +119 -0
  55. package/dist-server/service/survey/survey-types.d.ts +91 -0
  56. package/dist-server/service/survey/survey-types.js +319 -0
  57. package/dist-server/service/survey/survey.d.ts +47 -0
  58. package/dist-server/service/survey/survey.js +214 -0
  59. package/dist-shared/ballot.d.ts +54 -0
  60. package/dist-shared/ballot.js +146 -0
  61. package/dist-shared/blind-rsa.d.ts +18 -0
  62. package/dist-shared/blind-rsa.js +127 -0
  63. package/dist-shared/elgamal.d.ts +20 -0
  64. package/dist-shared/elgamal.js +54 -0
  65. package/dist-shared/group.d.ts +22 -0
  66. package/dist-shared/group.js +112 -0
  67. package/dist-shared/proofs.d.ts +20 -0
  68. package/dist-shared/proofs.js +94 -0
  69. package/dist-shared/threshold.d.ts +39 -0
  70. package/dist-shared/threshold.js +98 -0
  71. package/dist-shared/verify.d.ts +13 -0
  72. package/dist-shared/verify.js +73 -0
  73. package/package.json +63 -4
  74. package/things-factory.config.js +15 -0
  75. package/translations/en.json +202 -0
  76. package/translations/es.json +202 -0
  77. package/translations/ja.json +202 -0
  78. package/translations/ko.json +202 -0
  79. package/translations/ms.json +202 -0
  80. package/translations/zh.json +202 -0
  81. package/README.md +0 -3
@@ -0,0 +1,154 @@
1
+ import gql from 'graphql-tag';
2
+ import { client } from '@operato/graphql';
3
+ import { sealBallot } from '@things-factory/survey/dist-shared/ballot.js';
4
+ import { blind, finalize, tokenMessage } from '@things-factory/survey/dist-shared/blind-rsa.js';
5
+ import { cipherOf } from '@things-factory/survey/dist-shared/elgamal.js';
6
+ import { fromHex, gPow, hex, randomBytes, randomScalar } from '@things-factory/survey/dist-shared/group.js';
7
+ import { proveKnowsLog } from '@things-factory/survey/dist-shared/proofs.js';
8
+ import { deal, openShare, partialOf, sealShare, shareFor, shareMatches } from '@things-factory/survey/dist-shared/threshold.js';
9
+ const keyingContext = (surveyId) => `survey:${surveyId}|keying`;
10
+ const ballotContext = (surveyId, serial) => `survey:${surveyId}|ballot|${serial}`;
11
+ const tallyContext = (surveyId) => `survey:${surveyId}|tally`;
12
+ const plain = (one) => ({ id: one.id, kind: one.kind, options: one.options, maxPicks: one.maxPicks, scaleMin: one.scaleMin, scaleMax: one.scaleMax, allocateTotal: one.allocateTotal });
13
+ /** A refusal from the ballot route, carried like a server refusal: its code, said by the screen. */
14
+ export class BallotRefusal extends Error {
15
+ constructor(code) {
16
+ super(code);
17
+ this.code = code;
18
+ }
19
+ }
20
+ /* ---- a person's ballot */
21
+ const PENDING = (surveyId) => `survey-ballot-pending:${surveyId}`;
22
+ const RECEIPT = (surveyId) => `survey-ballot-receipt:${surveyId}`;
23
+ function stored(key) {
24
+ try {
25
+ const text = localStorage.getItem(key);
26
+ return text ? JSON.parse(text) : undefined;
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
32
+ function store(key, value) {
33
+ try {
34
+ if (value === undefined)
35
+ localStorage.removeItem(key);
36
+ else
37
+ localStorage.setItem(key, JSON.stringify(value));
38
+ }
39
+ catch {
40
+ /* a browser that keeps nothing still sends the ballot - it only cannot resend it */
41
+ }
42
+ }
43
+ export const pendingBallotOf = (surveyId) => stored(PENDING(surveyId));
44
+ export const receiptOf = (surveyId) => stored(RECEIPT(surveyId))?.receipt;
45
+ /** Sent on the public route, without cookies - the request names nobody (design §6-4). */
46
+ async function postBallot(submission) {
47
+ const response = await fetch('/survey-ballots', {
48
+ method: 'POST',
49
+ credentials: 'omit',
50
+ headers: { 'Content-Type': 'application/json' },
51
+ body: JSON.stringify(submission)
52
+ });
53
+ const body = await response.json().catch(() => ({}));
54
+ if (!response.ok || !body.receipt)
55
+ throw new BallotRefusal(body.code ?? 'survey-ballot-invalid');
56
+ return body.receipt;
57
+ }
58
+ /** Sends a ballot that was sealed and signed but not yet received - the same ballot, the same token. */
59
+ export async function resendPending(surveyId) {
60
+ const pending = pendingBallotOf(surveyId);
61
+ if (!pending)
62
+ throw new BallotRefusal('survey-ballot-invalid');
63
+ const receipt = await postBallot(pending);
64
+ store(RECEIPT(surveyId), { receipt });
65
+ store(PENDING(surveyId), undefined);
66
+ return receipt;
67
+ }
68
+ /**
69
+ * Seals my answers to the survey's key, takes my one token blind, and sends the ballot without a sign-in. The ballot is
70
+ * sealed before the token is taken, so a failure to seal spends nothing; once signed, it is kept here until received.
71
+ */
72
+ export async function castSecretBallot(surveyId, questions, answers) {
73
+ const kit = (await client.query({ query: gql `query ($id: String!) { surveyBallotKit(id: $id) { publicKey weightClass modulus exponent taken } }`, variables: { id: surveyId }, fetchPolicy: 'network-only' })).data
74
+ ?.surveyBallotKit;
75
+ if (!kit)
76
+ throw new BallotRefusal('survey-not-asked');
77
+ if (kit.taken)
78
+ return await resendPending(surveyId);
79
+ const serial = [...randomBytes(32)].map(one => one.toString(16).padStart(2, '0')).join('');
80
+ const sealed = sealBallot(fromHex(kit.publicKey), questions.map(plain), answers, ballotContext(surveyId, serial));
81
+ const key = { n: fromHex(kit.modulus), e: fromHex(kit.exponent) };
82
+ const message = tokenMessage(surveyId, serial);
83
+ const { blinded, inverse } = blind(key, message);
84
+ const response = await client.mutate({ mutation: gql `mutation ($id: String!, $blinded: String!) { issueSurveyBallot(id: $id, blinded: $blinded) }`, variables: { id: surveyId, blinded: hex(blinded) } });
85
+ if (response.errors?.length)
86
+ throw response.errors[0];
87
+ const signature = hex(finalize(key, message, fromHex(response.data.issueSurveyBallot), inverse));
88
+ store(PENDING(surveyId), { surveyId, weightClass: kit.weightClass, serial, signature, sealed });
89
+ return await resendPending(surveyId);
90
+ }
91
+ /* ---- a key holder's key file */
92
+ const enc = new TextEncoder();
93
+ const dec = new TextDecoder();
94
+ const b64 = (bytes) => btoa(String.fromCharCode(...bytes));
95
+ const unb64 = (text) => Uint8Array.from(atob(text), c => c.charCodeAt(0));
96
+ const own = (bytes) => new Uint8Array(bytes);
97
+ async function aesKey(passphrase, salt) {
98
+ const base = await crypto.subtle.importKey('raw', enc.encode(passphrase), 'PBKDF2', false, ['deriveKey']);
99
+ return await crypto.subtle.deriveKey({ name: 'PBKDF2', salt, iterations: 310000, hash: 'SHA-256' }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
100
+ }
101
+ /** The key holder's secret, sealed with their passphrase into a file they keep - the server never sees either. */
102
+ export async function keyFileOf(content, passphrase) {
103
+ const salt = own(randomBytes(16));
104
+ const iv = own(randomBytes(12));
105
+ const data = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, await aesKey(passphrase, salt), enc.encode(JSON.stringify(content))));
106
+ return new Blob([JSON.stringify({ kind: 'operato-survey-key', surveyId: content.surveyId, seq: content.seq, salt: b64(salt), iv: b64(iv), data: b64(data) })], { type: 'application/json' });
107
+ }
108
+ export async function readKeyFile(file, passphrase) {
109
+ const sealed = JSON.parse(await file.text());
110
+ const plainText = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: unb64(sealed.iv) }, await aesKey(passphrase, unb64(sealed.salt)), unb64(sealed.data));
111
+ return JSON.parse(dec.decode(plainText));
112
+ }
113
+ export function download(blob, name) {
114
+ const url = URL.createObjectURL(blob);
115
+ const link = document.createElement('a');
116
+ link.href = url;
117
+ link.download = name;
118
+ link.click();
119
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
120
+ }
121
+ /* ---- a key holder's steps (design §3-2 step 2 · step 7) */
122
+ /** Step one: a transport key, its secret into the key file. */
123
+ export function makeTransportKey(surveyId, seq) {
124
+ const secret = randomScalar();
125
+ const key = gPow(secret);
126
+ return { secret: hex(secret), key: hex(key), proof: proveKnowsLog(key, secret, `${keyingContext(surveyId)}|transport|${seq}`) };
127
+ }
128
+ /** Step two: my dealing, and a share sealed to every key holder's transport key. */
129
+ export function makeDealing(view) {
130
+ const context = keyingContext(view.surveyId);
131
+ const dealing = deal(view.threshold, `${context}|deal|${view.seq}`);
132
+ const sealed = Object.fromEntries(view.trustees.map((one) => [String(one.seq), sealShare(fromHex(one.transportKey), shareFor(dealing.coefficients, one.seq), context)]));
133
+ return { dealing: { commitments: dealing.commitments.map(hex), proof: dealing.proof }, sealed };
134
+ }
135
+ /** My share of the survey's key - every share sealed to me, each checked against its dealer's commitments. */
136
+ export function myShareOf(view, transportSecret) {
137
+ const context = keyingContext(view.surveyId);
138
+ let total = 0n;
139
+ for (const { dealer, sealed } of view.sharesForMe) {
140
+ const share = openShare(fromHex(transportSecret), sealed, context);
141
+ const commitments = view.trustees.find((one) => one.seq === dealer)?.commitments;
142
+ if (!commitments || !shareMatches(commitments.map(fromHex), view.seq, share))
143
+ throw new Error(`share-from-${dealer}-does-not-match`);
144
+ total += share;
145
+ }
146
+ return total;
147
+ }
148
+ /** Step four: my partial decryption of every sum. */
149
+ export function makePartials(view, share) {
150
+ return view.sums.map(cells => cells.map(cell => partialOf(cipherOf(cell), view.seq, share, tallyContext(view.surveyId))));
151
+ }
152
+ /* ---- checking a bulletin (design §6-5) - pure, in shared/verify.ts */
153
+ export { checkBulletin } from '@things-factory/survey/dist-shared/verify.js';
154
+ //# sourceMappingURL=survey-secret.js.map
@@ -0,0 +1,2 @@
1
+ export * from './service';
2
+ export { ROLE_TASKS } from './role-tasks';
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ROLE_TASKS = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const auth_base_1 = require("@things-factory/auth-base");
6
+ const role_tasks_1 = require("./role-tasks");
7
+ const survey_attributes_1 = require("./service/survey/survey-attributes");
8
+ const survey_service_1 = require("./service/survey/survey-service");
9
+ const ballot_route_1 = require("./service/survey/ballot-route");
10
+ tslib_1.__exportStar(require("./service"), exports);
11
+ var role_tasks_2 = require("./role-tasks");
12
+ Object.defineProperty(exports, "ROLE_TASKS", { enumerable: true, get: function () { return role_tasks_2.ROLE_TASKS; } });
13
+ /*
14
+ * Surveys (operato-survey) - named surveys first; the secret level follows (design §10).
15
+ */
16
+ for (const task of role_tasks_1.ROLE_TASKS)
17
+ (0, auth_base_1.registerRoleTask)(task);
18
+ /* Tenure comes with the employee records every host has; shareholding is the host's to register (design §5-2). */
19
+ (0, survey_attributes_1.registerSurveyAttribute)(survey_attributes_1.TENURE_YEARS);
20
+ /* An open survey closes at its time - checked every minute (design §3-1 step 4). */
21
+ process.on('bootstrap-module-start', () => (0, survey_service_1.scheduleSurveyClosing)());
22
+ /*
23
+ * Secret ballots come in on the domain's public router - without a sign-in, so the request that brings a ballot carries
24
+ * nobody (design §6-4).
25
+ */
26
+ process.on('bootstrap-module-domain-public-route', (_app, domainPublicRouter) => (0, ballot_route_1.registerSurveyBallotRoute)(domainPublicRouter));
27
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ import type { RoleTask } from '@things-factory/auth-base';
2
+ export declare const ROLE_TASKS: RoleTask[];
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ROLE_TASKS = void 0;
4
+ /*
5
+ * The survey's role tasks (operato-survey design §1). Who is given them is the domain's administrator's choice
6
+ * (charter S11).
7
+ */
8
+ exports.ROLE_TASKS = [
9
+ /* Answering the surveys that ask me and reading the results published to me. */
10
+ { id: 'survey.respondent', grants: [{ category: 'survey', axes: ['query', 'mutation'] }] },
11
+ /* Making, opening, closing, counting and publishing surveys. */
12
+ { id: 'survey.operating', grants: [{ category: 'survey-admin', axes: ['query', 'mutation'] }] },
13
+ /* Holding a key of a secret survey - making it with the others, and opening the sums (design §6-3). */
14
+ { id: 'survey.trustee', grants: [{ category: 'survey-trustee', axes: ['query', 'mutation'] }] }
15
+ ];
16
+ //# sourceMappingURL=role-tasks.js.map
@@ -0,0 +1,16 @@
1
+ export * from './survey/survey';
2
+ export * from './survey/survey-question';
3
+ export * from './survey/survey-respondent';
4
+ export * from './survey/survey-answer';
5
+ export * from './survey/survey-rules';
6
+ export * from './survey/survey-service';
7
+ export * from './survey/survey-attributes';
8
+ export * from './survey/survey-secret';
9
+ export * from './survey/survey-trustee';
10
+ export * from './survey/survey-class-key';
11
+ export * from './survey/survey-ballot';
12
+ export * from './refusal';
13
+ export declare const entities: (typeof import("./survey/survey").Survey | typeof import("./survey/survey-question").SurveyQuestion | typeof import("./survey/survey-respondent").SurveyRespondent | typeof import("./survey/survey-answer").SurveyAnswer | typeof import("./survey/survey-ballot").SurveyBallot | typeof import("./survey/survey-class-key").SurveyClassKey | typeof import("./survey/survey-trustee").SurveyTrustee)[];
14
+ export declare const schema: {
15
+ resolverClasses: (typeof import("./survey/survey-resolver").SurveyResolver | typeof import("./survey/survey-resolver").SurveySecretResolver)[];
16
+ };
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.schema = exports.entities = void 0;
4
+ const tslib_1 = require("tslib");
5
+ /* EXPORT ENTITY TYPES */
6
+ tslib_1.__exportStar(require("./survey/survey"), exports);
7
+ tslib_1.__exportStar(require("./survey/survey-question"), exports);
8
+ tslib_1.__exportStar(require("./survey/survey-respondent"), exports);
9
+ tslib_1.__exportStar(require("./survey/survey-answer"), exports);
10
+ tslib_1.__exportStar(require("./survey/survey-rules"), exports);
11
+ tslib_1.__exportStar(require("./survey/survey-service"), exports);
12
+ tslib_1.__exportStar(require("./survey/survey-attributes"), exports);
13
+ tslib_1.__exportStar(require("./survey/survey-secret"), exports);
14
+ tslib_1.__exportStar(require("./survey/survey-trustee"), exports);
15
+ tslib_1.__exportStar(require("./survey/survey-class-key"), exports);
16
+ tslib_1.__exportStar(require("./survey/survey-ballot"), exports);
17
+ tslib_1.__exportStar(require("./refusal"), exports);
18
+ /* IMPORT ENTITIES AND RESOLVERS */
19
+ const survey_1 = require("./survey");
20
+ exports.entities = [
21
+ /* ENTITIES */
22
+ ...survey_1.entities
23
+ ];
24
+ exports.schema = {
25
+ resolverClasses: [
26
+ /* RESOLVER CLASSES */
27
+ ...survey_1.resolvers
28
+ ]
29
+ };
30
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,57 @@
1
+ import { Refusal } from '@things-factory/shell';
2
+ declare const ENGLISH: {
3
+ readonly 'survey-unknown': "no such survey in this domain";
4
+ readonly 'survey-step-not-now': "this survey is not at a step where that can be done";
5
+ readonly 'survey-level-unknown': "a survey is named or secret";
6
+ readonly 'survey-name-required': "give the survey a title";
7
+ readonly 'survey-no-questions': "a survey asks at least one question";
8
+ readonly 'survey-question-prompt-required': "a question says what it asks";
9
+ readonly 'survey-question-kind-unknown': "a question is single choice, multiple choice, a scale or an allocation";
10
+ readonly 'survey-question-scale-invalid': "a scale runs from a lower whole number to a higher one";
11
+ readonly 'survey-question-options-too-few': "a question offers at least two choices";
12
+ readonly 'survey-question-option-blank': "every choice has a key and a label";
13
+ readonly 'survey-question-option-duplicate': "two choices of a question have the same key";
14
+ readonly 'survey-question-max-picks-invalid': "how many may be chosen is between one and the number of choices";
15
+ readonly 'survey-question-total-invalid': "an allocation adds up to a whole number above zero";
16
+ readonly 'survey-readers-required': "choose who reads the published result";
17
+ readonly 'survey-figure-unknown': "the published figure is weighted or unweighted";
18
+ readonly 'survey-closes-at-past': "the closing time is not later than now";
19
+ readonly 'survey-nobody-asked': "the audience names nobody working here";
20
+ readonly 'survey-not-asked': "this survey does not ask you";
21
+ readonly 'survey-answered': "you have already answered this survey";
22
+ readonly 'survey-answer-missing': "a question is not answered";
23
+ readonly 'survey-answer-invalid': "an answer does not fit its question";
24
+ readonly 'survey-not-named': "only a named survey keeps who answered what";
25
+ readonly 'survey-weight-classes-too-few': "a weighting has at least two classes";
26
+ readonly 'survey-weight-class-key-invalid': "every class has its own key";
27
+ readonly 'survey-weight-rate-invalid': "a rate is a whole number of one or more";
28
+ readonly 'survey-weight-attribute-unknown': "no such attribute is registered here";
29
+ readonly 'survey-weight-condition-invalid': "a condition is one of: equals, at least, below";
30
+ readonly 'survey-weight-last-class-open': "the last class takes everyone left - it has no condition";
31
+ readonly 'survey-weight-class-small': "a class holds fewer people than the smallest group";
32
+ readonly 'survey-weight-unmatched': "someone asked fits no class";
33
+ readonly 'survey-basis-date-required': "a weighted survey names the day attributes are read on";
34
+ readonly 'survey-figure-required': "a weighted survey chooses the one set of figures it publishes";
35
+ readonly 'survey-not-secret': "this is not a secret survey";
36
+ readonly 'survey-not-trustee': "you are not a key holder of this survey";
37
+ readonly 'survey-trustees-invalid': "name the key holders and how many of them it takes to decrypt - at least one, at most all";
38
+ readonly 'survey-trustees-not-ready': "the other key holders have not reached this step yet";
39
+ readonly 'survey-trustee-step-done': "this step is not yours to take now";
40
+ readonly 'survey-trustee-proof-invalid': "what was sent does not check out";
41
+ readonly 'survey-keying-incomplete': "the key holders have not finished making the key";
42
+ readonly 'survey-ballot-invalid': "this ballot does not check out";
43
+ readonly 'survey-ballot-used': "this ballot token has been used";
44
+ readonly 'survey-ballots-exceed-issued': "a class holds more ballots than tokens issued to it - the count stops";
45
+ readonly 'survey-decrypt-failed': "the sums did not open - more key holders are needed";
46
+ readonly 'survey-top-too-few': "fewer choices are left than the top to be named";
47
+ readonly 'survey-top-tie': "a tie across the last place of the top - who is in it is not decided by this survey";
48
+ readonly 'survey-top-figures-required': "choose whether the top places are published with their figures or by rank alone";
49
+ readonly 'survey-carry-unset': "name the round before and how many choices to take from it";
50
+ readonly 'survey-follows-not-counted': "the round before is not counted yet";
51
+ readonly 'survey-carry-no-choices': "the round before has no question with choices first";
52
+ readonly 'survey-succession-exhausted': "not enough choices are left within the depth a withdrawn choice may be followed to";
53
+ };
54
+ export type SurveyRefusalCode = keyof typeof ENGLISH;
55
+ export declare function surveyRefusal(code: SurveyRefusalCode | string, params?: Record<string, string | number | boolean | null>): Refusal;
56
+ export declare const SURVEY_REFUSAL_CODES: SurveyRefusalCode[];
57
+ export {};
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SURVEY_REFUSAL_CODES = void 0;
4
+ exports.surveyRefusal = surveyRefusal;
5
+ const shell_1 = require("@things-factory/shell");
6
+ /*
7
+ * The survey's refusals - a name and values; the sentence is made where the request's language is known
8
+ * (`error.<code>` in translations). The English here is only the fallback.
9
+ */
10
+ const ENGLISH = {
11
+ 'survey-unknown': 'no such survey in this domain',
12
+ 'survey-step-not-now': 'this survey is not at a step where that can be done',
13
+ 'survey-level-unknown': 'a survey is named or secret',
14
+ 'survey-name-required': 'give the survey a title',
15
+ 'survey-no-questions': 'a survey asks at least one question',
16
+ 'survey-question-prompt-required': 'a question says what it asks',
17
+ 'survey-question-kind-unknown': 'a question is single choice, multiple choice, a scale or an allocation',
18
+ 'survey-question-scale-invalid': 'a scale runs from a lower whole number to a higher one',
19
+ 'survey-question-options-too-few': 'a question offers at least two choices',
20
+ 'survey-question-option-blank': 'every choice has a key and a label',
21
+ 'survey-question-option-duplicate': 'two choices of a question have the same key',
22
+ 'survey-question-max-picks-invalid': 'how many may be chosen is between one and the number of choices',
23
+ 'survey-question-total-invalid': 'an allocation adds up to a whole number above zero',
24
+ 'survey-readers-required': 'choose who reads the published result',
25
+ 'survey-figure-unknown': 'the published figure is weighted or unweighted',
26
+ 'survey-closes-at-past': 'the closing time is not later than now',
27
+ 'survey-nobody-asked': 'the audience names nobody working here',
28
+ 'survey-not-asked': 'this survey does not ask you',
29
+ 'survey-answered': 'you have already answered this survey',
30
+ 'survey-answer-missing': 'a question is not answered',
31
+ 'survey-answer-invalid': 'an answer does not fit its question',
32
+ 'survey-not-named': 'only a named survey keeps who answered what',
33
+ 'survey-weight-classes-too-few': 'a weighting has at least two classes',
34
+ 'survey-weight-class-key-invalid': 'every class has its own key',
35
+ 'survey-weight-rate-invalid': 'a rate is a whole number of one or more',
36
+ 'survey-weight-attribute-unknown': 'no such attribute is registered here',
37
+ 'survey-weight-condition-invalid': 'a condition is one of: equals, at least, below',
38
+ 'survey-weight-last-class-open': 'the last class takes everyone left - it has no condition',
39
+ 'survey-weight-class-small': 'a class holds fewer people than the smallest group',
40
+ 'survey-weight-unmatched': 'someone asked fits no class',
41
+ 'survey-basis-date-required': 'a weighted survey names the day attributes are read on',
42
+ 'survey-figure-required': 'a weighted survey chooses the one set of figures it publishes',
43
+ 'survey-not-secret': 'this is not a secret survey',
44
+ 'survey-not-trustee': 'you are not a key holder of this survey',
45
+ 'survey-trustees-invalid': 'name the key holders and how many of them it takes to decrypt - at least one, at most all',
46
+ 'survey-trustees-not-ready': 'the other key holders have not reached this step yet',
47
+ 'survey-trustee-step-done': 'this step is not yours to take now',
48
+ 'survey-trustee-proof-invalid': 'what was sent does not check out',
49
+ 'survey-keying-incomplete': 'the key holders have not finished making the key',
50
+ 'survey-ballot-invalid': 'this ballot does not check out',
51
+ 'survey-ballot-used': 'this ballot token has been used',
52
+ 'survey-ballots-exceed-issued': 'a class holds more ballots than tokens issued to it - the count stops',
53
+ 'survey-decrypt-failed': 'the sums did not open - more key holders are needed',
54
+ 'survey-top-too-few': 'fewer choices are left than the top to be named',
55
+ 'survey-top-tie': 'a tie across the last place of the top - who is in it is not decided by this survey',
56
+ 'survey-top-figures-required': 'choose whether the top places are published with their figures or by rank alone',
57
+ 'survey-carry-unset': 'name the round before and how many choices to take from it',
58
+ 'survey-follows-not-counted': 'the round before is not counted yet',
59
+ 'survey-carry-no-choices': 'the round before has no question with choices first',
60
+ 'survey-succession-exhausted': 'not enough choices are left within the depth a withdrawn choice may be followed to'
61
+ };
62
+ function surveyRefusal(code, params = {}) {
63
+ return new shell_1.Refusal(code, params, ENGLISH[code] ?? code);
64
+ }
65
+ exports.SURVEY_REFUSAL_CODES = Object.keys(ENGLISH);
66
+ //# sourceMappingURL=refusal.js.map
@@ -0,0 +1 @@
1
+ export declare function registerSurveyBallotRoute(router: any): void;
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerSurveyBallotRoute = registerSurveyBallotRoute;
4
+ /*
5
+ * `POST /survey-ballots` - where a secret ballot comes in (design §6-4). It reads no sign-in and keeps no request body in
6
+ * a log; the browser sends it without cookies. A refusal answers with its code - the screen says it in the reader's
7
+ * language.
8
+ */
9
+ const shell_1 = require("@things-factory/shell");
10
+ const survey_1 = require("./survey");
11
+ const survey_secret_1 = require("./survey-secret");
12
+ function registerSurveyBallotRoute(router) {
13
+ router.post('/survey-ballots', async (context) => {
14
+ const domain = context.state.domain;
15
+ if (!domain) {
16
+ context.status = 404;
17
+ context.body = { code: 'survey-unknown' };
18
+ return;
19
+ }
20
+ try {
21
+ const receipt = await (0, shell_1.getRepository)(survey_1.Survey).manager.transaction(tx => (0, survey_secret_1.acceptBallot)(tx, domain, context.request.body));
22
+ context.body = { receipt };
23
+ }
24
+ catch (error) {
25
+ context.status = error?.code ? 422 : 500;
26
+ context.body = { code: error?.code ?? 'survey-ballot-invalid' };
27
+ }
28
+ });
29
+ }
30
+ //# sourceMappingURL=ballot-route.js.map
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /*
4
+ * A sealed ballot's proofs checked off the server's main thread (design §6) - seconds of arithmetic per ballot would
5
+ * otherwise stop every other request while it runs.
6
+ */
7
+ const worker_threads_1 = require("worker_threads");
8
+ const ballot_js_1 = require("@things-factory/survey/dist-shared/ballot.js");
9
+ const group_js_1 = require("@things-factory/survey/dist-shared/group.js");
10
+ const { h, questions, sealed, context } = worker_threads_1.workerData;
11
+ let problem = null;
12
+ try {
13
+ problem = (0, ballot_js_1.openedCells)((0, group_js_1.fromHex)(h), questions, sealed, context).problem ?? null;
14
+ }
15
+ catch {
16
+ problem = 'ballot-shape';
17
+ }
18
+ worker_threads_1.parentPort.postMessage({ problem });
19
+ //# sourceMappingURL=ballot-worker.js.map
@@ -0,0 +1,10 @@
1
+ import { Survey } from './survey';
2
+ import { SurveyAnswer } from './survey-answer';
3
+ import { SurveyQuestion } from './survey-question';
4
+ import { SurveyRespondent } from './survey-respondent';
5
+ import { SurveyBallot } from './survey-ballot';
6
+ import { SurveyClassKey } from './survey-class-key';
7
+ import { SurveyResolver, SurveySecretResolver } from './survey-resolver';
8
+ import { SurveyTrustee } from './survey-trustee';
9
+ export declare const entities: (typeof Survey | typeof SurveyQuestion | typeof SurveyRespondent | typeof SurveyAnswer | typeof SurveyBallot | typeof SurveyClassKey | typeof SurveyTrustee)[];
10
+ export declare const resolvers: (typeof SurveyResolver | typeof SurveySecretResolver)[];
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolvers = exports.entities = void 0;
4
+ const survey_1 = require("./survey");
5
+ const survey_answer_1 = require("./survey-answer");
6
+ const survey_question_1 = require("./survey-question");
7
+ const survey_respondent_1 = require("./survey-respondent");
8
+ const survey_ballot_1 = require("./survey-ballot");
9
+ const survey_class_key_1 = require("./survey-class-key");
10
+ const survey_resolver_1 = require("./survey-resolver");
11
+ const survey_trustee_1 = require("./survey-trustee");
12
+ exports.entities = [survey_1.Survey, survey_question_1.SurveyQuestion, survey_respondent_1.SurveyRespondent, survey_answer_1.SurveyAnswer, survey_trustee_1.SurveyTrustee, survey_class_key_1.SurveyClassKey, survey_ballot_1.SurveyBallot];
13
+ exports.resolvers = [survey_resolver_1.SurveyResolver, survey_resolver_1.SurveySecretResolver];
14
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,23 @@
1
+ import { User } from '@things-factory/auth-base';
2
+ import { Domain } from '@things-factory/shell';
3
+ import { Survey } from './survey';
4
+ import { SurveyQuestion } from './survey-question';
5
+ import { SurveyRespondent } from './survey-respondent';
6
+ export declare class SurveyAnswer {
7
+ readonly id: string;
8
+ domain?: Domain;
9
+ domainId?: string;
10
+ survey?: Survey;
11
+ surveyId?: string;
12
+ respondent?: SurveyRespondent;
13
+ respondentId?: string;
14
+ question?: SurveyQuestion;
15
+ questionId?: string;
16
+ value: any;
17
+ createdAt?: Date;
18
+ updatedAt?: Date;
19
+ creator?: User;
20
+ creatorId?: string;
21
+ updater?: User;
22
+ updaterId?: string;
23
+ }
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SurveyAnswer = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const typeorm_1 = require("typeorm");
6
+ const type_graphql_1 = require("type-graphql");
7
+ const auth_base_1 = require("@things-factory/auth-base");
8
+ const shell_1 = require("@things-factory/shell");
9
+ const survey_1 = require("./survey");
10
+ const survey_question_1 = require("./survey-question");
11
+ const survey_respondent_1 = require("./survey-respondent");
12
+ /*
13
+ * A named answer to one question (design §2-4) - the named level keeps who answered what. Given once, not changed - as
14
+ * a proposal's vote (ADR-0197 decision 3). A secret survey keeps no row here.
15
+ */
16
+ let SurveyAnswer = class SurveyAnswer {
17
+ };
18
+ exports.SurveyAnswer = SurveyAnswer;
19
+ tslib_1.__decorate([
20
+ (0, typeorm_1.PrimaryGeneratedColumn)('uuid'),
21
+ (0, type_graphql_1.Field)(type => type_graphql_1.ID, { description: 'Unique identifier' }),
22
+ tslib_1.__metadata("design:type", String)
23
+ ], SurveyAnswer.prototype, "id", void 0);
24
+ tslib_1.__decorate([
25
+ (0, typeorm_1.ManyToOne)(type => shell_1.Domain),
26
+ (0, type_graphql_1.Field)(type => shell_1.Domain, { nullable: true, description: 'The domain' }),
27
+ tslib_1.__metadata("design:type", shell_1.Domain)
28
+ ], SurveyAnswer.prototype, "domain", void 0);
29
+ tslib_1.__decorate([
30
+ (0, typeorm_1.RelationId)((row) => row.domain),
31
+ tslib_1.__metadata("design:type", String)
32
+ ], SurveyAnswer.prototype, "domainId", void 0);
33
+ tslib_1.__decorate([
34
+ (0, typeorm_1.ManyToOne)(type => survey_1.Survey, { onDelete: 'CASCADE' }),
35
+ tslib_1.__metadata("design:type", survey_1.Survey)
36
+ ], SurveyAnswer.prototype, "survey", void 0);
37
+ tslib_1.__decorate([
38
+ (0, typeorm_1.RelationId)((row) => row.survey),
39
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The survey' }),
40
+ tslib_1.__metadata("design:type", String)
41
+ ], SurveyAnswer.prototype, "surveyId", void 0);
42
+ tslib_1.__decorate([
43
+ (0, typeorm_1.ManyToOne)(type => survey_respondent_1.SurveyRespondent, { onDelete: 'CASCADE' }),
44
+ tslib_1.__metadata("design:type", survey_respondent_1.SurveyRespondent)
45
+ ], SurveyAnswer.prototype, "respondent", void 0);
46
+ tslib_1.__decorate([
47
+ (0, typeorm_1.RelationId)((row) => row.respondent),
48
+ (0, type_graphql_1.Field)({ nullable: true, description: 'Who answered' }),
49
+ tslib_1.__metadata("design:type", String)
50
+ ], SurveyAnswer.prototype, "respondentId", void 0);
51
+ tslib_1.__decorate([
52
+ (0, typeorm_1.ManyToOne)(type => survey_question_1.SurveyQuestion, { onDelete: 'CASCADE' }),
53
+ tslib_1.__metadata("design:type", survey_question_1.SurveyQuestion)
54
+ ], SurveyAnswer.prototype, "question", void 0);
55
+ tslib_1.__decorate([
56
+ (0, typeorm_1.RelationId)((row) => row.question),
57
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The question' }),
58
+ tslib_1.__metadata("design:type", String)
59
+ ], SurveyAnswer.prototype, "questionId", void 0);
60
+ tslib_1.__decorate([
61
+ (0, typeorm_1.Column)('simple-json'),
62
+ (0, type_graphql_1.Field)(type => shell_1.ScalarObject, { description: 'The answer - { pick }, { picks }, { value } or { shares }' }),
63
+ tslib_1.__metadata("design:type", Object)
64
+ ], SurveyAnswer.prototype, "value", void 0);
65
+ tslib_1.__decorate([
66
+ (0, typeorm_1.CreateDateColumn)(),
67
+ (0, type_graphql_1.Field)({ nullable: true, description: 'When it was given' }),
68
+ tslib_1.__metadata("design:type", Date)
69
+ ], SurveyAnswer.prototype, "createdAt", void 0);
70
+ tslib_1.__decorate([
71
+ (0, typeorm_1.UpdateDateColumn)(),
72
+ (0, type_graphql_1.Field)({ nullable: true, description: 'When it was last changed' }),
73
+ tslib_1.__metadata("design:type", Date)
74
+ ], SurveyAnswer.prototype, "updatedAt", void 0);
75
+ tslib_1.__decorate([
76
+ (0, typeorm_1.ManyToOne)(type => auth_base_1.User, { nullable: true }),
77
+ (0, type_graphql_1.Field)(type => auth_base_1.User, { nullable: true, description: 'Who gave it' }),
78
+ tslib_1.__metadata("design:type", auth_base_1.User)
79
+ ], SurveyAnswer.prototype, "creator", void 0);
80
+ tslib_1.__decorate([
81
+ (0, typeorm_1.RelationId)((row) => row.creator),
82
+ tslib_1.__metadata("design:type", String)
83
+ ], SurveyAnswer.prototype, "creatorId", void 0);
84
+ tslib_1.__decorate([
85
+ (0, typeorm_1.ManyToOne)(type => auth_base_1.User, { nullable: true }),
86
+ (0, type_graphql_1.Field)(type => auth_base_1.User, { nullable: true, description: 'Who changed it last' }),
87
+ tslib_1.__metadata("design:type", auth_base_1.User)
88
+ ], SurveyAnswer.prototype, "updater", void 0);
89
+ tslib_1.__decorate([
90
+ (0, typeorm_1.RelationId)((row) => row.updater),
91
+ tslib_1.__metadata("design:type", String)
92
+ ], SurveyAnswer.prototype, "updaterId", void 0);
93
+ exports.SurveyAnswer = SurveyAnswer = tslib_1.__decorate([
94
+ (0, typeorm_1.Entity)({ name: 'survey_answers' }),
95
+ (0, typeorm_1.Index)('ix_survey_answer_0', (row) => [row.respondent, row.question], { unique: true }),
96
+ (0, typeorm_1.Index)('ix_survey_answer_1', (row) => [row.survey]),
97
+ (0, type_graphql_1.ObjectType)({ description: 'A named answer to one question of a survey' })
98
+ ], SurveyAnswer);
99
+ //# sourceMappingURL=survey-answer.js.map
@@ -0,0 +1,16 @@
1
+ import { EntityManager } from 'typeorm';
2
+ import { Domain } from '@things-factory/shell';
3
+ export interface SurveyAttribute {
4
+ /** The name a weight condition uses - `tenureYears`. */
5
+ name: string;
6
+ /** A translation key for its label. */
7
+ label: string;
8
+ type: 'boolean' | 'number';
9
+ /** Each person's value on the basis day (YYYY-MM-DD). A person with no value matches no condition on it. */
10
+ valuesOn(tx: EntityManager, domain: Domain, userIds: string[], basisDate: string): Promise<Map<string, unknown>>;
11
+ }
12
+ export declare function registerSurveyAttribute(attribute: SurveyAttribute): void;
13
+ export declare const surveyAttributes: () => SurveyAttribute[];
14
+ export declare const surveyAttributeOf: (name: string) => SurveyAttribute;
15
+ /** Full years of service on the basis day, from the employee record's hire day (organization). */
16
+ export declare const TENURE_YEARS: SurveyAttribute;