]> Git — Sourcephile - sourcephile-nix.git/blob - machines/losurdo/nginx/sourcephile.fr/cryptpad.nix
cryptpad: add service
[sourcephile-nix.git] / machines / losurdo / nginx / sourcephile.fr / cryptpad.nix
1 { domain, ... }:
2 { pkgs, lib, config, machineName, ... }:
3 let
4 inherit (config) networking;
5 inherit (config.services) nginx;
6 srv = "cryptpad";
7
8 # CryptPad serves static assets over these two domains.
9 # `main_domain` is what users will enter in their address bar.
10 # Privileged computation such as key management is handled in this scope
11 # UI content is loaded via the `sandbox_domain`.
12 # "Content Security Policy" headers prevent content loaded via the sandbox
13 # from accessing privileged information.
14 # These variables must be different to take advantage of CryptPad's sandboxing techniques.
15 # In the event of an XSS vulnerability in CryptPad's front-end code
16 # this will limit the amount of information accessible to attackers.
17 main_domain = "${srv}.${domain}";
18 sandbox_domain = "${srv}-sandbox.${domain}";
19
20 # CryptPad's dynamic content (websocket traffic and encrypted blobs)
21 # can be served over separate domains. Using dedicated domains (or subdomains)
22 # for these purposes allows you to move them to a separate machine at a later date
23 # if you find that a single machine cannot handle all of your users.
24 # If you don't use dedicated domains, this can be the same as $main_domain
25 # If you do, they'll be added as exceptions to any rules which block connections to remote domains.
26 api_domain = "${srv}-api.${domain}";
27 files_domain = "${srv}-files.${domain}";
28
29 # CSS can be dynamically set inline, loaded from the same domain, or from $main_domain
30 styleSrc = "'unsafe-inline' 'self' ${main_domain}";
31
32 # connect-src restricts URLs which can be loaded using script interfaces
33 connectSrc = "'self' https://${main_domain} ${main_domain} https://${api_domain} blob: wss://${api_domain} ${api_domain} ${files_domain}";
34
35 # fonts can be loaded from data-URLs or the main domain
36 fontSrc = "'self' data: ${main_domain}";
37
38 # images can be loaded from anywhere, though we'd like to deprecate this as it allows the use of images for tracking
39 imgSrc = "'self' data: * blob: ${main_domain}";
40
41 # frame-src specifies valid sources for nested browsing contexts.
42 # this prevents loading any iframes from anywhere other than the sandbox domain
43 frameSrc = "'self' ${sandbox_domain} blob:";
44
45 # specifies valid sources for loading media using video or audio
46 mediaSrc = "'self' data: * blob: ${main_domain}";
47
48 # defines valid sources for webworkers and nested browser contexts
49 # deprecated in favour of worker-src and frame-src
50 childSrc = "https://${main_domain}";
51
52 # specifies valid sources for Worker, SharedWorker, or ServiceWorker scripts.
53 # supercedes child-src but is unfortunately not yet universally supported.
54 workerSrc = "https://${main_domain}";
55
56 # add_header clear all parent add_header
57 # and thus must be repeated in sub-blocks
58 add_headers = ''
59 ${nginx.configs.https_add_headers}
60 add_header Access-Control-Allow-Origin "*";
61 add_header Cache-Control $cacheControl;
62 add_header X-Frame-Options "";
63 add_header Content-Security-Policy "default-src 'none'; child-src ${childSrc}; worker-src ${workerSrc}; media-src ${mediaSrc}; style-src ${styleSrc}; script-src $scriptSrc; connect-src ${connectSrc}; font-src ${fontSrc}; img-src ${imgSrc}; frame-src ${frameSrc};";
64 '';
65 cryptpad_root = "/var/lib/nginx/cryptpad";
66 in
67 {
68 services.cryptpad = {
69 enable = true;
70 # DOC: https://github.com/xwiki-labs/cryptpad/blob/master/config/config.example.js
71 configFile = pkgs.writeText "config.js" ''
72 module.exports = {
73 httpUnsafeOrigin: 'https://${main_domain}/',
74 httpSafeOrigin: "https://${sandbox_domain}/",
75 httpAddress: '::1',
76 httpPort: 3000,
77 httpSafePort: 3001,
78 maxWorkers: 1,
79
80 /* =====================
81 * Admin
82 * ===================== */
83 adminKeys: [
84 "https://cryptpad.sourcephile.fr/user/#/1/julm/s9y2aE8C5INMZSrR2yQbWBNcGpB8nSLZGFVhGHE8Nn8=",
85 ],
86 // supportMailboxPublicKey: "",
87
88 removeDonateButton: true,
89 disableAnonymousStore: true,
90 disableCrowdfundingMessages: true,
91 adminEmail: 'root+cryptpad@sourcephile.fr',
92 blockDailyCheck: true,
93 defaultStorageLimit: 1024 * 1024 * 1024,
94
95 /* =====================
96 * STORAGE
97 * ===================== */
98 //inactiveTime: 90, // days
99 //archiveRetentionTime: 15,
100 maxUploadSize: 256 * 1024 * 1024,
101
102 /*
103 customLimits: {
104 "https://my.awesome.website/user/#/1/cryptpad-user1/YZgXQxKR0Rcb6r6CmxHPdAGLVludrAF2lEnkbx1vVOo=": {
105 limit: 20 * 1024 * 1024 * 1024,
106 plan: 'insider',
107 note: 'storage space donated by my.awesome.website'
108 },
109 "https://my.awesome.website/user/#/1/cryptpad-user2/GdflkgdlkjeworijfkldfsdflkjeEAsdlEnkbx1vVOo=": {
110 limit: 10 * 1024 * 1024 * 1024,
111 plan: 'insider',
112 note: 'storage space donated by my.awesome.website'
113 }
114 },
115 */
116
117 //premiumUploadSize: 100 * 1024 * 1024,
118
119 /* =====================
120 * DATABASE VOLUMES
121 * ===================== */
122 filePath: './datastore/',
123 archivePath: './data/archive',
124 pinPath: './data/pins',
125 taskPath: './data/tasks',
126 blockPath: './block',
127 blobPath: './blob',
128 blobStagingPath: './data/blobstage',
129 logPath: './data/logs',
130
131 /* =====================
132 * Debugging
133 * ===================== */
134 logToStdout: false,
135 logLevel: 'info',
136 logFeedback: false,
137 verbose: false,
138 };
139 '';
140 };
141
142 fileSystems."/var/lib/private/cryptpad" = {
143 device = "${machineName}/var/cryptpad";
144 fsType = "zfs";
145 };
146
147 services.syncoid.commands = {
148 "${machineName}/var/cryptpad" = {
149 sendOptions = "raw";
150 target = "backup@mermet.${networking.domain}:rpool/backup/${machineName}/var/cryptpad";
151 };
152 };
153
154 systemd.services.nginx = {
155 #after = [ "cryptpad.service" ];
156 #wants = [ "cryptpad.service" ];
157 serviceConfig = {
158 BindReadOnlyPaths = [
159 "/var/lib/private/cryptpad:${cryptpad_root}"
160 ];
161 LogsDirectory = lib.mkForce [
162 "nginx/${domain}/${srv}"
163 ];
164 };
165 };
166
167 services.nginx = {
168 virtualHosts.${main_domain} = {
169 serverAliases = [ sandbox_domain ];
170 listen = [
171 { addr="0.0.0.0"; port = 443; ssl = true; }
172 { addr="[::]"; port = 443; ssl = true; }
173 ];
174 useACMEHost = domain;
175 forceSSL = true;
176
177 # DOC: https://github.com/xwiki-labs/cryptpad/blob/master/docs/example.nginx.conf
178 root = "${pkgs.cryptpad}/lib/node_modules/cryptpad";
179
180 # The nodejs process can handle all traffic whether accessed over websocket or as static assets
181 # We prefer to serve static content from nginx directly and to leave the API server to handle
182 # the dynamic content that only it can manage. This is primarily an optimization
183 locations."^~ /cryptpad_websocket" = {
184 proxyPass = "http://[::1]:3000";
185 proxyWebsockets = true;
186 };
187
188 locations."^~ /customize.dist/" = {
189 # This is needed in order to prevent infinite recursion between /customize/ and the root
190 };
191 # try to load customizeable content via /customize/ and fall back to the default content
192 # located at /customize.dist/
193 # This is what allows you to override behaviour.
194 locations."^~ /customize/".extraConfig = ''
195 rewrite ^/customize/(.*)$ $1 break;
196 try_files /customize/$uri /customize.dist/$uri;
197 '';
198
199 # /api/config is loaded once per page load and is used to retrieve
200 # the caching variable which is applied to every other resource
201 # which is loaded during that session.
202 locations."= /api/config" = {
203 proxyPass = "http://[::1]:3000";
204 };
205
206 # encrypted blobs are immutable and are thus cached for a year
207 locations."^~ /blob/" = {
208 root = cryptpad_root;
209 extraConfig = ''
210 ${add_headers}
211 if ($request_method = 'OPTIONS') {
212 ${add_headers}
213 add_header 'Access-Control-Allow-Origin' '*';
214 add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
215 add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
216 add_header 'Access-Control-Max-Age' 1728000;
217 add_header 'Content-Type' 'application/octet-stream; charset=utf-8';
218 add_header 'Content-Length' 0;
219 return 204;
220 }
221 add_header Cache-Control max-age=31536000;
222 add_header 'Access-Control-Allow-Origin' '*';
223 add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
224 add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
225 add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
226 try_files $uri =404;
227 '';
228 };
229
230 # The "block-store" serves encrypted payloads containing users' drive keys
231 # these payloads are unlocked via login credentials.
232 # They are mutable and are thus never cached.
233 # They're small enough that it doesn't matter, in any case.
234 locations."^~ /block/" = {
235 root = cryptpad_root;
236 extraConfig = ''
237 ${add_headers}
238 add_header Cache-Control max-age=0;
239 try_files $uri =404;
240 '';
241 };
242
243 # ugly hack: disable registration
244 /*
245 locations."/register" = {
246 deny all;
247 }
248 */
249
250 # The nodejs server has some built-in forwarding rules to prevent
251 # URLs like /pad from resulting in a 404. This simply adds a trailing slash
252 # to a variety of applications.
253 locations."~ ^/(register|login|settings|user|pad|drive|poll|slide|code|whiteboard|file|media|profile|contacts|todo|filepicker|debug|kanban|sheet|support|admin|notifications|teams)$".extraConfig = ''
254 rewrite ^(.*)$ $1/ redirect;
255 '';
256
257 extraConfig = ''
258 access_log /var/log/nginx/${domain}/${srv}/access.log json;
259 error_log /var/log/nginx/${domain}/${srv}/error.log warn;
260
261 index index.html;
262 error_page 404 /customize.dist/404.html;
263
264 # add_header will not set any header if it is emptystring
265 set $cacheControl "";
266 # any static assets loaded with "ver=" in their URL will be cached for a year
267 if ($args ~ ver=) {
268 set $cacheControl max-age=31536000;
269 }
270
271 set $unsafe 0;
272 # the following assets are loaded via the sandbox domain
273 # they unfortunately still require exceptions to the sandboxing to work correctly.
274 if ($uri = "/pad/inner.html") { set $unsafe 1; }
275 if ($uri = "/sheet/inner.html") { set $unsafe 1; }
276 if ($uri ~ ^\/common\/onlyoffice\/.*\/index\.html.*$) { set $unsafe 1; }
277
278 # Everything except the sandbox domain is a privileged scope,
279 # as they might be used to handle keys
280 if ($host != "${sandbox_domain}") { set $unsafe 0; }
281
282 # script-src specifies valid sources for javascript, including inline handlers
283 set $scriptSrc "'self' resource: ${main_domain}";
284
285 # privileged contexts allow a few more rights than unprivileged contexts,
286 # though limits are still applied
287 if ($unsafe) {
288 set $scriptSrc "'self' 'unsafe-eval' 'unsafe-inline' resource: ${main_domain}";
289 }
290
291 ${add_headers}
292
293 # Finally, serve anything the above exceptions don't govern.
294 try_files /www/$uri /www/$uri/index.html /customize/$uri;
295 '';
296 };
297 };
298 }