homecubbie-server 0.1.0
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/LICENSE +75 -0
- package/README.md +241 -0
- package/dist/crypto.js +135 -0
- package/dist/home-network.js +103 -0
- package/dist/household.js +912 -0
- package/dist/http-server.js +604 -0
- package/dist/https-listener.js +92 -0
- package/dist/main.js +11 -0
- package/dist/quiet-warnings.js +34 -0
- package/dist/start.js +104 -0
- package/dist/store.js +400 -0
- package/dist/web-app.js +138 -0
- package/package.json +30 -0
- package/web/(now)/index.html +474 -0
- package/web/(now)/month.html +474 -0
- package/web/+not-found.html +474 -0
- package/web/_expo/.routes.json +3 -0
- package/web/_expo/static/css/global-31a95f46f0d26533c432758949249e15.css +1 -0
- package/web/_expo/static/js/web/entry-0f771d01e242dad2ff9cf31c003ad963.js +2839 -0
- package/web/_expo/static/js/web/worker-d922322f88a7f1ead9d277776b9d9ebb.js +22 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png +0 -0
- package/web/assets/__HomeCubbie/node_modules/expo-sqlite/web/wa-sqlite/wa-sqlite.7ca566fbbc2ec2a172c5aefa63a20f4b.wasm +0 -0
- package/web/assets/assets/fonts/BricolageGrotesque_600SemiBold.e5b5fc505484ff3ca24da73cba67c660.ttf +0 -0
- package/web/assets/assets/images/icon.51a3d296cef4a538e85170017fc2f169.png +0 -0
- package/web/costs/[year].html +474 -0
- package/web/costs/index.html +474 -0
- package/web/favicon.ico +0 -0
- package/web/first-run.html +474 -0
- package/web/form/account/bill/edit/[id].html +474 -0
- package/web/form/account/bill/new.html +474 -0
- package/web/form/account/edit/[id].html +474 -0
- package/web/form/account/new.html +474 -0
- package/web/form/activity/new.html +474 -0
- package/web/form/event/edit/[id].html +474 -0
- package/web/form/event/new.html +474 -0
- package/web/form/note/edit/[id].html +474 -0
- package/web/form/note/new.html +474 -0
- package/web/form/person/edit/[id].html +474 -0
- package/web/form/person/new.html +474 -0
- package/web/form/place/edit/[id].html +474 -0
- package/web/form/place/new.html +474 -0
- package/web/form/policy/correct/[id].html +474 -0
- package/web/form/policy/new.html +474 -0
- package/web/form/policy/renew/[id].html +474 -0
- package/web/form/policy/term/[id].html +474 -0
- package/web/form/schedule/edit/[id].html +474 -0
- package/web/form/schedule/new.html +474 -0
- package/web/form/task/edit/[id].html +474 -0
- package/web/form/task/new.html +474 -0
- package/web/form/thing/edit/[id].html +474 -0
- package/web/form/thing/new.html +474 -0
- package/web/home/about/[category].html +474 -0
- package/web/home/about/index.html +474 -0
- package/web/home/arrange.html +474 -0
- package/web/home/index.html +474 -0
- package/web/home/place/[id].html +474 -0
- package/web/home/thing/[id].html +474 -0
- package/web/homecubbie-web.json +5 -0
- package/web/index.html +474 -0
- package/web/month.html +474 -0
- package/web/records/account/[id].html +474 -0
- package/web/records/accounts.html +474 -0
- package/web/records/document/[id].html +474 -0
- package/web/records/documents.html +474 -0
- package/web/records/events.html +474 -0
- package/web/records/history.html +474 -0
- package/web/records/index.html +474 -0
- package/web/records/people.html +474 -0
- package/web/records/person/[id].html +474 -0
- package/web/records/policies.html +474 -0
- package/web/records/policy/[id].html +474 -0
- package/web/records/supplies.html +474 -0
- package/web/records/year/[year].html +474 -0
- package/web/scan/[id].html +474 -0
- package/web/scan/index.html +474 -0
- package/web/search.html +474 -0
- package/web/settings/app-lock.html +474 -0
- package/web/settings/backup.html +474 -0
- package/web/settings/categories.html +474 -0
- package/web/settings/index.html +474 -0
- package/web/settings/open-source.html +474 -0
- package/web/settings/privacy.html +474 -0
- package/web/settings/property.html +474 -0
- package/web/settings/recently-deleted.html +474 -0
- package/web/settings/reminders.html +474 -0
- package/web/settings/restore.html +474 -0
- package/web/settings/sharing-guide.html +474 -0
- package/web/settings/sharing.html +474 -0
- package/web/settings/start-over.html +474 -0
- package/web/settings/storage.html +474 -0
- package/web/settings/tags.html +474 -0
- package/web/settings/who-uses-this-phone.html +474 -0
- package/web/tasks/[id].html +474 -0
- package/web/tasks/index.html +474 -0
|
@@ -0,0 +1,604 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The household server's HTTP face: `node:http`, nothing else.
|
|
3
|
+
*
|
|
4
|
+
* Anything outside `/api` is the web app (#376, #424): HomeCubbie's web build,
|
|
5
|
+
* from a list read once at start (`web-app.ts`), or this page when the server
|
|
6
|
+
* was started without one. The `/api` routes are of three kinds, checked in
|
|
7
|
+
* this order:
|
|
8
|
+
*
|
|
9
|
+
* 1. **Open:** `GET /api/hello`. It says what this is, whether it has been
|
|
10
|
+
* set up, its public key and the house's database version. Nothing secret.
|
|
11
|
+
* 2. **Door:** `POST /api/claim` and `POST /api/join`. Proven with a key
|
|
12
|
+
* derived from the setup code or from an invite, because the phone has no
|
|
13
|
+
* link key yet.
|
|
14
|
+
* 3. **Phone:** everything else. Proven with that phone's link key, which
|
|
15
|
+
* neither side ever sends.
|
|
16
|
+
*
|
|
17
|
+
* Every proof covers the method, the path, the time, a one-use nonce and the
|
|
18
|
+
* body's hash, and every reply to a known phone carries a proof back, so a
|
|
19
|
+
* phone can tell its own server from another one at the same address. No
|
|
20
|
+
* token, cookie or password crosses the network (`docs/open/sharing-key-scheme.md`).
|
|
21
|
+
*/
|
|
22
|
+
import { createServer } from "node:http";
|
|
23
|
+
import { isIP } from "node:net";
|
|
24
|
+
import { claimKey, claimReplyKey, fromBase64Url, hmac, sameBytes, sha256Hex } from "./crypto.js";
|
|
25
|
+
import { Household, Refusal } from "./household.js";
|
|
26
|
+
import { answerHomeOnly } from "./home-network.js";
|
|
27
|
+
export const BODY_LIMITS = {
|
|
28
|
+
json: 16 * 1024 * 1024,
|
|
29
|
+
/** A 1 MiB piece plus its nonce and tag, with room to spare. */
|
|
30
|
+
piece: 1024 * 1024 + 1024,
|
|
31
|
+
copy: 256 * 1024 * 1024,
|
|
32
|
+
};
|
|
33
|
+
const SECURITY_HEADERS = {
|
|
34
|
+
"Cache-Control": "no-store",
|
|
35
|
+
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
|
|
36
|
+
"Referrer-Policy": "no-referrer",
|
|
37
|
+
"X-Content-Type-Options": "nosniff",
|
|
38
|
+
"X-Frame-Options": "DENY",
|
|
39
|
+
};
|
|
40
|
+
const LANDING_PAGE = `<!doctype html>
|
|
41
|
+
<meta charset="utf-8">
|
|
42
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
43
|
+
<title>HomeCubbie server</title>
|
|
44
|
+
<h1>HomeCubbie server</h1>
|
|
45
|
+
<p>This computer holds a household's HomeCubbie data, encrypted. It can't read it, and it never contacts anyone.</p>
|
|
46
|
+
<p>To connect a phone, open HomeCubbie on it and go to Settings › Sharing.</p>`;
|
|
47
|
+
/**
|
|
48
|
+
* For a browser that reached the server by a name it wasn't given. It repeats
|
|
49
|
+
* nothing from the request, so nothing a link put there is shown back (#424).
|
|
50
|
+
*/
|
|
51
|
+
const REFUSED_HOST_PAGE = `<!doctype html>
|
|
52
|
+
<meta charset="utf-8">
|
|
53
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
54
|
+
<title>HomeCubbie</title>
|
|
55
|
+
<h1>This server doesn't answer to that name</h1>
|
|
56
|
+
<p>A HomeCubbie server answers to its own address, to localhost on its own computer, and to the names it was given in HOMECUBBIE_HOSTS.</p>
|
|
57
|
+
<p>If this is your household's server and you reached it by a name, add the name to HOMECUBBIE_HOSTS where the server runs, and start it again.</p>`;
|
|
58
|
+
/**
|
|
59
|
+
* Sent with every file of the web app (#424). Cross-origin isolation is what
|
|
60
|
+
* the web build's database needs for its worker, as Actual's server sends it
|
|
61
|
+
* for the same reason. The Content-Security-Policy and Cache-Control are added
|
|
62
|
+
* per file.
|
|
63
|
+
*/
|
|
64
|
+
const WEB_HEADERS = {
|
|
65
|
+
"Cross-Origin-Opener-Policy": "same-origin",
|
|
66
|
+
"Cross-Origin-Embedder-Policy": "require-corp",
|
|
67
|
+
"Referrer-Policy": "no-referrer",
|
|
68
|
+
"X-Content-Type-Options": "nosniff",
|
|
69
|
+
"X-Frame-Options": "DENY",
|
|
70
|
+
};
|
|
71
|
+
/** A file named by its hash never changes; anything else may with the next build. */
|
|
72
|
+
const CACHE_HASHED = "public, max-age=31536000, immutable";
|
|
73
|
+
export function createHouseholdServer(household, options = {}) {
|
|
74
|
+
const server = createServer(householdRequestListener(household, options));
|
|
75
|
+
answerHomeOnly(server, options);
|
|
76
|
+
return server;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* What answers every request, over plain http on the phones' port and, given
|
|
80
|
+
* a certificate, over HTTPS for a browser on another computer (#427): the
|
|
81
|
+
* same routes, proofs and Host check on both, so neither is a side door.
|
|
82
|
+
*/
|
|
83
|
+
export function householdRequestListener(household, options = {}) {
|
|
84
|
+
const hostNames = new Set((options.hostNames ?? []).map((name) => name.toLowerCase()));
|
|
85
|
+
const webApp = options.webApp ?? null;
|
|
86
|
+
return (request, response) => {
|
|
87
|
+
if (!/^\/api(?:[/?]|$)/.test(request.url ?? "/")) {
|
|
88
|
+
serveWeb(request, response, webApp, hostNames);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
handle(household, hostNames, request)
|
|
92
|
+
.then((outcome) => send(response, outcome.reply, outcome.replyKey, outcome.nonce))
|
|
93
|
+
.catch((error) => {
|
|
94
|
+
const refusal = error instanceof Refusal ? error : null;
|
|
95
|
+
if (refusal === null)
|
|
96
|
+
console.error("homecubbie-server: unexpected error", error);
|
|
97
|
+
const reply = refusal
|
|
98
|
+
? { status: refusal.status, json: { error: refusal.code, ...refusal.details } }
|
|
99
|
+
: { status: 500, json: { error: "server-error" } };
|
|
100
|
+
const signing = error instanceof SignedRefusal ? error : null;
|
|
101
|
+
send(response, reply, signing?.replyKey ?? null, signing?.nonce ?? null);
|
|
102
|
+
});
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/** A refusal to a phone whose proof checked out, so the refusal can be signed too. */
|
|
106
|
+
class SignedRefusal extends Refusal {
|
|
107
|
+
replyKey;
|
|
108
|
+
nonce;
|
|
109
|
+
constructor(inner, replyKey, nonce) {
|
|
110
|
+
super(inner.code, inner.details);
|
|
111
|
+
this.replyKey = replyKey;
|
|
112
|
+
this.nonce = nonce;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
async function handle(household, hostNames, request) {
|
|
116
|
+
checkHost(request, hostNames);
|
|
117
|
+
const url = new URL(request.url ?? "/", "http://placeholder");
|
|
118
|
+
const method = request.method ?? "GET";
|
|
119
|
+
const path = url.pathname + url.search;
|
|
120
|
+
if (method === "GET" && url.pathname === "/api/hello") {
|
|
121
|
+
return { reply: { status: 200, json: household.hello() }, replyKey: null, nonce: null };
|
|
122
|
+
}
|
|
123
|
+
// Before the body, who is asking: a phone this server knows, or one of the
|
|
124
|
+
// two doors. Anyone who can reach the port could otherwise make it hold a
|
|
125
|
+
// whole upload in memory before it knew (#420).
|
|
126
|
+
const door = method === "POST" && (url.pathname === "/api/claim" || url.pathname === "/api/join");
|
|
127
|
+
if (!door)
|
|
128
|
+
household.requirePhone(request.headers["x-hc-phone"]);
|
|
129
|
+
const body = await readBody(request, bodyLimitFor(method, url.pathname));
|
|
130
|
+
const signed = readSignature(request, method, path, body);
|
|
131
|
+
if (method === "POST" && url.pathname === "/api/claim") {
|
|
132
|
+
const code = household.setupCode();
|
|
133
|
+
if (code === null)
|
|
134
|
+
throw new Refusal("already-set-up");
|
|
135
|
+
if (!proofHolds(claimKey(code), signed)) {
|
|
136
|
+
household.countClaimFailure();
|
|
137
|
+
throw new Refusal("bad-setup-code");
|
|
138
|
+
}
|
|
139
|
+
household.checkFresh(signed.time, signed.nonce);
|
|
140
|
+
const input = parseJson(body);
|
|
141
|
+
const phone = household.claim({
|
|
142
|
+
householdId: requireString(input.householdId),
|
|
143
|
+
phoneId: requireString(input.phoneId),
|
|
144
|
+
phoneKey: decode(input.phoneKey, 32),
|
|
145
|
+
nameBlob: decode(input.nameBlob),
|
|
146
|
+
serverKey: decode(input.serverKey, 32),
|
|
147
|
+
signingKey: decode(input.signingKey, 32),
|
|
148
|
+
// A household moving here starts at its next epoch (#419 package 2),
|
|
149
|
+
// with the move signed by the phone moving it (#442).
|
|
150
|
+
...(input.epoch === undefined ? {} : { epoch: requireInteger(input.epoch) }),
|
|
151
|
+
...(input.rekeyProof === undefined || input.rekeyProof === null ? {} : { rekeyProof: decode(input.rekeyProof, 32) }),
|
|
152
|
+
...(input.statement === undefined
|
|
153
|
+
? {}
|
|
154
|
+
: { signed: { statement: requireStatement(input.statement), signature: decode(input.signature, 64) } }),
|
|
155
|
+
});
|
|
156
|
+
return {
|
|
157
|
+
reply: { status: 200, json: { householdId: household.householdId(), epoch: household.epoch() } },
|
|
158
|
+
replyKey: claimReplyKey(claimKey(code), household.linkKeyFor(phone)),
|
|
159
|
+
nonce: signed.nonce,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
if (method === "POST" && url.pathname === "/api/join") {
|
|
163
|
+
const input = parseJson(body);
|
|
164
|
+
const inviteId = requireString(input.inviteId);
|
|
165
|
+
const verifier = household.inviteVerifier(inviteId);
|
|
166
|
+
if (!proofHolds(verifier, signed)) {
|
|
167
|
+
household.countJoinFailure(inviteId);
|
|
168
|
+
throw new Refusal("bad-proof");
|
|
169
|
+
}
|
|
170
|
+
household.checkFresh(signed.time, signed.nonce);
|
|
171
|
+
const { phone, packet } = household.join({
|
|
172
|
+
inviteId,
|
|
173
|
+
phoneId: requireString(input.phoneId),
|
|
174
|
+
phoneKey: decode(input.phoneKey, 32),
|
|
175
|
+
nameBlob: decode(input.nameBlob),
|
|
176
|
+
signingKey: decode(input.signingKey, 32),
|
|
177
|
+
arrival: decode(input.arrival, 64),
|
|
178
|
+
arrivalOwn: decode(input.arrivalOwn, 64),
|
|
179
|
+
});
|
|
180
|
+
return {
|
|
181
|
+
reply: {
|
|
182
|
+
status: 200,
|
|
183
|
+
json: {
|
|
184
|
+
householdId: household.householdId(),
|
|
185
|
+
epoch: household.epoch(),
|
|
186
|
+
packet: packet.toString("base64url"),
|
|
187
|
+
// The proof of the change to this epoch, for a phone joining again
|
|
188
|
+
// that holds the key before to check (#419 package 2, decision 364).
|
|
189
|
+
rekeyProof: household.currentRekeyProof(),
|
|
190
|
+
// Every signed key change, and every phone with how it came in, for
|
|
191
|
+
// a phone joining again to check the key from what it held (#442).
|
|
192
|
+
keyChanges: household.keyChanges(),
|
|
193
|
+
phones: household.phones(),
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
replyKey: household.linkKeyFor(phone),
|
|
197
|
+
nonce: signed.nonce,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
// Everything else is a joined phone's.
|
|
201
|
+
const phone = household.requirePhone(request.headers["x-hc-phone"]);
|
|
202
|
+
const key = household.linkKeyFor(phone);
|
|
203
|
+
if (!proofHolds(key, signed))
|
|
204
|
+
throw new Refusal("bad-proof");
|
|
205
|
+
try {
|
|
206
|
+
household.checkFresh(signed.time, signed.nonce);
|
|
207
|
+
household.requireActive(phone);
|
|
208
|
+
const reply = route(household, phone, method, url, request, body);
|
|
209
|
+
return { reply, replyKey: key, nonce: signed.nonce };
|
|
210
|
+
}
|
|
211
|
+
catch (error) {
|
|
212
|
+
if (error instanceof Refusal)
|
|
213
|
+
throw new SignedRefusal(error, key, signed.nonce);
|
|
214
|
+
throw error;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
function route(household, phone, method, url, request, body) {
|
|
218
|
+
const path = url.pathname;
|
|
219
|
+
const file = /^\/api\/files\/([0-9a-f]{32})(?:\/(\d+))?$/.exec(path);
|
|
220
|
+
if (method === "POST" && path === "/api/sync") {
|
|
221
|
+
const input = parseJson(body);
|
|
222
|
+
if (!Array.isArray(input.batches))
|
|
223
|
+
throw new Refusal("bad-request");
|
|
224
|
+
const batches = input.batches.map((raw) => {
|
|
225
|
+
const item = requireObject(raw);
|
|
226
|
+
return {
|
|
227
|
+
batch: requireInteger(item.batch),
|
|
228
|
+
epoch: requireInteger(item.epoch),
|
|
229
|
+
schemaVersion: requireInteger(item.schemaVersion),
|
|
230
|
+
blob: decode(item.blob),
|
|
231
|
+
};
|
|
232
|
+
});
|
|
233
|
+
return { status: 200, json: household.sync(phone, { since: requireInteger(input.since), batches }) };
|
|
234
|
+
}
|
|
235
|
+
if (method === "GET" && path === "/api/phones")
|
|
236
|
+
return { status: 200, json: { phones: household.phones() } };
|
|
237
|
+
// No route adds a phone except an invite. A route that let any member add a
|
|
238
|
+
// "paper" phone, for a recovery code, let a member plant one the others
|
|
239
|
+
// couldn't see or remove (#420). The recovery code is an invite instead,
|
|
240
|
+
// used through `/api/join` like any other (#419, decision 362).
|
|
241
|
+
if (method === "POST" && path === "/api/phones/name") {
|
|
242
|
+
household.renamePhone(phone, decode(parseJson(body).nameBlob));
|
|
243
|
+
return { status: 200, json: { ok: true } };
|
|
244
|
+
}
|
|
245
|
+
if (method === "POST" && path === "/api/phones/remove") {
|
|
246
|
+
household.removePhone(phone, parseJson(body).phoneId);
|
|
247
|
+
return { status: 200, json: { ok: true } };
|
|
248
|
+
}
|
|
249
|
+
if (method === "POST" && path === "/api/leave") {
|
|
250
|
+
household.removePhone(phone, phone.id);
|
|
251
|
+
return { status: 200, json: { ok: true } };
|
|
252
|
+
}
|
|
253
|
+
if (method === "POST" && path === "/api/invites") {
|
|
254
|
+
const input = parseJson(body);
|
|
255
|
+
household.createInvite(phone, {
|
|
256
|
+
inviteId: requireString(input.inviteId),
|
|
257
|
+
sealedVerifier: decode(input.sealedVerifier),
|
|
258
|
+
packet: decode(input.packet),
|
|
259
|
+
expiresInMs: requireInteger(input.expiresInMs),
|
|
260
|
+
doorKey: decode(input.doorKey, 32),
|
|
261
|
+
doorEpoch: requireInteger(input.doorEpoch),
|
|
262
|
+
vouch: decode(input.vouch, 64),
|
|
263
|
+
});
|
|
264
|
+
return { status: 200, json: { ok: true } };
|
|
265
|
+
}
|
|
266
|
+
if (method === "POST" && path === "/api/recovery") {
|
|
267
|
+
const input = parseJson(body);
|
|
268
|
+
household.createRecovery(phone, {
|
|
269
|
+
recoveryId: requireString(input.recoveryId),
|
|
270
|
+
sealedVerifier: decode(input.sealedVerifier),
|
|
271
|
+
packet: decode(input.packet),
|
|
272
|
+
epoch: requireInteger(input.epoch),
|
|
273
|
+
doorKey: decode(input.doorKey, 32),
|
|
274
|
+
vouch: decode(input.vouch, 64),
|
|
275
|
+
});
|
|
276
|
+
return { status: 200, json: { ok: true } };
|
|
277
|
+
}
|
|
278
|
+
if (method === "GET" && path === "/api/recovery")
|
|
279
|
+
return { status: 200, json: household.recoveryStatus() };
|
|
280
|
+
if (method === "PUT" && path === "/api/copy") {
|
|
281
|
+
// In the query, which the request proof covers, not in headers, which it
|
|
282
|
+
// doesn't: a raised schema version would lock every phone out (#420), and
|
|
283
|
+
// a raised floor would lock out the phones behind it (#452).
|
|
284
|
+
const floor = url.searchParams.get("floor");
|
|
285
|
+
const copyId = household.uploadCopy(phone, {
|
|
286
|
+
epoch: requireInteger(Number(url.searchParams.get("epoch"))),
|
|
287
|
+
schemaVersion: requireInteger(Number(url.searchParams.get("schema"))),
|
|
288
|
+
throughSeq: requireInteger(Number(url.searchParams.get("through"))),
|
|
289
|
+
bytes: body,
|
|
290
|
+
...(floor === null ? {} : { schemaFloor: requireInteger(Number(floor)) }),
|
|
291
|
+
});
|
|
292
|
+
return { status: 200, json: { copyId } };
|
|
293
|
+
}
|
|
294
|
+
if (method === "POST" && path === "/api/copy/activate") {
|
|
295
|
+
household.activateCopy(parseJson(body).copyId);
|
|
296
|
+
return { status: 200, json: { ok: true } };
|
|
297
|
+
}
|
|
298
|
+
if (method === "GET" && path === "/api/copy") {
|
|
299
|
+
const { copy, bytes } = household.activeCopyBytes();
|
|
300
|
+
return { status: 200, bytes, headers: { ...downloadHeaders(), "X-HC-Copy": JSON.stringify(copy) } };
|
|
301
|
+
}
|
|
302
|
+
if (method === "POST" && path === "/api/key") {
|
|
303
|
+
const input = parseJson(body);
|
|
304
|
+
const changed = household.changeKey(phone, {
|
|
305
|
+
epoch: requireInteger(input.epoch),
|
|
306
|
+
copyId: input.copyId,
|
|
307
|
+
reset: input.reset === true,
|
|
308
|
+
rekeyProof: decode(input.rekeyProof, 32),
|
|
309
|
+
statement: requireStatement(input.statement),
|
|
310
|
+
signature: decode(input.signature, 64),
|
|
311
|
+
remove: input.remove,
|
|
312
|
+
wraps: parseWraps(input.wraps),
|
|
313
|
+
});
|
|
314
|
+
return { status: 200, json: changed };
|
|
315
|
+
}
|
|
316
|
+
if (method === "POST" && path === "/api/copy/loaded") {
|
|
317
|
+
household.copyLoaded(phone, parseJson(body).copyId);
|
|
318
|
+
return { status: 200, json: { ok: true } };
|
|
319
|
+
}
|
|
320
|
+
if (method === "GET" && url.pathname === "/api/key") {
|
|
321
|
+
const asked = url.searchParams.get("epoch");
|
|
322
|
+
return { status: 200, json: household.wrapFor(phone, asked === null ? undefined : requireInteger(Number(asked))) };
|
|
323
|
+
}
|
|
324
|
+
if (file !== null) {
|
|
325
|
+
const fileId = file[1];
|
|
326
|
+
const piece = file[2] === undefined ? null : Number(file[2]);
|
|
327
|
+
if (piece !== null && method === "PUT") {
|
|
328
|
+
household.putPiece(fileId, piece, body);
|
|
329
|
+
return { status: 200, json: { ok: true } };
|
|
330
|
+
}
|
|
331
|
+
if (piece !== null && method === "GET")
|
|
332
|
+
return { status: 200, bytes: household.getPiece(fileId, piece), headers: downloadHeaders() };
|
|
333
|
+
if (piece === null && method === "GET")
|
|
334
|
+
return { status: 200, json: household.fileStatus(fileId) };
|
|
335
|
+
if (piece === null && method === "POST") {
|
|
336
|
+
household.completeFile(fileId, parseJson(body).pieces);
|
|
337
|
+
return { status: 200, json: { ok: true } };
|
|
338
|
+
}
|
|
339
|
+
if (piece === null && method === "DELETE") {
|
|
340
|
+
household.deleteFile(fileId);
|
|
341
|
+
return { status: 200, json: { ok: true } };
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
throw new Refusal("not-found");
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* The server answers only to an IP address, `localhost`, or a name it was
|
|
348
|
+
* given. That stops a website the household happens to visit from pointing
|
|
349
|
+
* its own domain at this server's address and talking to it through the
|
|
350
|
+
* browser (DNS rebinding).
|
|
351
|
+
*/
|
|
352
|
+
function checkHost(request, hostNames) {
|
|
353
|
+
const name = hostName(request);
|
|
354
|
+
if (name === null || !hostAllowed(name, hostNames))
|
|
355
|
+
throw new Refusal("host-not-allowed");
|
|
356
|
+
}
|
|
357
|
+
/** The name in the request's Host, lower-cased, without its port or an IPv6 address's brackets. */
|
|
358
|
+
function hostName(request) {
|
|
359
|
+
const host = request.headers.host;
|
|
360
|
+
if (host === undefined)
|
|
361
|
+
return null;
|
|
362
|
+
const name = host.startsWith("[") ? host.slice(1, host.indexOf("]")) : host.replace(/:\d+$/, "");
|
|
363
|
+
return name.toLowerCase();
|
|
364
|
+
}
|
|
365
|
+
function hostAllowed(name, hostNames) {
|
|
366
|
+
return isIP(name) !== 0 || name === "localhost" || hostNames.has(name);
|
|
367
|
+
}
|
|
368
|
+
/** `127.0.0.1` and `::1`: this computer, by a number rather than by `localhost`. */
|
|
369
|
+
function isLoopbackAddress(name) {
|
|
370
|
+
return (isIP(name) === 4 && name.startsWith("127.")) || name === "::1" || name === "0:0:0:0:0:0:0:1";
|
|
371
|
+
}
|
|
372
|
+
// ── the web app ────────────────────────────────────────────────────────
|
|
373
|
+
/**
|
|
374
|
+
* Everything outside `/api`: the web app's files, read once at start, or the
|
|
375
|
+
* landing page when the server has none (#424). Only `GET` and `HEAD`; no
|
|
376
|
+
* request is ever turned into a path on disk (`web-app.ts`).
|
|
377
|
+
*/
|
|
378
|
+
function serveWeb(request, response, web, hostNames) {
|
|
379
|
+
const name = hostName(request);
|
|
380
|
+
if (name === null || !hostAllowed(name, hostNames)) {
|
|
381
|
+
sendPlain(response, 421, REFUSED_HOST_PAGE, "text/html; charset=utf-8");
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
const method = request.method ?? "GET";
|
|
385
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
386
|
+
sendPlain(response, 405, "This server's pages can only be read.", "text/plain; charset=utf-8", { Allow: "GET, HEAD" });
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
const target = request.url ?? "/";
|
|
390
|
+
const pathname = webPathname(target);
|
|
391
|
+
if (pathname === null) {
|
|
392
|
+
sendPlain(response, 400, "That isn't an address this server has.", "text/plain; charset=utf-8");
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
if (web === null) {
|
|
396
|
+
if (pathname === "/")
|
|
397
|
+
sendPlain(response, 200, LANDING_PAGE, "text/html; charset=utf-8");
|
|
398
|
+
else
|
|
399
|
+
sendPlain(response, 404, "Not found.", "text/plain; charset=utf-8");
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
// `localhost`, `127.0.0.1` and an https name are three sites to a browser,
|
|
403
|
+
// and each would need its own join. One computer is one: `localhost`.
|
|
404
|
+
if (isLoopbackAddress(name)) {
|
|
405
|
+
const port = /:(\d+)$/.exec(request.headers.host ?? "")?.[1];
|
|
406
|
+
const scheme = request.socket.encrypted === true ? "https:" : "http:";
|
|
407
|
+
sendPlain(response, 307, "", "text/plain; charset=utf-8", { Location: `${scheme}//localhost${port === undefined ? "" : `:${port}`}${target}` });
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
const file = web.find(pathname);
|
|
411
|
+
if (file === null) {
|
|
412
|
+
if (web.notFound === null)
|
|
413
|
+
sendPlain(response, 404, "Not found.", "text/plain; charset=utf-8");
|
|
414
|
+
else
|
|
415
|
+
sendWebFile(response, 404, web, web.notFound, method);
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
sendWebFile(response, 200, web, file, method);
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* The path a browser asked for, decoded, or null when it can't be one of the
|
|
422
|
+
* web app's: a `.` or `..` part, a backslash, a NUL, or bad escaping. Those
|
|
423
|
+
* would find nothing in the list anyway; they are refused rather than looked up.
|
|
424
|
+
*/
|
|
425
|
+
function webPathname(target) {
|
|
426
|
+
const raw = target.split("?")[0] ?? "";
|
|
427
|
+
if (!raw.startsWith("/"))
|
|
428
|
+
return null;
|
|
429
|
+
let decoded;
|
|
430
|
+
try {
|
|
431
|
+
decoded = decodeURIComponent(raw);
|
|
432
|
+
}
|
|
433
|
+
catch {
|
|
434
|
+
return null;
|
|
435
|
+
}
|
|
436
|
+
if (decoded.includes("\\") || decoded.includes("\0"))
|
|
437
|
+
return null;
|
|
438
|
+
if (decoded.split("/").some((part) => part === "." || part === ".."))
|
|
439
|
+
return null;
|
|
440
|
+
return decoded;
|
|
441
|
+
}
|
|
442
|
+
function sendWebFile(response, status, web, file, method) {
|
|
443
|
+
response.writeHead(status, {
|
|
444
|
+
...WEB_HEADERS,
|
|
445
|
+
"Content-Security-Policy": web.contentSecurityPolicy,
|
|
446
|
+
"Cache-Control": file.hashed && status === 200 ? CACHE_HASHED : "no-store",
|
|
447
|
+
"Content-Type": file.type,
|
|
448
|
+
"Content-Length": String(file.bytes.length),
|
|
449
|
+
});
|
|
450
|
+
response.end(method === "HEAD" ? undefined : file.bytes);
|
|
451
|
+
}
|
|
452
|
+
function sendPlain(response, status, text, type, extra = {}) {
|
|
453
|
+
const body = Buffer.from(text);
|
|
454
|
+
response.writeHead(status, { ...SECURITY_HEADERS, "Content-Type": type, ...extra, "Content-Length": String(body.length) });
|
|
455
|
+
response.end(body);
|
|
456
|
+
}
|
|
457
|
+
function bodyLimitFor(method, path) {
|
|
458
|
+
if (method === "PUT" && path === "/api/copy")
|
|
459
|
+
return BODY_LIMITS.copy;
|
|
460
|
+
if (method === "PUT" && path.startsWith("/api/files/"))
|
|
461
|
+
return BODY_LIMITS.piece;
|
|
462
|
+
return BODY_LIMITS.json;
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* How many request-body bytes the server holds at once, across every request:
|
|
466
|
+
* one full copy and a little more. Uploads beyond it wait for the phone to
|
|
467
|
+
* try again, so no number of requests can run it out of memory (#420).
|
|
468
|
+
*/
|
|
469
|
+
export const BODY_BYTES_IN_FLIGHT = BODY_LIMITS.copy + 16 * BODY_LIMITS.piece;
|
|
470
|
+
let bodyBytesHeld = 0;
|
|
471
|
+
function readBody(request, limit) {
|
|
472
|
+
return new Promise((resolve, reject) => {
|
|
473
|
+
const declared = Number(request.headers["content-length"] ?? "0");
|
|
474
|
+
if (declared > limit) {
|
|
475
|
+
request.resume();
|
|
476
|
+
reject(new Refusal("too-large"));
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
const chunks = [];
|
|
480
|
+
let size = 0;
|
|
481
|
+
const release = () => {
|
|
482
|
+
bodyBytesHeld -= size;
|
|
483
|
+
size = 0;
|
|
484
|
+
};
|
|
485
|
+
request.on("data", (chunk) => {
|
|
486
|
+
size += chunk.length;
|
|
487
|
+
bodyBytesHeld += chunk.length;
|
|
488
|
+
if (size > limit || bodyBytesHeld > BODY_BYTES_IN_FLIGHT) {
|
|
489
|
+
const busy = size <= limit;
|
|
490
|
+
release();
|
|
491
|
+
request.destroy();
|
|
492
|
+
reject(new Refusal("too-large", busy ? { reason: "busy" } : {}));
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
chunks.push(chunk);
|
|
496
|
+
});
|
|
497
|
+
request.on("end", () => {
|
|
498
|
+
const whole = Buffer.concat(chunks);
|
|
499
|
+
release();
|
|
500
|
+
resolve(whole);
|
|
501
|
+
});
|
|
502
|
+
request.on("error", (error) => {
|
|
503
|
+
release();
|
|
504
|
+
reject(error);
|
|
505
|
+
});
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
function readSignature(request, method, path, body) {
|
|
509
|
+
const time = Number(request.headers["x-hc-time"]);
|
|
510
|
+
const nonce = request.headers["x-hc-nonce"];
|
|
511
|
+
const proof = request.headers["x-hc-proof"];
|
|
512
|
+
if (typeof nonce !== "string" || typeof proof !== "string" || !Number.isFinite(time))
|
|
513
|
+
throw new Refusal("bad-proof");
|
|
514
|
+
try {
|
|
515
|
+
fromBase64Url(nonce, 16);
|
|
516
|
+
return { method, path, time, nonce, proof: fromBase64Url(proof, 32), body };
|
|
517
|
+
}
|
|
518
|
+
catch {
|
|
519
|
+
throw new Refusal("bad-proof");
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
/** The string every request proof is computed over. The phone builds the same one. */
|
|
523
|
+
export function requestProofInput(method, path, time, nonce, body) {
|
|
524
|
+
return `${method}\n${path}\n${time}\n${nonce}\n${sha256Hex(body)}`;
|
|
525
|
+
}
|
|
526
|
+
/** The string every reply proof is computed over. */
|
|
527
|
+
/**
|
|
528
|
+
* The string every reply proof covers. `copy` is the `X-HC-Copy` header a
|
|
529
|
+
* copy download carries: how far through the changes the copy runs, which a
|
|
530
|
+
* phone acts on and so must not be able to be changed on the way (#420).
|
|
531
|
+
*/
|
|
532
|
+
export function replyProofInput(nonce, status, body, copy = null) {
|
|
533
|
+
return `reply\n${nonce}\n${status}\n${sha256Hex(body)}` + (copy === null ? "" : `\ncopy ${copy}`);
|
|
534
|
+
}
|
|
535
|
+
function proofHolds(key, signed) {
|
|
536
|
+
const expected = hmac(key, requestProofInput(signed.method, signed.path, signed.time, signed.nonce, signed.body));
|
|
537
|
+
return sameBytes(expected, signed.proof);
|
|
538
|
+
}
|
|
539
|
+
function send(response, reply, replyKey, nonce) {
|
|
540
|
+
const body = reply.bytes ?? Buffer.from(JSON.stringify(reply.json ?? {}));
|
|
541
|
+
const headers = {
|
|
542
|
+
...SECURITY_HEADERS,
|
|
543
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
544
|
+
...reply.headers,
|
|
545
|
+
"Content-Length": String(body.length),
|
|
546
|
+
};
|
|
547
|
+
if (replyKey !== null && nonce !== null) {
|
|
548
|
+
const copy = reply.headers?.["X-HC-Copy"] ?? null;
|
|
549
|
+
headers["X-HC-Reply-Proof"] = hmac(replyKey, replyProofInput(nonce, reply.status, body, copy)).toString("base64url");
|
|
550
|
+
}
|
|
551
|
+
response.writeHead(reply.status, headers);
|
|
552
|
+
response.end(body);
|
|
553
|
+
}
|
|
554
|
+
/** Files and copies go out as downloads, never as something a browser would show or run. */
|
|
555
|
+
function downloadHeaders() {
|
|
556
|
+
return { "Content-Type": "application/octet-stream", "Content-Disposition": "attachment" };
|
|
557
|
+
}
|
|
558
|
+
function parseJson(body) {
|
|
559
|
+
try {
|
|
560
|
+
return requireObject(JSON.parse(body.toString("utf8")));
|
|
561
|
+
}
|
|
562
|
+
catch (error) {
|
|
563
|
+
if (error instanceof Refusal)
|
|
564
|
+
throw error;
|
|
565
|
+
throw new Refusal("bad-request");
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
function requireObject(value) {
|
|
569
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
570
|
+
throw new Refusal("bad-request");
|
|
571
|
+
return value;
|
|
572
|
+
}
|
|
573
|
+
function requireString(value) {
|
|
574
|
+
if (typeof value !== "string")
|
|
575
|
+
throw new Refusal("bad-request");
|
|
576
|
+
return value;
|
|
577
|
+
}
|
|
578
|
+
function requireInteger(value) {
|
|
579
|
+
if (typeof value !== "number" || !Number.isInteger(value))
|
|
580
|
+
throw new Refusal("bad-request");
|
|
581
|
+
return value;
|
|
582
|
+
}
|
|
583
|
+
/** A signed key change's statement (#442): text, kept as it came, so its signature still holds when it is served. */
|
|
584
|
+
function requireStatement(value) {
|
|
585
|
+
if (typeof value !== "string" || value.length === 0 || value.length > 64 * 1024)
|
|
586
|
+
throw new Refusal("bad-request");
|
|
587
|
+
return value;
|
|
588
|
+
}
|
|
589
|
+
function decode(value, bytes) {
|
|
590
|
+
try {
|
|
591
|
+
return fromBase64Url(value, bytes);
|
|
592
|
+
}
|
|
593
|
+
catch {
|
|
594
|
+
throw new Refusal("bad-request");
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
function parseWraps(value) {
|
|
598
|
+
if (!Array.isArray(value))
|
|
599
|
+
throw new Refusal("bad-request");
|
|
600
|
+
return value.map((raw) => {
|
|
601
|
+
const item = requireObject(raw);
|
|
602
|
+
return { phoneId: requireString(item.phoneId), ephemeralKey: decode(item.ephemeralKey, 32), blob: decode(item.blob) };
|
|
603
|
+
});
|
|
604
|
+
}
|