@sovereignfs/create 0.13.0 → 0.17.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.
Files changed (33) hide show
  1. package/README.md +13 -1
  2. package/dist/create.mjs +910 -47
  3. package/package.json +1 -1
  4. package/template/app/AGENTS.md +49 -0
  5. package/template/app/CHANGELOG.md +11 -0
  6. package/template/app/CLAUDE.md +9 -0
  7. package/template/app/CONTRIBUTING.md +41 -27
  8. package/template/app/README.md +5 -1
  9. package/template/app/RELEASING.md +31 -0
  10. package/template/app/_github/repository.json +50 -0
  11. package/template/app/_github/workflows/ci.yml +11 -3
  12. package/template/app/_github/workflows/promotion.yml +24 -0
  13. package/template/app/_github/workflows/publish.yml +56 -7
  14. package/template/app/_github/workflows/release.yml +40 -0
  15. package/template/components/RELEASING.md +27 -0
  16. package/template/encryption/ENCRYPTION.md +30 -0
  17. package/template/encryption/app/actions.ts +20 -0
  18. package/template/encryption/app/api/me/keys/route.ts +21 -0
  19. package/template/encryption/app/api/notes/[id]/route.ts +39 -0
  20. package/template/encryption/app/api/notes/route.ts +36 -0
  21. package/template/encryption/app/api/people/[sub]/keys/route.ts +26 -0
  22. package/template/encryption/app/api/people/route.ts +22 -0
  23. package/template/encryption/app/keys/return/page.tsx +11 -0
  24. package/template/encryption/app/keys/return/received.tsx +36 -0
  25. package/template/encryption/app/notes.tsx +529 -0
  26. package/template/encryption/app/page.tsx +71 -0
  27. package/template/encryption/app/ui.tsx +14 -0
  28. package/template/encryption/lib/auth.ts +19 -0
  29. package/template/encryption/lib/keys.ts +14 -0
  30. package/template/encryption/lib/notes.ts +201 -0
  31. package/template/encryption/lib/sovereign.ts +21 -0
  32. package/template/encryption/migrations/001_init.sql +39 -0
  33. package/template/encryption/sovereign.manifest.json +21 -0
@@ -0,0 +1,529 @@
1
+ 'use client';
2
+
3
+ import {
4
+ appKeys,
5
+ decryptBytes,
6
+ encryptBytes,
7
+ importDocumentKey,
8
+ type CheckedPerson,
9
+ type MyKeys,
10
+ type OpenedIdentity,
11
+ type PersonKeys,
12
+ } from '@sovereignfs/sdk/keys';
13
+ import { useEffect, useMemo, useState } from 'react';
14
+ import { Alert, Button, Card, Dialog, EmptyState, Input, LockedState } from './ui';
15
+
16
+ /**
17
+ * The notes, encrypted in this browser (ENCRYPTION.md, RFC 0005). The app key comes from core once each browser session; each note has
18
+ * a key of its own, sealed to everyone who may read it; its title and text are encrypted with it. The server stores what this page sends
19
+ * and can open none of it. Everything that opens or makes a key happens here.
20
+ */
21
+
22
+ type Stored = {
23
+ id: string;
24
+ owner: string;
25
+ version: number;
26
+ meta: string;
27
+ body: string;
28
+ record: string;
29
+ readers: string[];
30
+ };
31
+ type Note = Stored & { title: string; text: string };
32
+ type Keys = ReturnType<typeof appKeys>;
33
+ type Ready = { keys: Keys; identity: OpenedIdentity; me: MyKeys };
34
+
35
+ const enc = new TextEncoder();
36
+ const dec = new TextDecoder();
37
+ const b64 = (bytes: Uint8Array) => {
38
+ let binary = '';
39
+ for (const byte of bytes) binary += String.fromCharCode(byte);
40
+ return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
41
+ };
42
+ const unb64 = (text: string) =>
43
+ Uint8Array.from(atob(text.replaceAll('-', '+').replaceAll('_', '/')), (c) => c.charCodeAt(0));
44
+ const metaId = (id: string) => `${id}/meta`;
45
+
46
+ async function json<T>(response: Response): Promise<T> {
47
+ if (!response.ok)
48
+ throw Object.assign(new Error(String(response.status)), { status: response.status });
49
+ return (await response.json()) as T;
50
+ }
51
+
52
+ export function Notes(props: {
53
+ core: string;
54
+ clientId: string;
55
+ returnTo: string;
56
+ appName: string;
57
+ }) {
58
+ const keys = useMemo(
59
+ () => appKeys({ core: props.core, clientId: props.clientId, returnTo: props.returnTo }),
60
+ [props.core, props.clientId, props.returnTo],
61
+ );
62
+ const [phase, setPhase] = useState<'opening' | 'locked' | 'open' | 'failed'>('opening');
63
+ const [ready, setReady] = useState<Ready>();
64
+ const [list, setList] = useState<Note[]>([]);
65
+ const [names, setNames] = useState<Record<string, string>>({});
66
+ const [draft, setDraft] = useState('');
67
+ const [busy, setBusy] = useState(false);
68
+ const [error, setError] = useState('');
69
+ // The note being shared, by id: after each change the list is loaded again, and the dialog shows the note as it now is.
70
+ const [sharingId, setSharingId] = useState<string>();
71
+
72
+ /** A person's keys, checked against their account's signature and the signing key this browser remembers for them. */
73
+ async function personKeys(
74
+ sub: string,
75
+ at: Ready,
76
+ ): Promise<CheckedPerson | 'changed' | 'not-opened'> {
77
+ if (sub === at.me.sub) return { ...at.me, checked: true };
78
+ const response = await fetch(`/api/people/${encodeURIComponent(sub)}/keys`, {
79
+ cache: 'no-store',
80
+ });
81
+ if (response.status === 404) return 'not-opened';
82
+ const checked = await at.keys.checkPerson(await json<PersonKeys>(response));
83
+ if (checked.ok) return checked.person;
84
+ if (checked.reason === 'changed') return 'changed';
85
+ throw new Error('Their keys are not signed by their account.');
86
+ }
87
+
88
+ /** Opens a note: its key from the record sealed to this person, checked as signed by the owner, then its title and text. */
89
+ async function open(note: Stored, at: Ready): Promise<Note> {
90
+ const owner = await personKeys(note.owner, at);
91
+ if (typeof owner === 'string') throw new Error('The owner’s keys cannot be checked.');
92
+ const raw = await at.keys.openShared({
93
+ record: JSON.parse(note.record),
94
+ documentId: note.id,
95
+ me: at.me,
96
+ from: owner,
97
+ identity: at.identity,
98
+ });
99
+ try {
100
+ const key = await importDocumentKey(raw);
101
+ const meta = await decryptBytes(
102
+ key,
103
+ { documentId: metaId(note.id), version: note.version },
104
+ unb64(note.meta),
105
+ );
106
+ const body = await decryptBytes(
107
+ key,
108
+ { documentId: note.id, version: note.version },
109
+ unb64(note.body),
110
+ );
111
+ return {
112
+ ...note,
113
+ title: (JSON.parse(dec.decode(meta)) as { title: string }).title,
114
+ text: dec.decode(body),
115
+ };
116
+ } finally {
117
+ raw.fill(0);
118
+ }
119
+ }
120
+
121
+ async function load(at: Ready) {
122
+ const answer = await json<{ notes: Stored[]; names: Record<string, string> }>(
123
+ await fetch('/api/notes', { cache: 'no-store' }),
124
+ );
125
+ setNames(answer.names);
126
+ const opened: Note[] = [];
127
+ for (const note of answer.notes) {
128
+ try {
129
+ opened.push(await open(note, at));
130
+ } catch {
131
+ // A note that does not open (its owner's keys changed, or it was tampered with) is left out, never shown as ciphertext.
132
+ }
133
+ }
134
+ setList(opened);
135
+ }
136
+
137
+ useEffect(() => {
138
+ let live = true;
139
+ (async () => {
140
+ const key = await keys.open();
141
+ if (key.state === 'locked') return live && setPhase('locked');
142
+ const me = await json<MyKeys>(await fetch('/api/me/keys', { cache: 'no-store' }));
143
+ const identity = await keys.identity(key.key, me);
144
+ if (!identity.ok) throw new Error(identity.reason);
145
+ const at = { keys, identity: identity.identity, me };
146
+ await load(at);
147
+ if (live) {
148
+ setReady(at);
149
+ setPhase('open');
150
+ }
151
+ })().catch(() => live && setPhase('failed'));
152
+ return () => {
153
+ live = false;
154
+ };
155
+ // `load` reads only what it is given, so the keys are all this depends on.
156
+ }, [keys]);
157
+
158
+ /**
159
+ * Encrypts a note with `documentKey` under `version` and sends it with its readers, the key sealed to each. The caller overwrites the
160
+ * key's bytes.
161
+ */
162
+ async function write(
163
+ at: Ready,
164
+ id: string,
165
+ version: number,
166
+ title: string,
167
+ text: string,
168
+ documentKey: Uint8Array,
169
+ readers: CheckedPerson[],
170
+ ) {
171
+ const key = await importDocumentKey(documentKey);
172
+ const meta = await encryptBytes(
173
+ key,
174
+ { documentId: metaId(id), version },
175
+ enc.encode(JSON.stringify({ title })),
176
+ );
177
+ const body = await encryptBytes(key, { documentId: id, version }, enc.encode(text));
178
+ const sealed = await Promise.all(
179
+ readers.map(async (to) => ({
180
+ sub: to.sub,
181
+ record: JSON.stringify(
182
+ await at.keys.share({ documentKey, documentId: id, to, identity: at.identity }),
183
+ ),
184
+ })),
185
+ );
186
+ const response = await fetch(`/api/notes/${id}`, {
187
+ method: 'PUT',
188
+ headers: { 'content-type': 'application/json' },
189
+ body: JSON.stringify({ version, meta: b64(meta), body: b64(body), readers: sealed }),
190
+ });
191
+ if (!response.ok) throw new Error('The note was not saved.');
192
+ }
193
+
194
+ async function act(run: () => Promise<void>, failure: string) {
195
+ if (!ready) return;
196
+ setBusy(true);
197
+ setError('');
198
+ try {
199
+ await run();
200
+ await load(ready);
201
+ } catch {
202
+ setError(failure);
203
+ } finally {
204
+ setBusy(false);
205
+ }
206
+ }
207
+
208
+ const add = () =>
209
+ act(async () => {
210
+ if (!ready || draft.trim() === '') return;
211
+ const text = draft.trim();
212
+ const documentKey = ready.keys.newDocumentKey();
213
+ try {
214
+ await write(
215
+ ready,
216
+ crypto.randomUUID(),
217
+ 1,
218
+ text.split('\n')[0]?.slice(0, 120) ?? '',
219
+ text,
220
+ documentKey,
221
+ [{ ...ready.me, checked: true }],
222
+ );
223
+ } finally {
224
+ documentKey.fill(0);
225
+ }
226
+ setDraft('');
227
+ }, 'Couldn’t save the note. Try again.');
228
+
229
+ const remove = (note: Note) =>
230
+ act(async () => {
231
+ const response = await fetch(`/api/notes/${note.id}`, { method: 'DELETE' });
232
+ if (!response.ok && response.status !== 404) throw new Error('not deleted');
233
+ }, 'Couldn’t delete the note. Try again.');
234
+
235
+ /** Shares with one more person: the note's key, unchanged, sealed to them too. */
236
+ async function shareWith(note: Note, person: CheckedPerson) {
237
+ if (!ready) return;
238
+ const raw = await ready.keys.openShared({
239
+ record: JSON.parse(note.record),
240
+ documentId: note.id,
241
+ me: ready.me,
242
+ from: { ...ready.me, checked: true },
243
+ identity: ready.identity,
244
+ });
245
+ try {
246
+ const readers = await checkedReaders(note.readers.filter((sub) => sub !== person.sub));
247
+ await write(ready, note.id, note.version, note.title, note.text, raw, [...readers, person]);
248
+ } finally {
249
+ raw.fill(0);
250
+ }
251
+ await load(ready);
252
+ }
253
+
254
+ /** Stops sharing with someone: a new key for the note, sealed only to those who remain (RFC 0005 §8). */
255
+ async function unshare(note: Note, sub: string) {
256
+ if (!ready) return;
257
+ const documentKey = ready.keys.newDocumentKey();
258
+ try {
259
+ const readers = await checkedReaders(note.readers.filter((each) => each !== sub));
260
+ await write(ready, note.id, note.version + 1, note.title, note.text, documentKey, readers);
261
+ } finally {
262
+ documentKey.fill(0);
263
+ }
264
+ await load(ready);
265
+ }
266
+
267
+ async function checkedReaders(subs: string[]): Promise<CheckedPerson[]> {
268
+ if (!ready) return [];
269
+ const out: CheckedPerson[] = [];
270
+ for (const sub of subs) {
271
+ const keys_ = await personKeys(sub, ready);
272
+ // Someone whose keys changed, or who cannot be checked, is not sealed to again until the owner shares with them anew.
273
+ if (typeof keys_ !== 'string') out.push(keys_);
274
+ }
275
+ if (!out.some((reader) => reader.sub === ready.me.sub))
276
+ out.push({ ...ready.me, checked: true });
277
+ return out;
278
+ }
279
+
280
+ if (phase === 'opening') return null;
281
+ if (phase === 'locked')
282
+ return (
283
+ <Card>
284
+ <LockedState
285
+ reason="locked"
286
+ appName={props.appName}
287
+ action={<Button onClick={() => void keys.unlock()}>Unlock</Button>}
288
+ />
289
+ </Card>
290
+ );
291
+ if (phase === 'failed')
292
+ return (
293
+ <Alert variant="error" heading="Couldn’t open your notes">
294
+ Reload the page to try again. If it keeps happening, sign out and back in.
295
+ </Alert>
296
+ );
297
+
298
+ const sharing = list.find((note) => note.id === sharingId);
299
+
300
+ const who = (note: Note) => {
301
+ if (note.owner !== ready?.me.sub) return `Shared with you by ${names[note.owner] ?? 'someone'}`;
302
+ const others = note.readers.filter((sub) => sub !== note.owner);
303
+ return others.length === 0
304
+ ? 'Only you'
305
+ : `Shared with ${others.map((sub) => names[sub] ?? 'someone').join(', ')}`;
306
+ };
307
+
308
+ return (
309
+ <>
310
+ <Card>
311
+ <p>Only you and the people you share a note with can read it. Not yet audited.</p>
312
+ </Card>
313
+ <Card>
314
+ <form
315
+ onSubmit={(event) => {
316
+ event.preventDefault();
317
+ void add();
318
+ }}
319
+ >
320
+ <Input
321
+ value={draft}
322
+ onChange={(event) => setDraft(event.target.value)}
323
+ placeholder="What do you want to remember?"
324
+ aria-label="A note"
325
+ maxLength={20000}
326
+ required
327
+ />
328
+ <Button type="submit" loading={busy}>
329
+ {busy ? 'Saving…' : 'Save'}
330
+ </Button>
331
+ </form>
332
+ </Card>
333
+ {error ? <Alert variant="error">{error}</Alert> : null}
334
+ {list.length === 0 ? (
335
+ <EmptyState
336
+ icon="file-text"
337
+ heading="No notes yet"
338
+ description="Write one above. Only you can read it until you share it."
339
+ />
340
+ ) : (
341
+ <ul>
342
+ {list.map((note) => (
343
+ <li key={note.id}>
344
+ <Card>
345
+ <div style={{ flex: 1 }}>
346
+ <strong>{note.title}</strong>
347
+ <p>{note.text}</p>
348
+ <small>{who(note)}</small>
349
+ </div>
350
+ {note.owner === ready?.me.sub ? (
351
+ <>
352
+ <Button variant="ghost" size="sm" onClick={() => setSharingId(note.id)}>
353
+ Share
354
+ </Button>
355
+ <Button
356
+ variant="ghost"
357
+ size="sm"
358
+ onClick={() => void remove(note)}
359
+ disabled={busy}
360
+ >
361
+ Delete
362
+ </Button>
363
+ </>
364
+ ) : null}
365
+ </Card>
366
+ </li>
367
+ ))}
368
+ </ul>
369
+ )}
370
+ {sharing && ready ? (
371
+ <Share
372
+ note={sharing}
373
+ names={names}
374
+ appName={props.appName}
375
+ onClose={() => setSharingId(undefined)}
376
+ find={(sub) => personKeys(sub, ready)}
377
+ trust={async (keys_) => {
378
+ await ready.keys.trustChanged(keys_);
379
+ }}
380
+ fetchKeys={async (sub) =>
381
+ json<PersonKeys>(
382
+ await fetch(`/api/people/${encodeURIComponent(sub)}/keys`, { cache: 'no-store' }),
383
+ )
384
+ }
385
+ share={(person) => shareWith(sharing, person)}
386
+ unshare={(sub) => unshare(sharing, sub)}
387
+ />
388
+ ) : null}
389
+ </>
390
+ );
391
+ }
392
+
393
+ function Share(props: {
394
+ note: Note;
395
+ names: Record<string, string>;
396
+ appName: string;
397
+ onClose: () => void;
398
+ find: (sub: string) => Promise<CheckedPerson | 'changed' | 'not-opened'>;
399
+ trust: (keys: PersonKeys) => Promise<void>;
400
+ fetchKeys: (sub: string) => Promise<PersonKeys>;
401
+ share: (person: CheckedPerson) => Promise<void>;
402
+ unshare: (sub: string) => Promise<void>;
403
+ }) {
404
+ const [q, setQ] = useState('');
405
+ const [found, setFound] = useState<{ sub: string; name: string }[]>([]);
406
+ const [message, setMessage] = useState('');
407
+ const [changed, setChanged] = useState<{ sub: string; name: string }>();
408
+ const [busy, setBusy] = useState(false);
409
+ const others = props.note.readers.filter((sub) => sub !== props.note.owner);
410
+
411
+ useEffect(() => {
412
+ if (q.trim().length < 2) return setFound([]);
413
+ const timer = setTimeout(() => {
414
+ void fetch(`/api/people?q=${encodeURIComponent(q.trim())}`, { cache: 'no-store' })
415
+ .then((response) => (response.ok ? response.json() : { people: [] }))
416
+ .then((answer: { people: { sub: string; name: string }[] }) => setFound(answer.people));
417
+ }, 250);
418
+ return () => clearTimeout(timer);
419
+ }, [q]);
420
+
421
+ async function choose(person: { sub: string; name: string }) {
422
+ setBusy(true);
423
+ setMessage('');
424
+ try {
425
+ const keys = await props.find(person.sub);
426
+ if (keys === 'not-opened') {
427
+ setMessage(
428
+ `${person.name} hasn’t opened ${props.appName} yet. Ask them to open it once, then share again.`,
429
+ );
430
+ } else if (keys === 'changed') {
431
+ setChanged(person);
432
+ } else {
433
+ await props.share(keys);
434
+ setQ('');
435
+ }
436
+ } catch {
437
+ setMessage('Couldn’t share the note. Try again.');
438
+ } finally {
439
+ setBusy(false);
440
+ }
441
+ }
442
+
443
+ async function shareAnyway() {
444
+ if (!changed) return;
445
+ setBusy(true);
446
+ try {
447
+ await props.trust(await props.fetchKeys(changed.sub));
448
+ const keys = await props.find(changed.sub);
449
+ if (typeof keys !== 'string') await props.share(keys);
450
+ setChanged(undefined);
451
+ } catch {
452
+ setMessage('Couldn’t share the note. Try again.');
453
+ } finally {
454
+ setBusy(false);
455
+ }
456
+ }
457
+
458
+ return (
459
+ <Dialog
460
+ open
461
+ onClose={props.onClose}
462
+ header={<strong>Share “{props.note.title}”</strong>}
463
+ title={`Share “${props.note.title}”`}
464
+ footer={
465
+ <Button variant="secondary" onClick={props.onClose}>
466
+ Close
467
+ </Button>
468
+ }
469
+ >
470
+ <p>People you share with can read this note and every change to it.</p>
471
+ <Input
472
+ value={q}
473
+ onChange={(event) => setQ(event.target.value)}
474
+ placeholder="Search people on this Sovereign"
475
+ aria-label="Person"
476
+ />
477
+ <ul>
478
+ {found.map((person) => (
479
+ <li key={person.sub}>
480
+ <Button variant="ghost" onClick={() => void choose(person)} disabled={busy}>
481
+ {person.name}
482
+ </Button>
483
+ </li>
484
+ ))}
485
+ </ul>
486
+ {message ? <Alert variant="info">{message}</Alert> : null}
487
+ {changed ? (
488
+ <Alert variant="warning" heading={`${changed.name}’s security details changed`}>
489
+ This can happen when {changed.name} resets their account, or if someone tampered with the
490
+ server. Check with {changed.name} before you share with them again.
491
+ <div>
492
+ <Button variant="secondary" onClick={() => setChanged(undefined)}>
493
+ Not now
494
+ </Button>
495
+ <Button onClick={() => void shareAnyway()} loading={busy}>
496
+ Share anyway
497
+ </Button>
498
+ </div>
499
+ </Alert>
500
+ ) : null}
501
+ {others.length > 0 ? (
502
+ <>
503
+ <p>
504
+ <strong>Shared with</strong>
505
+ </p>
506
+ <ul>
507
+ {others.map((sub) => (
508
+ <li key={sub}>
509
+ {props.names[sub] ?? 'Someone'}{' '}
510
+ <Button
511
+ variant="secondary"
512
+ size="sm"
513
+ onClick={() => void props.unshare(sub)}
514
+ disabled={busy}
515
+ >
516
+ Remove
517
+ </Button>
518
+ </li>
519
+ ))}
520
+ </ul>
521
+ <small>
522
+ Removing someone stops them reading changes. What they already read cannot be taken
523
+ back.
524
+ </small>
525
+ </>
526
+ ) : null}
527
+ </Dialog>
528
+ );
529
+ }
@@ -0,0 +1,71 @@
1
+ import { auth } from '@/lib/auth';
2
+ import { files } from '@/lib/files';
3
+ import { keySettings } from '@/lib/keys';
4
+ import { deleteFile } from './actions';
5
+ import { Notes } from './notes';
6
+ import { Button, Card, PageHeader } from './ui';
7
+ import { Upload } from './upload';
8
+
9
+ /** A size as a person reads it: 512 KB, 3.4 MB, 200 GB. */
10
+ function size(bytes: number): string {
11
+ const units = ['bytes', 'KB', 'MB', 'GB', 'TB'];
12
+ let value = bytes;
13
+ let unit = 0;
14
+ while (value >= 1024 && unit < units.length - 1) {
15
+ value /= 1024;
16
+ unit += 1;
17
+ }
18
+ return unit === 0 ? `${value} bytes` : `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit]}`;
19
+ }
20
+
21
+ // The page is for the person signed in, so it is made for each request.
22
+ export const dynamic = 'force-dynamic';
23
+
24
+ export default async function Home() {
25
+ // Sends a person to sign in with core, and back here.
26
+ const session = await auth().requireSession('/');
27
+ // Their files, kept the suite's way: a folder for this person and a quota for this person (lib/files.ts).
28
+ const [kept, usage] = await Promise.all([files().list(session.sub), files().usage(session.sub)]);
29
+ const name = typeof session.claims.name === 'string' ? session.claims.name : 'there';
30
+
31
+ return (
32
+ <main>
33
+ <PageHeader title="__TITLE__" description={`Signed in as ${name}`} />
34
+ {/* The notes are opened and written in the browser alone (app/notes.tsx); the server renders nothing of them. */}
35
+ <Notes {...keySettings()} appName="__TITLE__" />
36
+ <Card>
37
+ <div>
38
+ <h2>Files</h2>
39
+ <p>
40
+ {usage.files} of {usage.quota.files} files, {size(usage.bytes)} of{' '}
41
+ {size(usage.quota.bytes)} used. Files are not encrypted: the server can read them.
42
+ </p>
43
+ <Upload />
44
+ </div>
45
+ </Card>
46
+ <ul>
47
+ {kept.map((file) => (
48
+ <li key={file.id}>
49
+ <Card>
50
+ <form action={deleteFile}>
51
+ <a href={`/api/files/${file.id}`} style={{ flex: 1 }}>
52
+ {file.name} ({size(file.size)})
53
+ </a>
54
+ <input type="hidden" name="id" value={file.id} />
55
+ <Button type="submit" variant="ghost" size="sm">
56
+ Delete
57
+ </Button>
58
+ </form>
59
+ </Card>
60
+ </li>
61
+ ))}
62
+ </ul>
63
+ {/* Signing out ends the session, and with it the secret this browser's kept key needs: it opens nothing afterwards. */}
64
+ <form action="/auth/logout" method="post">
65
+ <Button type="submit" variant="secondary">
66
+ Sign out
67
+ </Button>
68
+ </form>
69
+ </main>
70
+ );
71
+ }
@@ -0,0 +1,14 @@
1
+ 'use client';
2
+
3
+ // `@sovereignfs/ui` is one bundle with components that use React context, so a Server Component cannot import it directly. It is
4
+ // re-exported from here, a Client Component module, and pages import the parts they use from "./ui". They still render on the server.
5
+ export {
6
+ Alert,
7
+ Button,
8
+ Card,
9
+ Dialog,
10
+ EmptyState,
11
+ Input,
12
+ LockedState,
13
+ PageHeader,
14
+ } from '@sovereignfs/ui';
@@ -0,0 +1,19 @@
1
+ import { nextAuth } from '@sovereignfs/sdk/next';
2
+ import { files } from './files';
3
+ import { notes } from './notes';
4
+ import { sovereign } from './sovereign';
5
+
6
+ /**
7
+ * Sign-in for this app (docs/using-the-sdk.md). When a person deletes their account on the instance, core tells the app and keeps
8
+ * telling it until it answers 200, which the SDK sends only after this function has finished. It must be safe to run twice.
9
+ */
10
+ export const auth = () =>
11
+ nextAuth(sovereign(), {
12
+ onAccountDeleted: async ({ sub }) => {
13
+ // Their notes and the keys sealed to them for others' notes (RFC 0005 §8): with the keys gone, nothing of theirs opens.
14
+ await notes().deleteAll(sub);
15
+ // And the files they uploaded: their folder, which is gone once this has run, however often it does.
16
+ await files().removeAll(sub);
17
+ // The SDK has already ended the person's sessions and forgotten their refresh token.
18
+ },
19
+ });
@@ -0,0 +1,14 @@
1
+ import { required } from './config';
2
+
3
+ /**
4
+ * What the page needs to get the app's key from core (sdk §9.3): core's address, the app's client id, and the key return address as
5
+ * registered, absolute. Read on the server for each request and handed to the page, never built into the bundle.
6
+ */
7
+ export function keySettings() {
8
+ const app = required('__PREFIX___URL').replace(/\/+$/, '');
9
+ return {
10
+ core: required('__PREFIX___CORE_URL'),
11
+ clientId: required('__PREFIX___CORE_CLIENT_ID'),
12
+ returnTo: `${app}/keys/return`,
13
+ };
14
+ }