@sovereignfs/create 0.19.0 → 0.27.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 (61) hide show
  1. package/README.md +5 -3
  2. package/dist/create.mjs +354 -88
  3. package/package.json +3 -2
  4. package/template/app/AGENTS.md +36 -3
  5. package/template/app/CONTRIBUTING.md +3 -3
  6. package/template/app/Dockerfile +6 -5
  7. package/template/app/README.md +64 -32
  8. package/template/app/_env.example +11 -1
  9. package/template/app/_githooks/pre-push +2 -2
  10. package/template/app/_github/workflows/ci.yml +5 -4
  11. package/template/app/_github/workflows/publish.yml +8 -6
  12. package/template/app/_gitignore +4 -0
  13. package/template/app/app/actions.ts +34 -8
  14. package/template/app/app/api/auth/[...all]/route.ts +10 -0
  15. package/template/app/app/api/files/[id]/route.ts +4 -6
  16. package/template/app/app/api/files/route.ts +8 -5
  17. package/template/app/app/api/push/subscription/route.ts +23 -0
  18. package/template/app/app/api/sign-in-salt/route.ts +9 -0
  19. package/template/app/app/api/sovereign/account-deleted/route.ts +10 -0
  20. package/template/app/app/api/sovereign/backchannel-logout/route.ts +10 -0
  21. package/template/app/app/api/sovereign/export/route.ts +10 -0
  22. package/template/app/app/notifications.tsx +42 -0
  23. package/template/app/app/page.tsx +21 -9
  24. package/template/app/app/push-actions.ts +41 -0
  25. package/template/app/app/security/actions.ts +45 -0
  26. package/template/app/app/security/page.tsx +33 -0
  27. package/template/app/app/security/panels.tsx +50 -0
  28. package/template/app/app/sign-in/page.tsx +49 -0
  29. package/template/app/app/sign-in/panel.tsx +71 -0
  30. package/template/app/app/sign-out.tsx +19 -0
  31. package/template/app/app/sign-up/page.tsx +39 -0
  32. package/template/app/app/sign-up/panel.tsx +54 -0
  33. package/template/app/app/sw.js/route.ts +10 -2
  34. package/template/app/app/ui.tsx +13 -1
  35. package/template/app/compose.yml +3 -2
  36. package/template/app/instrumentation.ts +9 -1
  37. package/template/app/lib/account.ts +6 -0
  38. package/template/app/lib/crypto.ts +16 -9
  39. package/template/app/lib/csp.ts +5 -3
  40. package/template/app/lib/notices.ts +63 -0
  41. package/template/app/lib/push.ts +227 -0
  42. package/template/app/lib/session.ts +40 -0
  43. package/template/app/lib/sign-in-client.ts +22 -0
  44. package/template/app/lib/sign-in.ts +113 -0
  45. package/template/app/lib/sovereign.ts +7 -6
  46. package/template/app/migrations/002_push.sql +24 -0
  47. package/template/app/sovereign.manifest.json +11 -8
  48. package/template/encryption/_env.example +27 -0
  49. package/template/encryption/_skip +18 -0
  50. package/template/encryption/app/api/files/[id]/route.ts +45 -0
  51. package/template/encryption/app/api/files/route.ts +43 -0
  52. package/template/{app → encryption}/app/auth/[action]/route.ts +2 -1
  53. package/template/encryption/app/page.tsx +7 -2
  54. package/template/encryption/app/sign-out.tsx +21 -0
  55. package/template/encryption/app/ui.tsx +1 -0
  56. package/template/encryption/instrumentation.ts +12 -0
  57. package/template/encryption/lib/account.ts +6 -0
  58. package/template/encryption/lib/auth.ts +36 -0
  59. package/template/encryption/sovereign.manifest.json +4 -3
  60. package/template/pm/yarn/_yarnrc.yml +3 -0
  61. package/template/app/lib/auth.ts +0 -18
@@ -5,11 +5,11 @@ import { PWA_CSP_DIRECTIVES } from '@sovereignfs/pwa';
5
5
  * mark, and nothing loads from another site:
6
6
  *
7
7
  * - **Scripts** run only with this request's nonce, or when a script that has it loads them (`'strict-dynamic'`): the bundles Next adds.
8
- * No inline handler, no `javascript:` address, no `eval` but in development, where React wants it.
8
+ * No inline handler, no `javascript:` address, no `eval` but in development, where React wants it; WebAssembly for the sign-in value.
9
9
  * - **Style elements** carry the nonce; **style attributes** are allowed, which the design system positions overlays with and which can
10
10
  * change how something looks but not run anything.
11
11
  * - **Everything else is this origin's**: images, fonts, what the page fetches, the service worker and the manifest.
12
- * - **Forms** go to this origin and to core: signing out posts here, and the answer sends the browser on to core.
12
+ * - **Forms** go to this origin and to core: signing out posts here, and the answer may send the browser on to core.
13
13
  * - Nobody may frame a page, `<base>` cannot be changed, and over https every request of the page is made over https.
14
14
  *
15
15
  * Kept free of Node's built-ins, since the proxy imports it.
@@ -30,7 +30,9 @@ export function contentSecurityPolicy({ nonce, secure, development, core }: Poli
30
30
  const styles = development ? "'self' 'unsafe-inline'" : `'self' 'nonce-${nonce}'`;
31
31
  return [
32
32
  "default-src 'self'",
33
- `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${development ? " 'unsafe-eval'" : ''}`,
33
+ // `'wasm-unsafe-eval'` runs the sign-in value's Argon2id, which is WebAssembly (auth.md §4, rule 1); never `'unsafe-eval'` but in
34
+ // development.
35
+ `script-src 'self' 'nonce-${nonce}' 'strict-dynamic' 'wasm-unsafe-eval'${development ? " 'unsafe-eval'" : ''}`,
34
36
  `style-src ${styles}`,
35
37
  `style-src-elem ${styles}`,
36
38
  "style-src-attr 'unsafe-inline'",
@@ -0,0 +1,63 @@
1
+ import { coreNotices, userIdForSub } from '@sovereignfs/auth/core';
2
+ import pkg from '../package.json' with { type: 'json' };
3
+ import { required } from './config';
4
+ import { files } from './files';
5
+ import { pushStore } from './push';
6
+ import { signIn } from './sign-in';
7
+ import { sovereign } from './sovereign';
8
+ import { tokenStore } from './stores';
9
+
10
+ /**
11
+ * Core's two notices (auth.md §8): a logout ends this app's sessions of that core session, or of that person; an account deleted at the
12
+ * instance deletes the person here first, and core keeps telling the app until it has. It must be safe to run twice.
13
+ */
14
+ export async function notices() {
15
+ const { auth, database } = await signIn();
16
+ return coreNotices({
17
+ database,
18
+ auth,
19
+ coreUrl: required('__PREFIX___CORE_URL'),
20
+ clientId: required('__PREFIX___CORE_CLIENT_ID'),
21
+ dropRefreshToken: async (sub) => {
22
+ await tokenStore.delete?.(sub);
23
+ },
24
+ onAccountDeleted: async (sub) => {
25
+ const userId = await userIdForSub(database, sub);
26
+ if (!userId) return;
27
+ await database.run('DELETE FROM notes WHERE owner = ?', [userId]);
28
+ // And the files they uploaded: their folder, which is gone once this has run, however often it does.
29
+ await files().removeAll(userId);
30
+ // And the devices they get notifications on, with what was waiting for them.
31
+ await pushStore().removeAccount(userId);
32
+ await (await auth.$context).internalAdapter.deleteUser(userId);
33
+ },
34
+ });
35
+ }
36
+
37
+ /**
38
+ * Core's request for a person's part of their export from the instance (core-app §4.7.2): what this app keeps of them, and nothing of
39
+ * anyone else. The SDK checks core's signed request and writes the format; a person with no account here gets an empty part.
40
+ */
41
+ export async function exportPart(request: Request) {
42
+ const { database } = await signIn();
43
+ return sovereign().auth.handleExportRequest(
44
+ request,
45
+ { prefix: '__PREFIX_LOWER__', version: pkg.version },
46
+ async ({ sub, writer }) => {
47
+ const userId = await userIdForSub(database, sub);
48
+ if (!userId) return;
49
+ const { rows } = await database.run(
50
+ 'SELECT id, body, created_at FROM notes WHERE owner = ? ORDER BY id',
51
+ [userId],
52
+ );
53
+ await writer.addRecords('apps/__PREFIX_LOWER__/records/notes.jsonl', 'notes', rows);
54
+ const kept = await files().list(userId);
55
+ // What each file is (its name, type and size), then the files themselves.
56
+ await writer.addRecords('apps/__PREFIX_LOWER__/records/files.jsonl', 'files', kept);
57
+ for (const record of kept) {
58
+ const { body } = await files().get(userId, record.id);
59
+ await writer.addFile(`apps/__PREFIX_LOWER__/files/${record.id}`, body, record.size);
60
+ }
61
+ },
62
+ );
63
+ }
@@ -0,0 +1,227 @@
1
+ import type { Pool, PoolClient } from 'pg';
2
+ import {
3
+ MAX_DEVICES,
4
+ pushSettings,
5
+ runPushOutbox,
6
+ type ClaimedPush,
7
+ type PushMessage,
8
+ type PushSettings,
9
+ type PushStore,
10
+ } from '@sovereignfs/push';
11
+ import { db } from './db';
12
+ import { open, seal } from './crypto';
13
+
14
+ /**
15
+ * Web Push (`@sovereignfs/push`): the app's key from `__PREFIX___VAPID_PRIVATE_KEY`, which the instance makes once (`generate` in
16
+ * sovereign.manifest.json). With no key the app sends no notifications, and the settings say nothing of them.
17
+ */
18
+ let settings: PushSettings | undefined | null = null;
19
+ export function appPush(): PushSettings | undefined {
20
+ if (settings === null) settings = pushSettings('__PREFIX__');
21
+ return settings;
22
+ }
23
+
24
+ /** A device's keys are sealed under a key of their own, made from the app's secret (lib/crypto.ts). */
25
+ const PURPOSE = 'push devices';
26
+
27
+ type Queryable = Pick<Pool, 'query'> | PoolClient;
28
+
29
+ const isPool = (q: Queryable): q is Pool => 'connect' in q && 'totalCount' in q;
30
+
31
+ /** Runs `work` in one transaction: on a client of the pool, or in the transaction the caller is already in. */
32
+ async function atomically<T>(q: Queryable, work: (client: Queryable) => Promise<T>): Promise<T> {
33
+ if (!isPool(q)) return work(q);
34
+ const client = await q.connect();
35
+ try {
36
+ await client.query('BEGIN');
37
+ const result = await work(client);
38
+ await client.query('COMMIT');
39
+ return result;
40
+ } catch (error) {
41
+ await client.query('ROLLBACK').catch(() => undefined);
42
+ throw error;
43
+ } finally {
44
+ client.release();
45
+ }
46
+ }
47
+
48
+ /**
49
+ * The devices and waiting pushes, in the app's database (migrations/002_push.sql), as `@sovereignfs/push` asks for them. Give it the
50
+ * client of a transaction to queue a push with the change that raised it: a change rolled back sends nothing.
51
+ */
52
+ export function pushStore(q: Queryable = db()): PushStore {
53
+ return {
54
+ async saveDevice(account, subscription, now) {
55
+ const keys = seal(
56
+ JSON.stringify({ p256dh: subscription.p256dh, auth: subscription.auth }),
57
+ PURPOSE,
58
+ );
59
+ await atomically(q, async (tx) => {
60
+ // An endpoint another account had becomes this one's, and nothing that account was waiting for goes to it.
61
+ await tx.query('DELETE FROM push_outbox WHERE endpoint = $1 AND account <> $2', [
62
+ subscription.endpoint,
63
+ account,
64
+ ]);
65
+ await tx.query(
66
+ `INSERT INTO push_devices (endpoint, account, keys, saved_at) VALUES ($1, $2, $3, $4)
67
+ ON CONFLICT (endpoint) DO UPDATE SET account = EXCLUDED.account, keys = EXCLUDED.keys, saved_at = EXCLUDED.saved_at`,
68
+ [subscription.endpoint, account, keys, now],
69
+ );
70
+ await tx.query(
71
+ `DELETE FROM push_devices WHERE account = $1 AND endpoint NOT IN (
72
+ SELECT endpoint FROM push_devices WHERE account = $1 ORDER BY saved_at DESC, endpoint DESC LIMIT $2
73
+ )`,
74
+ [account, MAX_DEVICES],
75
+ );
76
+ });
77
+ },
78
+
79
+ async removeDevice(account, endpoint) {
80
+ await q.query('DELETE FROM push_devices WHERE endpoint = $1 AND account = $2', [
81
+ endpoint,
82
+ account,
83
+ ]);
84
+ },
85
+
86
+ async devices(account) {
87
+ const { rows } = await q.query<{ endpoint: string; keys: string }>(
88
+ 'SELECT endpoint, keys FROM push_devices WHERE account = $1 ORDER BY saved_at, endpoint',
89
+ [account],
90
+ );
91
+ return rows.flatMap((row) => {
92
+ const keys = openKeys(row.keys);
93
+ return keys ? [{ endpoint: row.endpoint, ...keys }] : [];
94
+ });
95
+ },
96
+
97
+ async removeAccount(account) {
98
+ await atomically(q, async (tx) => {
99
+ await tx.query('DELETE FROM push_outbox WHERE account = $1', [account]);
100
+ await tx.query('DELETE FROM push_devices WHERE account = $1', [account]);
101
+ });
102
+ },
103
+
104
+ async forget(endpoint) {
105
+ await q.query('DELETE FROM push_devices WHERE endpoint = $1', [endpoint]);
106
+ },
107
+
108
+ async enqueue(items) {
109
+ for (const item of items) {
110
+ // Only for a device that is the account's: never a push to someone else's device.
111
+ await q.query(
112
+ `INSERT INTO push_outbox (id, account, endpoint, message, due_at, expires_at)
113
+ SELECT $1, $2, $3, $4, $5, $6
114
+ WHERE EXISTS (SELECT 1 FROM push_devices WHERE endpoint = $3 AND account = $2)`,
115
+ [
116
+ item.id,
117
+ item.account,
118
+ item.endpoint,
119
+ JSON.stringify(item.message),
120
+ item.dueAt,
121
+ item.expiresAt,
122
+ ],
123
+ );
124
+ }
125
+ },
126
+
127
+ async claim(now, leaseMs, batch) {
128
+ // One statement, and rows another runner holds are skipped: two runners never claim one push.
129
+ const { rows } = await q.query<{
130
+ id: string;
131
+ account: string;
132
+ endpoint: string;
133
+ message: PushMessage;
134
+ attempts: number;
135
+ due_at: string;
136
+ expires_at: string;
137
+ }>(
138
+ `UPDATE push_outbox SET attempts = attempts + 1, claimed_until = $1::bigint + $2::bigint
139
+ WHERE id IN (
140
+ SELECT id FROM push_outbox WHERE due_at <= $1 AND claimed_until <= $1
141
+ ORDER BY due_at, id LIMIT $3 FOR UPDATE SKIP LOCKED
142
+ ) AND due_at <= $1 AND claimed_until <= $1
143
+ RETURNING id, account, endpoint, message, attempts, due_at, expires_at`,
144
+ [now, leaseMs, batch],
145
+ );
146
+ if (rows.length === 0) return [];
147
+ const devices = await q.query<{ endpoint: string; account: string; keys: string }>(
148
+ 'SELECT endpoint, account, keys FROM push_devices WHERE endpoint = ANY($1)',
149
+ [[...new Set(rows.map((row) => row.endpoint))]],
150
+ );
151
+ const byEndpoint = new Map(devices.rows.map((device) => [device.endpoint, device]));
152
+ const claimed: ClaimedPush[] = [];
153
+ for (const row of rows) {
154
+ const device = byEndpoint.get(row.endpoint);
155
+ const keys = device && device.account === row.account ? openKeys(device.keys) : undefined;
156
+ if (!keys) {
157
+ // Its device is gone, or is someone else's now, or its keys were sealed under a secret the app no longer has.
158
+ await q.query('DELETE FROM push_outbox WHERE id = $1', [row.id]);
159
+ continue;
160
+ }
161
+ claimed.push({
162
+ id: row.id,
163
+ account: row.account,
164
+ endpoint: row.endpoint,
165
+ message: row.message,
166
+ attempts: Number(row.attempts),
167
+ dueAt: Number(row.due_at),
168
+ expiresAt: Number(row.expires_at),
169
+ subscription: { endpoint: row.endpoint, ...keys },
170
+ });
171
+ }
172
+ return claimed.sort((a, b) => a.dueAt - b.dueAt || a.id.localeCompare(b.id));
173
+ },
174
+
175
+ async done(id) {
176
+ await q.query('DELETE FROM push_outbox WHERE id = $1', [id]);
177
+ },
178
+
179
+ async later(id, at) {
180
+ await q.query('UPDATE push_outbox SET due_at = $2, claimed_until = 0 WHERE id = $1', [
181
+ id,
182
+ at,
183
+ ]);
184
+ },
185
+
186
+ async drop(id) {
187
+ await q.query('DELETE FROM push_outbox WHERE id = $1', [id]);
188
+ },
189
+ };
190
+ }
191
+
192
+ function openKeys(sealed: string): { p256dh: string; auth: string } | undefined {
193
+ try {
194
+ const keys = JSON.parse(open(sealed, PURPOSE)) as { p256dh?: unknown; auth?: unknown };
195
+ return typeof keys.p256dh === 'string' && typeof keys.auth === 'string'
196
+ ? { p256dh: keys.p256dh, auth: keys.auth }
197
+ : undefined;
198
+ } catch {
199
+ return undefined;
200
+ }
201
+ }
202
+
203
+ /** Sends what is due now. Safe to call at any time: a pass already running is not doubled in this process, and the lease covers others. */
204
+ let running: Promise<unknown> | undefined;
205
+ export function sendDuePushes(): Promise<unknown> {
206
+ running ??= runPushOutbox({ store: pushStore(), settings: appPush(), now: Date.now() })
207
+ .catch(() => undefined)
208
+ .finally(() => {
209
+ running = undefined;
210
+ });
211
+ return running;
212
+ }
213
+
214
+ const OUTBOX_INTERVAL_MS = 15_000;
215
+ const started = Symbol.for('__NAME__.push-outbox');
216
+
217
+ /**
218
+ * Called once at start-up (instrumentation.ts): reads the key, so a key or contact that is wrong stops the app here, and then sends
219
+ * waiting pushes every fifteen seconds.
220
+ */
221
+ export function startPushOutbox(): void {
222
+ if (!appPush()) return;
223
+ const global = globalThis as { [started]?: true };
224
+ if (global[started]) return;
225
+ global[started] = true;
226
+ setInterval(() => void sendDuePushes(), OUTBOX_INTERVAL_MS).unref();
227
+ }
@@ -0,0 +1,40 @@
1
+ import { headers } from 'next/headers';
2
+ import { redirect } from 'next/navigation';
3
+ import { needsCoreCheck, signedInUser } from '@sovereignfs/auth/core';
4
+ import { sessionGuards } from '@sovereignfs/auth/next';
5
+ import { readSession, userOf, type User } from '@sovereignfs/auth/server';
6
+ import { signIn } from './sign-in';
7
+
8
+ /** The signed-in person's session for this request, or nothing (auth.md §6). Every page, action and route reads it here. */
9
+ export async function getSession() {
10
+ const { auth } = await signIn();
11
+ return readSession(auth, await headers());
12
+ }
13
+
14
+ const guards = sessionGuards({
15
+ getSession,
16
+ // A session that came from core is checked against it at most an hour after the last check (sdk §9.7).
17
+ onPage: async (session) => {
18
+ const { database, ways } = await signIn();
19
+ if (ways.core && (await needsCoreCheck(database, session.session.id))) {
20
+ redirect('/api/auth/sign-in/sovereign?prompt=none');
21
+ }
22
+ },
23
+ });
24
+
25
+ /** The guard of every page that needs someone signed in: their session, or the sign-in page with the way back. */
26
+ export const requireSignedIn = guards.requireSignedIn;
27
+
28
+ /** For the sign-in and sign-up pages: someone already signed in goes on. */
29
+ export const sendOnIfSignedIn = guards.sendOnIfSignedIn;
30
+
31
+ /**
32
+ * Who is signed in, typed (sdk §9.9): `id` is this app's id for them, and with core as a way in, `sub` and the roles core signed
33
+ * for one who came through it. Read people from this rather than from the session's raw fields.
34
+ */
35
+ export async function userOfSession(
36
+ session: NonNullable<Awaited<ReturnType<typeof getSession>>>,
37
+ ): Promise<User> {
38
+ const { database, ways } = await signIn();
39
+ return ways.core ? signedInUser(database, session) : userOf(session.user);
40
+ }
@@ -0,0 +1,22 @@
1
+ 'use client';
2
+
3
+ import {
4
+ saltReader,
5
+ SIGN_IN_CLIENT,
6
+ SIGN_IN_USER_FIELDS,
7
+ signInClientPlugins,
8
+ signInDerivation,
9
+ } from '@sovereignfs/auth/client';
10
+ import { inferAdditionalFields } from 'better-auth/client/plugins';
11
+ import { createAuthClient } from 'better-auth/react';
12
+
13
+ /** The browser's client for the app's sign-in (auth.md §2): better-auth's, with the package's plugins. */
14
+ export const authClient = createAuthClient({
15
+ ...SIGN_IN_CLIENT,
16
+ plugins: [...signInClientPlugins(), inferAdditionalFields({ user: { ...SIGN_IN_USER_FIELDS } })],
17
+ });
18
+
19
+ /** The sign-in value, made in the page from the password, the address and the app's salt: the password never leaves the browser. */
20
+ export const { deriveForSignIn, signInValue } = signInDerivation(
21
+ saltReader('/api/sign-in-salt', 'vaultId'),
22
+ );
@@ -0,0 +1,113 @@
1
+ import { betterAuth } from 'better-auth';
2
+ import { nextCookies } from 'better-auth/next-js';
3
+ import {
4
+ coreSignInMigrations,
5
+ CORE_SIGN_IN_MIGRATIONS_TABLE,
6
+ sovereignSignIn,
7
+ } from '@sovereignfs/auth/core';
8
+ import { postgresDatabase } from '@sovereignfs/auth/postgres';
9
+ import {
10
+ ACCOUNT_MIGRATIONS_TABLE,
11
+ accountMigrations,
12
+ accountTables,
13
+ createAuthPreset,
14
+ resolveAuthSettings,
15
+ resolveWaysIn,
16
+ runMigrations,
17
+ signUpPolicy,
18
+ } from '@sovereignfs/auth/server';
19
+ import { AppVault, VAULT_MIGRATIONS_TABLE, vaultMigrations } from '@sovereignfs/sdk/vault';
20
+ import { required, setting } from './config';
21
+ import { db } from './db';
22
+ import { sovereign } from './sovereign';
23
+
24
+ /** How this app signs people in (`@sovereignfs/auth`, auth.md §5): accounts of its own, core, or both, from its settings. */
25
+ export function waysIn() {
26
+ return resolveWaysIn({
27
+ local: setting('__PREFIX___AUTH_LOCAL'),
28
+ signUp: setting('__PREFIX___AUTH_SIGNUP'),
29
+ coreUrl: setting('__PREFIX___CORE_URL'),
30
+ });
31
+ }
32
+
33
+ /** The password policy and the rest of the sign-in's settings, read with the app's prefix (auth.md §5). */
34
+ export function signInSettings() {
35
+ const list = (name: string) =>
36
+ (setting(name) ?? '')
37
+ .split(',')
38
+ .map((entry) => entry.trim())
39
+ .filter(Boolean);
40
+ const number = (name: string, fallback: number) => Number(setting(name) ?? fallback) || fallback;
41
+ return resolveAuthSettings(
42
+ {
43
+ url: required('__PREFIX___URL'),
44
+ authSecret: { reveal: () => required('__PREFIX___AUTH_SECRET') },
45
+ authTrustedOrigins: list('__PREFIX___AUTH_TRUSTED_ORIGINS'),
46
+ authTrustedProxies: list('__PREFIX___AUTH_TRUSTED_PROXIES'),
47
+ authCookieDomain: undefined,
48
+ authPasswordMinLength: number('__PREFIX___AUTH_PASSWORD_MIN_LENGTH', 8),
49
+ authPasswordRequireUppercase: false,
50
+ authPasswordRequireLowercase: false,
51
+ authPasswordRequireNumber: false,
52
+ authPasswordRequireSymbol: false,
53
+ authRequireEmailVerification: false,
54
+ authWebauthnRpId: undefined,
55
+ authWebauthnRpName: '__TITLE__',
56
+ authWebauthnOrigin: [],
57
+ },
58
+ { prefix: '__PREFIX__', appName: '__TITLE__' },
59
+ );
60
+ }
61
+
62
+ async function make() {
63
+ const database = await postgresDatabase(db());
64
+ const ways = waysIn();
65
+ const settings = signInSettings();
66
+ const auth = betterAuth(
67
+ createAuthPreset({
68
+ appName: '__TITLE__',
69
+ database,
70
+ tables: accountTables('postgres'),
71
+ settings,
72
+ // This app sends no mail, so it cannot verify an address or send a reset link, and says so before anything is looked up.
73
+ mail: {
74
+ unavailable: () => Promise.resolve('This app does not send mail.'),
75
+ verification: () => Promise.resolve(),
76
+ passwordReset: () => Promise.resolve(),
77
+ accountCreated: () => Promise.resolve(),
78
+ },
79
+ registration: signUpPolicy(database, ways.signUp === 'open' ? 'open' : 'closed'),
80
+ localAccounts: ways.local,
81
+ plugins: [
82
+ ...(ways.core ? [sovereignSignIn({ sovereign: sovereign(), database })] : []),
83
+ // Last: it turns the cookies a server action sets into the response's.
84
+ nextCookies(),
85
+ ],
86
+ }),
87
+ );
88
+ return { auth, database, ways, vault: new AppVault(database) };
89
+ }
90
+
91
+ let made: ReturnType<typeof make> | undefined;
92
+
93
+ /** The app's sign-in for this process: its better-auth on the package's preset, its database, its ways in and its vault. */
94
+ export function signIn(): ReturnType<typeof make> {
95
+ made ??= make().catch((error: unknown) => {
96
+ made = undefined;
97
+ throw error;
98
+ });
99
+ return made;
100
+ }
101
+
102
+ /** The sign-in's tables, under their own histories (auth.md §10), after the app's own migrations. */
103
+ export async function migrateSignIn(): Promise<void> {
104
+ const { database, ways } = await signIn();
105
+ await runMigrations(database, accountMigrations('postgres'), { table: ACCOUNT_MIGRATIONS_TABLE });
106
+ if (ways.core) {
107
+ await runMigrations(database, coreSignInMigrations('postgres'), {
108
+ table: CORE_SIGN_IN_MIGRATIONS_TABLE,
109
+ });
110
+ }
111
+ // The vault id is the salt of the sign-in value (sdk §9.5): the same one the app's vault uses if it adds encryption.
112
+ await runMigrations(database, vaultMigrations('postgres'), { table: VAULT_MIGRATIONS_TABLE });
113
+ }
@@ -4,18 +4,19 @@ import { sessionStore, tokenStore } from './stores';
4
4
  let client: Sovereign | undefined;
5
5
 
6
6
  /**
7
- * The one client for this process. It reads __PREFIX___URL, __PREFIX___CORE_URL, __PREFIX___CORE_CLIENT_ID and __PREFIX___CORE_CLIENT_SECRET,
8
- * makes no call to core, and is made when first used, so building the app needs none of them.
9
- *
10
- * A person's session here is checked against core every hour: the next page they open after that goes through core, which shows
11
- * nothing while they are still signed in there and asks them to sign in when they are not, and brings their name and roles up to date.
7
+ * The one client for this process, when the app signs people in through core. It reads __PREFIX___URL, __PREFIX___CORE_URL,
8
+ * __PREFIX___CORE_CLIENT_ID and __PREFIX___CORE_CLIENT_SECRET, makes no call to core, and is made when first used, so building the app
9
+ * needs none of them. Signing in through core is `@sovereignfs/auth/core` on it; the session is the app's own (lib/sign-in.ts), and a
10
+ * session from core is checked against it every hour (lib/session.ts).
12
11
  */
13
12
  export function sovereign(): Sovereign {
14
13
  client ??= createSovereign({
15
14
  prefix: '__PREFIX__',
15
+ // The addresses `@sovereignfs/auth/core` answers at (auth.md §8); the pending sign-in stays in the SDK's store.
16
+ redirectPath: '/api/auth/callback/sovereign',
17
+ postLogoutPath: '/sign-in',
16
18
  sessionStore,
17
19
  tokenStore,
18
- checkEverySeconds: 60 * 60,
19
20
  });
20
21
  return client;
21
22
  }
@@ -0,0 +1,24 @@
1
+ -- Web Push (@sovereignfs/push): the devices that get notifications, each for the account that turned them on, and the pushes waiting to
2
+ -- be sent. A device's keys are sealed by the app (lib/crypto.ts); a waiting push names its device and goes with it.
3
+
4
+ CREATE TABLE push_devices (
5
+ endpoint text PRIMARY KEY,
6
+ account text NOT NULL,
7
+ keys text NOT NULL,
8
+ saved_at bigint NOT NULL
9
+ );
10
+ CREATE INDEX push_devices_account ON push_devices (account, saved_at);
11
+
12
+ CREATE TABLE push_outbox (
13
+ id text PRIMARY KEY,
14
+ account text NOT NULL,
15
+ endpoint text NOT NULL REFERENCES push_devices (endpoint) ON DELETE CASCADE,
16
+ message jsonb NOT NULL,
17
+ attempts integer NOT NULL DEFAULT 0,
18
+ due_at bigint NOT NULL,
19
+ claimed_until bigint NOT NULL DEFAULT 0,
20
+ expires_at bigint NOT NULL
21
+ );
22
+ CREATE INDEX push_outbox_due ON push_outbox (due_at, claimed_until);
23
+ CREATE INDEX push_outbox_endpoint ON push_outbox (endpoint);
24
+ CREATE INDEX push_outbox_account ON push_outbox (account);
@@ -1,5 +1,5 @@
1
1
  {
2
- "manifest": 3,
2
+ "manifest": 5,
3
3
  "prefix": "__PREFIX_LOWER__",
4
4
  "name": "__TITLE__",
5
5
  "description": "Notes, as a starting point for an app on a Sovereign instance",
@@ -8,14 +8,17 @@
8
8
  "icon": "/pwa-icon/192",
9
9
  "launch": "/",
10
10
  "signIn": {
11
- "redirect": ["/auth/callback"],
12
- "postLogout": ["/"],
13
- "backChannel": "/auth/backchannel-logout",
14
- "accountDeleted": "/auth/account-deleted",
11
+ "redirect": ["/api/auth/callback/sovereign"],
12
+ "postLogout": ["/sign-in"],
13
+ "backChannel": "/api/sovereign/backchannel-logout",
14
+ "accountDeleted": "/api/sovereign/account-deleted",
15
+ "export": "/api/sovereign/export",
15
16
  "scopes": ["openid", "profile", "email", "offline_access"]
16
17
  },
17
- "database": { "pooling": "transaction" },
18
+ "database": {
19
+ "pooling": "transaction"
20
+ },
18
21
  "storage": true,
19
- "generate": ["__PREFIX___AUTH_SECRET"],
20
- "core": ">=0.49.0 <1.0.0"
22
+ "generate": ["__PREFIX___AUTH_SECRET", { "name": "__PREFIX___VAPID_PRIVATE_KEY", "bytes": 32 }],
23
+ "core": ">=0.126.0 <1.0.0"
21
24
  }
@@ -0,0 +1,27 @@
1
+ # What the instance gives this app (contracts/app-manifest.md §3), for running it on your own machine against a core you can reach.
2
+ # A secret may be given as NAME_FILE=/path instead of NAME=value.
3
+ __PREFIX___URL=http://localhost:__PORT__
4
+ __PREFIX___CORE_URL=https://core.sovereign.local
5
+ __PREFIX___CORE_CLIENT_ID=
6
+ __PREFIX___CORE_CLIENT_SECRET=
7
+ __PREFIX___DB_DIALECT=postgres
8
+ __PREFIX___POSTGRES_URL=postgres://user:password@localhost:5432/__NAME__
9
+ # The same database on the server itself, never behind a pooler: the migrations and the token lock use it. Without it, the line above is used.
10
+ __PREFIX___POSTGRES_DIRECT_URL=postgres://user:password@localhost:5432/__NAME__
11
+ # The most connections the app may hold in all (2 or more), 2 of them for the direct address. An instance sets it, and limits the app's
12
+ # database role to that number plus 2. Without it, 10.
13
+ __PREFIX___POSTGRES_POOL_MAX=10
14
+ __PREFIX___AUTH_SECRET=change-me-to-something-long-and-random
15
+ # People's files (contracts/app-manifest.md §2.7). An instance mounts this app's folder at /data/s3/__NAME__ and sets these; running it yourself,
16
+ # the folder is here (docker compose mounts a volume at /data/s3/__NAME__ instead). Each person's quota: megabytes and files.
17
+ __PREFIX___STORAGE_DRIVER=fs
18
+ __PREFIX___STORAGE_PATH=./data/s3/__NAME__
19
+ __PREFIX___STORAGE_QUOTA_MB=204800
20
+ __PREFIX___STORAGE_FILE_QUOTA=1000
21
+ # Signs the addresses that serve a file without a session, for a few minutes. At least 32 characters. An instance makes its own.
22
+ __PREFIX___STORAGE_SIGNING_KEY=change-me-to-something-at-least-thirty-two-characters
23
+ # Notifications (Web Push, @sovereignfs/push): the app's key, 32 bytes in URL-safe base64. An instance makes its own; running it yourself,
24
+ # make one with `npx @sovereignfs/push keys`. Empty: the app sends no notifications.
25
+ __PREFIX___VAPID_PRIVATE_KEY=
26
+ # Whom the browsers' push services may contact about this app: mailto: or https:, never localhost. Empty: __PREFIX___URL, when that is https.
27
+ __PREFIX___VAPID_SUBJECT=
@@ -0,0 +1,18 @@
1
+ # The base app's files an app with --encryption leaves out: it signs in through core with the SDK's nextAuth, as before, until the
2
+ # sign-in package carries encryption's key secret (auth.md §8). One path to a line.
3
+ lib/sign-in.ts
4
+ lib/session.ts
5
+ lib/sign-in-client.ts
6
+ lib/notices.ts
7
+ app/sign-in/page.tsx
8
+ app/sign-in/panel.tsx
9
+ app/sign-up/page.tsx
10
+ app/sign-up/panel.tsx
11
+ app/security/page.tsx
12
+ app/security/panels.tsx
13
+ app/security/actions.ts
14
+ app/api/auth/[...all]/route.ts
15
+ app/api/sovereign/backchannel-logout/route.ts
16
+ app/api/sovereign/account-deleted/route.ts
17
+ app/api/sovereign/export/route.ts
18
+ app/api/sign-in-salt/route.ts
@@ -0,0 +1,45 @@
1
+ import { auth } from '@/lib/auth';
2
+ import { failure, files, refuseCrossOrigin, unauthorised } from '@/lib/files';
3
+
4
+ export const dynamic = 'force-dynamic';
5
+
6
+ type Context = { params: Promise<{ id: string }> };
7
+
8
+ /** One file, to its owner: to their session, or through an address signed for them that has not run out. Someone else's is not found. */
9
+ export async function GET(request: Request, { params }: Context) {
10
+ const { id } = await params;
11
+ const query = new URL(request.url).searchParams;
12
+ const sub = query.has('signature')
13
+ ? files().signedFor(id, query)
14
+ : (await auth().getSession())?.sub;
15
+ if (!sub) return query.has('signature') ? expired() : unauthorised();
16
+ try {
17
+ return await files().serve(sub, id, request);
18
+ } catch (error) {
19
+ const known = failure(error);
20
+ if (known) return known;
21
+ throw error;
22
+ }
23
+ }
24
+
25
+ /** Deletes one of the signed-in person's files and gives its space back. */
26
+ export async function DELETE(request: Request, { params }: Context) {
27
+ const refused = refuseCrossOrigin(request);
28
+ if (refused) return refused;
29
+ const session = await auth().getSession();
30
+ if (!session) return unauthorised();
31
+ try {
32
+ await files().remove(session.sub, (await params).id);
33
+ return new Response(null, { status: 204 });
34
+ } catch (error) {
35
+ const known = failure(error);
36
+ if (known) return known;
37
+ throw error;
38
+ }
39
+ }
40
+
41
+ const expired = () =>
42
+ Response.json(
43
+ { error: 'expired', message: 'This link has run out. Open the file again from the app.' },
44
+ { status: 403 },
45
+ );