@feltdb/feltkit 0.3.17 → 0.3.18
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/dist/app.d.ts +195 -5
- package/dist/app.js +150 -3
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.d.ts +45 -0
- package/dist/appboundry/build.js +52 -1
- package/dist/appboundry/build.js.map +1 -1
- package/dist/appboundry/guest.js +39 -1
- package/dist/appboundry/guest.js.map +1 -1
- package/dist/appboundry/host.js +4 -0
- package/dist/appboundry/host.js.map +1 -1
- package/dist/authorize.js +1 -0
- package/dist/authorize.js.map +1 -1
- package/dist/cli/deploy-appboundry-self-hosted.d.ts +2 -0
- package/dist/cli/deploy-appboundry-self-hosted.js +1 -1
- package/dist/cli/deploy-appboundry-self-hosted.js.map +1 -1
- package/dist/cli/deploy-appboundry.js +3 -0
- package/dist/cli/deploy-appboundry.js.map +1 -1
- package/dist/cli/main.js +6 -1
- package/dist/cli/main.js.map +1 -1
- package/dist/client/index.d.ts +192 -5
- package/dist/client/index.js +301 -28
- package/dist/client/index.js.map +1 -1
- package/dist/docs.d.ts +1 -1
- package/dist/docs.js +1 -0
- package/dist/docs.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js.map +1 -1
- package/dist/react/auth.d.ts +131 -0
- package/dist/react/auth.js +830 -0
- package/dist/react/auth.js.map +1 -0
- package/dist/react/context.d.ts +8 -0
- package/dist/react/context.js +14 -0
- package/dist/react/context.js.map +1 -0
- package/dist/react/index.d.ts +3 -18
- package/dist/react/index.js +5 -13
- package/dist/react/index.js.map +1 -1
- package/dist/runtime/accounts.d.ts +33 -2
- package/dist/runtime/accounts.js +167 -27
- package/dist/runtime/accounts.js.map +1 -1
- package/dist/runtime/authority.d.ts +8 -1
- package/dist/runtime/authority.js +11 -2
- package/dist/runtime/authority.js.map +1 -1
- package/dist/runtime/challenges.d.ts +51 -0
- package/dist/runtime/challenges.js +121 -0
- package/dist/runtime/challenges.js.map +1 -0
- package/dist/runtime/changes.d.ts +22 -0
- package/dist/runtime/changes.js +51 -3
- package/dist/runtime/changes.js.map +1 -1
- package/dist/runtime/context.d.ts +41 -0
- package/dist/runtime/contract.js +14 -3
- package/dist/runtime/contract.js.map +1 -1
- package/dist/runtime/data.d.ts +36 -2
- package/dist/runtime/data.js +56 -17
- package/dist/runtime/data.js.map +1 -1
- package/dist/runtime/live.d.ts +48 -0
- package/dist/runtime/live.js +154 -0
- package/dist/runtime/live.js.map +1 -0
- package/dist/runtime/outbox.js +3 -0
- package/dist/runtime/outbox.js.map +1 -1
- package/dist/runtime/runtime.d.ts +70 -5
- package/dist/runtime/runtime.js +290 -35
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/search.d.ts +54 -0
- package/dist/runtime/search.js +66 -0
- package/dist/runtime/search.js.map +1 -0
- package/dist/runtime/sessions.d.ts +16 -2
- package/dist/runtime/sessions.js +40 -4
- package/dist/runtime/sessions.js.map +1 -1
- package/dist/runtime/tenancy.d.ts +189 -0
- package/dist/runtime/tenancy.js +376 -0
- package/dist/runtime/tenancy.js.map +1 -0
- package/dist/runtime/tenant-scope.d.ts +9 -0
- package/dist/runtime/tenant-scope.js +127 -0
- package/dist/runtime/tenant-scope.js.map +1 -0
- package/dist/runtime/transactions.d.ts +45 -2
- package/dist/runtime/transactions.js +36 -9
- package/dist/runtime/transactions.js.map +1 -1
- package/dist/server/index.d.ts +2 -1
- package/dist/server/index.js +300 -58
- package/dist/server/index.js.map +1 -1
- package/dist/server/mcp.js +6 -3
- package/dist/server/mcp.js.map +1 -1
- package/dist/server/session-http.d.ts +48 -0
- package/dist/server/session-http.js +116 -0
- package/dist/server/session-http.js.map +1 -0
- package/dist/server/tenancy.d.ts +40 -0
- package/dist/server/tenancy.js +191 -0
- package/dist/server/tenancy.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.js +7 -2
- package/dist/testing/index.js.map +1 -1
- package/docs/AGENT-OPERATIONS.md +1 -0
- package/docs/APPBOUNDRY.md +11 -1
- package/docs/ARCHITECTURE.md +4 -2
- package/docs/AUTH.md +262 -0
- package/docs/GUARANTEES.md +50 -3
- package/docs/README.md +3 -2
- package/docs/SECURITY.md +3 -2
- package/docs/TRANSACTIONS.md +98 -1
- package/docs/UPSTREAM-GAPS.md +2 -0
- package/package.json +11 -10
- package/skills/.claude-plugin/marketplace.json +1 -1
- package/skills/.claude-plugin/plugin.json +1 -1
- package/skills/feltkit-data/SKILL.md +6 -0
- package/dist/runtime/account-links.d.ts +0 -19
- package/dist/runtime/account-links.js +0 -45
- package/dist/runtime/account-links.js.map +0 -1
package/dist/server/index.js
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
*
|
|
4
4
|
* POST /api/query/<name> run a query { args } → { ok, value, reads }
|
|
5
5
|
* POST /api/mutation/<name> run a mutation { args } → { ok, value }
|
|
6
|
-
* GET /api/events change stream (SSE): which collections changed
|
|
6
|
+
* GET /api/events change stream (SSE): which collections changed, with opaque
|
|
7
|
+
* keys of the changed records' keyed values (runtime/live.ts)
|
|
7
8
|
* GET /api/session who am I
|
|
8
9
|
* POST /api/auth/dev development sign-in as a declared dev user
|
|
9
10
|
* POST /api/auth/signout
|
|
@@ -28,10 +29,14 @@ import { FELTKIT_MARK_DATA_URI } from "./brand.js";
|
|
|
28
29
|
import { embeddedManagement, startManagementConsole } from "./management.js";
|
|
29
30
|
import { handleAdmin } from "./admin.js";
|
|
30
31
|
import { handleMcp } from "./mcp.js";
|
|
31
|
-
import {
|
|
32
|
+
import { normalizeEmail } from "../runtime/accounts.js";
|
|
32
33
|
import { handleProvider, signInProviders } from "./oauth.js";
|
|
34
|
+
import { handleTenancy } from "./tenancy.js";
|
|
35
|
+
import { MEMBERSHIPS_COLLECTION } from "../runtime/tenancy.js";
|
|
36
|
+
import { checkCookieRequest, clearSessionCookie, clientAddress, cookieToken, csrfToken, setSessionCookie, wantsCookie } from "./session-http.js";
|
|
33
37
|
import { bearerToken, headerRecord, isLoopbackHost, readBytes, readJSON, safeEqual, securityHeaders, sendError, sendJSON, startSSE } from "./http.js";
|
|
34
38
|
import { FILE_CONTENT_COLLECTION } from "../runtime/services.js";
|
|
39
|
+
import { changeKeys } from "../runtime/live.js";
|
|
35
40
|
const CONTENT_TYPES = {
|
|
36
41
|
".html": "text/html; charset=utf-8",
|
|
37
42
|
".js": "text/javascript; charset=utf-8",
|
|
@@ -87,7 +92,40 @@ export function dashboardPolicy(dir) {
|
|
|
87
92
|
return policy;
|
|
88
93
|
}
|
|
89
94
|
/** Collections a browser may learn changed: the app's own, plus service collections functions read. */
|
|
95
|
+
/**
|
|
96
|
+
* One change event as one subscriber receives it (runtime/live.ts). Collections the change feed
|
|
97
|
+
* described record by record get opaque keys instead of being re-run wholesale; for a tenant-scoped
|
|
98
|
+
* collection, records of other tenants are withheld (a collection none of whose changed records
|
|
99
|
+
* belongs to the subscriber's tenant is not sent at all). A collection without details is sent by
|
|
100
|
+
* name, as before. No field value is ever sent.
|
|
101
|
+
*/
|
|
102
|
+
function liveChange(runtime, event, visible, tenant) {
|
|
103
|
+
if (event.collections.includes("*"))
|
|
104
|
+
return { collections: ["*"], withheld: false };
|
|
105
|
+
const collections = [];
|
|
106
|
+
const keys = {};
|
|
107
|
+
let withheld = false;
|
|
108
|
+
for (const collection of event.collections) {
|
|
109
|
+
if (!visible.has(collection))
|
|
110
|
+
continue;
|
|
111
|
+
const records = event.details?.[collection];
|
|
112
|
+
if (!records) {
|
|
113
|
+
collections.push(collection);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
const field = runtime.app.collections.get(collection)?.tenant?.field;
|
|
117
|
+
const kept = field ? records.filter((r) => tenant !== null && (r.before?.[field] === tenant || r.after?.[field] === tenant)) : records;
|
|
118
|
+
if (kept.length < records.length)
|
|
119
|
+
withheld = true;
|
|
120
|
+
if (!kept.length)
|
|
121
|
+
continue;
|
|
122
|
+
collections.push(collection);
|
|
123
|
+
keys[collection] = [...new Set(kept.flatMap((record) => changeKeys(collection, record)))];
|
|
124
|
+
}
|
|
125
|
+
return { collections, ...(Object.keys(keys).length ? { keys } : {}), withheld };
|
|
126
|
+
}
|
|
90
127
|
function publicCollections(runtime) {
|
|
128
|
+
// Memberships are not here: they are sent only to their own tenant and principal (see /api/events).
|
|
91
129
|
return new Set([...runtime.app.collections.keys(), "files", FILE_CONTENT_COLLECTION, "notifications", "ConfigurationVariables"]);
|
|
92
130
|
}
|
|
93
131
|
export async function startServer(options) {
|
|
@@ -97,19 +135,28 @@ export async function startServer(options) {
|
|
|
97
135
|
const production = runtime.environment.production;
|
|
98
136
|
const dashboard = options.dashboard?.enabled && options.dashboard.adminToken ? options.dashboard : null;
|
|
99
137
|
let url = "";
|
|
100
|
-
const mailBudget = new SendBudget();
|
|
101
138
|
// The packaged AppPort Services pages, on their own loopback origin. Development only.
|
|
102
139
|
const servicesConsole = dashboard && !production ? await startManagementConsole(runtime) : null;
|
|
103
140
|
// The same management contract for Studio's own Services screens. Development only.
|
|
104
141
|
const servicesManagement = dashboard && !production ? embeddedManagement(runtime) : null;
|
|
105
142
|
/** Identity for a request: a FeltKit session token, else the app's authenticate hook. Never a client-supplied claim. */
|
|
143
|
+
const sessionHttp = () => runtime.app.options.auth?.session ?? {};
|
|
106
144
|
const identify = async (request) => {
|
|
107
145
|
const token = bearerToken(request);
|
|
108
146
|
if (token) {
|
|
109
147
|
const principal = await runtime.principalForToken(token);
|
|
110
148
|
if (!principal)
|
|
111
149
|
throw new FeltKitError("UNAUTHORIZED", "The session token is invalid or expired. Sign in again.");
|
|
112
|
-
return { principal, token };
|
|
150
|
+
return { principal, token, transport: "bearer" };
|
|
151
|
+
}
|
|
152
|
+
// A browser's session cookie: an ambient credential, so the request must prove it came from this app.
|
|
153
|
+
const cookie = cookieToken(request);
|
|
154
|
+
if (cookie) {
|
|
155
|
+
const principal = await runtime.principalForToken(cookie);
|
|
156
|
+
if (principal) {
|
|
157
|
+
checkCookieRequest(request, cookie, runtime.authSecret());
|
|
158
|
+
return { principal, token: cookie, transport: "cookie" };
|
|
159
|
+
}
|
|
113
160
|
}
|
|
114
161
|
const hook = runtime.app.options.auth?.authenticate;
|
|
115
162
|
if (hook) {
|
|
@@ -130,8 +177,14 @@ export async function startServer(options) {
|
|
|
130
177
|
const token = typeof auth === "string" && auth.startsWith("Bearer ") ? auth.slice(7).trim() : request.sessionId;
|
|
131
178
|
if (token) {
|
|
132
179
|
const session = await runtime.sessions.get(token);
|
|
133
|
-
if (session)
|
|
134
|
-
|
|
180
|
+
if (session) {
|
|
181
|
+
// The principal as it is now (account sessions are re-resolved), not the copy on the session.
|
|
182
|
+
const current = await runtime.principalForToken(token);
|
|
183
|
+
if (!current)
|
|
184
|
+
return undefined;
|
|
185
|
+
const principal = toAppPortPrincipal(current);
|
|
186
|
+
return { session: { ...session, principal }, principal };
|
|
187
|
+
}
|
|
135
188
|
// An AppPort Services API key (services.apiKeys), holding services.apiKeys.roles.
|
|
136
189
|
const keyed = await runtime.principalForToken(token);
|
|
137
190
|
return keyed ? { principal: toAppPortPrincipal(keyed) } : undefined;
|
|
@@ -152,6 +205,14 @@ export async function startServer(options) {
|
|
|
152
205
|
}
|
|
153
206
|
return binding;
|
|
154
207
|
};
|
|
208
|
+
/** Answer a sign-in: a cookie for the browser client (no token in the body), else the token. */
|
|
209
|
+
const sendSession = (request, response, status, issued, extra = {}) => {
|
|
210
|
+
if (wantsCookie(request)) {
|
|
211
|
+
setSessionCookie(response, request, issued.token, issued.expiresAt, sessionHttp(), production);
|
|
212
|
+
return sendJSON(response, status, { ok: true, principal: issued.principal, expiresAt: issued.expiresAt, csrf: csrfToken(runtime.authSecret(), issued.token), ...extra });
|
|
213
|
+
}
|
|
214
|
+
return sendJSON(response, status, { ok: true, token: issued.token, principal: issued.principal, expiresAt: issued.expiresAt, ...extra });
|
|
215
|
+
};
|
|
155
216
|
const handleApi = async (request, response, pathname) => {
|
|
156
217
|
const method = request.method ?? "GET";
|
|
157
218
|
const match = /^\/api\/(query|mutation)\/(.+)$/.exec(pathname);
|
|
@@ -192,16 +253,29 @@ export async function startServer(options) {
|
|
|
192
253
|
});
|
|
193
254
|
return sendJSON(response, 201, { ok: true, file });
|
|
194
255
|
}
|
|
256
|
+
if (await handleTenancy({ runtime, identify, sendSession }, request, response, pathname))
|
|
257
|
+
return;
|
|
195
258
|
if (pathname === "/api/session" && method === "GET") {
|
|
196
259
|
let principal = null;
|
|
260
|
+
let current = {};
|
|
197
261
|
try {
|
|
198
|
-
|
|
262
|
+
const found = await identify(request);
|
|
263
|
+
principal = found.principal;
|
|
264
|
+
current = found;
|
|
199
265
|
}
|
|
200
266
|
catch {
|
|
201
267
|
principal = null;
|
|
202
268
|
}
|
|
269
|
+
// A cookie whose session expired or was revoked: drop it, so the browser stops sending it.
|
|
270
|
+
if (!principal && cookieToken(request))
|
|
271
|
+
clearSessionCookie(response);
|
|
203
272
|
return sendJSON(response, 200, {
|
|
204
273
|
principal,
|
|
274
|
+
// The page's CSRF token (cookie sessions): sent back as X-FeltKit-CSRF on every unsafe request.
|
|
275
|
+
...(current.transport === "cookie" && current.token ? { csrf: csrfToken(runtime.authSecret(), current.token) } : {}),
|
|
276
|
+
transport: current.transport ?? null,
|
|
277
|
+
tenant: principal?.tenant ?? null,
|
|
278
|
+
tenancy: runtime.tenancy ? { name: runtime.tenancy.config.name ?? "workspace", roles: runtime.tenancy.roles } : null,
|
|
205
279
|
permissions: runtime.authority.permissionsFor(principal),
|
|
206
280
|
application: runtime.app.name,
|
|
207
281
|
environment: { name: runtime.environment.name, production },
|
|
@@ -216,28 +290,42 @@ export async function startServer(options) {
|
|
|
216
290
|
const accounts = runtime.accounts;
|
|
217
291
|
if (!accounts)
|
|
218
292
|
throw new FeltKitError("NOT_FOUND", "This app has no accounts.");
|
|
293
|
+
if (runtime.app.options.auth?.accounts?.password === false)
|
|
294
|
+
throw new FeltKitError("NOT_FOUND", "Password sign-in is not enabled for this app.");
|
|
219
295
|
const body = await readJSON(request);
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
|
|
296
|
+
const caller = clientAddress(request, sessionHttp());
|
|
297
|
+
let account;
|
|
298
|
+
try {
|
|
299
|
+
account = pathname === "/api/auth/signup" ? await accounts.signUp({ email: body.email, password: body.password, name: body.name }) : await accounts.signIn({ email: body.email, password: body.password }, caller);
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
// With verification required, sign-up answers the same for a taken address as for a new one
|
|
303
|
+
// (no enumeration): the address's owner gets a password-reset link instead, which is harmless.
|
|
304
|
+
if (pathname === "/api/auth/signup" && accounts.requireVerified && runtime.mail && error instanceof FeltKitError && error.code === "CONFLICT") {
|
|
305
|
+
const existing = await accounts.findByEmail(body.email);
|
|
306
|
+
if (existing && !existing.disabled)
|
|
307
|
+
await runtime.sendChallenge({ purpose: "reset", subject: existing.id, recipient: existing.id }).catch(() => false);
|
|
308
|
+
return sendJSON(response, 201, { ok: true, verificationRequired: true, message: "Check your e-mail: open the link we sent to verify your address, then sign in." });
|
|
309
|
+
}
|
|
310
|
+
throw error;
|
|
311
|
+
}
|
|
223
312
|
// A new account gets its verification e-mail (when the app sends account e-mail).
|
|
224
|
-
if (pathname === "/api/auth/signup" && runtime.mail
|
|
225
|
-
await runtime.
|
|
226
|
-
.sendAccountMail({ recipient: account.id, type: "account.verify-email", title: "Verify your e-mail address", data: { purpose: "verify" }, expiresAt: new Date(Date.now() + 60 * 60_000).toISOString() })
|
|
227
|
-
.catch((error) => runtime.logger.warn(`Could not send the verification e-mail: ${error instanceof Error ? error.message : String(error)}`));
|
|
313
|
+
if (pathname === "/api/auth/signup" && runtime.mail) {
|
|
314
|
+
await runtime.sendChallenge({ purpose: "verify", subject: account.id, recipient: account.id }).catch((error) => runtime.logger.warn(`Could not send the verification e-mail: ${error instanceof Error ? error.message : String(error)}`));
|
|
228
315
|
}
|
|
229
316
|
// Sign-up with required verification: the account exists, and signs in once verified.
|
|
230
317
|
if (pathname === "/api/auth/signup" && accounts.requireVerified) {
|
|
231
318
|
return sendJSON(response, 201, { ok: true, verificationRequired: true, message: "Check your e-mail: open the link we sent to verify your address, then sign in." });
|
|
232
319
|
}
|
|
233
320
|
const issued = await runtime.issueSession({ id: account.id, type: "user", roles: account.roles, displayName: account.name ?? account.email }, { kind: "account", label: pathname === "/api/auth/signup" ? "signed up" : "signed in", via: "http" });
|
|
234
|
-
return
|
|
321
|
+
return sendSession(request, response, pathname === "/api/auth/signup" ? 201 : 200, issued);
|
|
235
322
|
}
|
|
236
323
|
if (pathname.startsWith("/api/auth/providers/") && (await handleProvider(runtime, request, response, pathname, new URL(request.url ?? "/", "http://local"))))
|
|
237
324
|
return;
|
|
238
|
-
// Account e-mail (auth.accounts.email): ask for a verification or
|
|
239
|
-
// A request answers the same whether or not the address has an account
|
|
240
|
-
|
|
325
|
+
// Account e-mail (auth.accounts.email): ask for a verification, reset or sign-in link, then use it.
|
|
326
|
+
// A request answers the same whether or not the address has an account (and whether or not the
|
|
327
|
+
// hourly limit for it was reached).
|
|
328
|
+
const emailAccounts = () => {
|
|
241
329
|
const accounts = runtime.accounts;
|
|
242
330
|
if (!accounts)
|
|
243
331
|
throw new FeltKitError("NOT_FOUND", "This app has no accounts.");
|
|
@@ -245,38 +333,117 @@ export async function startServer(options) {
|
|
|
245
333
|
throw new FeltKitError("NOT_FOUND", "This app sends no account e-mail (auth.accounts.email).");
|
|
246
334
|
if (!runtime.mail)
|
|
247
335
|
throw new FeltKitError("UNAVAILABLE", "Account e-mail is not configured for this deployment.", { hint: "Set MAILPORT_URL and MAILPORT_API_KEY (your Mailerport service)." });
|
|
336
|
+
return accounts;
|
|
337
|
+
};
|
|
338
|
+
if ((pathname === "/api/auth/verify/request" || pathname === "/api/auth/reset/request") && method === "POST") {
|
|
339
|
+
const accounts = emailAccounts();
|
|
248
340
|
const body = await readJSON(request);
|
|
249
341
|
const purpose = pathname === "/api/auth/reset/request" ? "reset" : "verify";
|
|
250
342
|
const account = await accounts.findByEmail(body.email);
|
|
251
|
-
if (account && (purpose === "reset" || !account.emailVerified)
|
|
252
|
-
await runtime.
|
|
253
|
-
recipient: account.id,
|
|
254
|
-
type: purpose === "reset" ? "account.password-reset" : "account.verify-email",
|
|
255
|
-
title: purpose === "reset" ? "Reset your password" : "Verify your e-mail address",
|
|
256
|
-
data: { purpose },
|
|
257
|
-
expiresAt: new Date(Date.now() + 60 * 60_000).toISOString(),
|
|
258
|
-
});
|
|
343
|
+
if (account && !account.disabled && (purpose === "reset" || !account.emailVerified)) {
|
|
344
|
+
await runtime.sendChallenge({ purpose, subject: account.id, recipient: account.id });
|
|
259
345
|
}
|
|
260
346
|
return sendJSON(response, 202, { ok: true, message: purpose === "reset" ? "If an account uses that address, we sent it a link to reset the password." : "If that address has an account to verify, we sent it a link." });
|
|
261
347
|
}
|
|
262
348
|
if ((pathname === "/api/auth/verify" || pathname === "/api/auth/reset") && method === "POST") {
|
|
263
|
-
const accounts =
|
|
264
|
-
if (!accounts || !runtime.app.options.auth?.accounts?.email)
|
|
265
|
-
throw new FeltKitError("NOT_FOUND", "This app sends no account e-mail (auth.accounts.email).");
|
|
349
|
+
const accounts = emailAccounts();
|
|
266
350
|
const body = await readJSON(request);
|
|
267
351
|
const purpose = pathname === "/api/auth/reset" ? "reset" : "verify";
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
readLink(null, purpose);
|
|
352
|
+
if (purpose === "reset")
|
|
353
|
+
accounts.checkNewPassword(body.password); // refuse a bad password before using up the link
|
|
354
|
+
const challenge = await runtime.challenges.redeemToken(body.token, purpose);
|
|
272
355
|
if (purpose === "verify") {
|
|
273
|
-
const account = await accounts.markVerified(
|
|
356
|
+
const account = await accounts.markVerified(challenge.subject);
|
|
357
|
+
runtime.recordAuth("account.verified", null, { subject: account.id });
|
|
274
358
|
return sendJSON(response, 200, { ok: true, email: account.email, emailVerified: true });
|
|
275
359
|
}
|
|
276
|
-
const account = await accounts.setPassword(
|
|
360
|
+
const account = await accounts.setPassword(challenge.subject, body.password);
|
|
277
361
|
await runtime.sessions.revokePrincipal(account.id);
|
|
362
|
+
runtime.recordAuth("account.password-reset", null, { subject: account.id });
|
|
278
363
|
const issued = await runtime.issueSession({ id: account.id, type: "user", roles: account.roles, displayName: account.name ?? account.email }, { kind: "account", label: "password reset", via: "http" });
|
|
279
|
-
return
|
|
364
|
+
return sendSession(request, response, 200, issued);
|
|
365
|
+
}
|
|
366
|
+
// Magic link (auth.accounts.magicLink): an e-mailed link, or its 8-digit code, signs in. A new
|
|
367
|
+
// address gets an account (verified: the link proved it) when sign-up is open.
|
|
368
|
+
if (pathname === "/api/auth/magic/request" && method === "POST") {
|
|
369
|
+
const accounts = emailAccounts();
|
|
370
|
+
if (!runtime.app.options.auth?.accounts?.magicLink)
|
|
371
|
+
throw new FeltKitError("NOT_FOUND", "Sign-in links are not enabled for this app (auth.accounts.magicLink).");
|
|
372
|
+
const body = await readJSON(request);
|
|
373
|
+
const email = normalizeEmail(body.email);
|
|
374
|
+
const account = await accounts.findByEmail(email);
|
|
375
|
+
if (account ? !account.disabled : accounts.signUpOpen) {
|
|
376
|
+
await runtime.sendChallenge({ purpose: "magic-link", subject: `email:${email}`, recipient: account ? account.id : `email:${email}`, data: { email } });
|
|
377
|
+
}
|
|
378
|
+
return sendJSON(response, 202, { ok: true, message: "If that address can sign in here, we sent it a sign-in link and code. They work for 15 minutes." });
|
|
379
|
+
}
|
|
380
|
+
if (pathname === "/api/auth/magic" && method === "POST") {
|
|
381
|
+
const accounts = emailAccounts();
|
|
382
|
+
if (!runtime.app.options.auth?.accounts?.magicLink)
|
|
383
|
+
throw new FeltKitError("NOT_FOUND", "Sign-in links are not enabled for this app (auth.accounts.magicLink).");
|
|
384
|
+
const body = await readJSON(request);
|
|
385
|
+
const challenge = body.token !== undefined
|
|
386
|
+
? await runtime.challenges.redeemToken(body.token, "magic-link")
|
|
387
|
+
: await runtime.challenges.redeemCode(`email:${normalizeEmail(body.email)}`, body.code, "magic-link");
|
|
388
|
+
const account = await accounts.signInWithEmailProof(challenge.data.email);
|
|
389
|
+
runtime.recordAuth("account.signed-in", null, { subject: account.id, method: "magic-link" });
|
|
390
|
+
const issued = await runtime.issueSession({ id: account.id, type: "user", roles: account.roles, displayName: account.name ?? account.email }, { kind: "account", label: "signed in with a link", via: "http" });
|
|
391
|
+
return sendSession(request, response, 200, issued);
|
|
392
|
+
}
|
|
393
|
+
// Your account (auth.accounts): profile, password, address, connected providers.
|
|
394
|
+
if (pathname === "/api/account" || pathname.startsWith("/api/account/")) {
|
|
395
|
+
const accounts = runtime.accounts;
|
|
396
|
+
if (!accounts)
|
|
397
|
+
throw new FeltKitError("NOT_FOUND", "This app has no accounts.");
|
|
398
|
+
// Confirming a new address needs only its link (it may be opened in another browser).
|
|
399
|
+
if (pathname === "/api/account/email/confirm" && method === "POST") {
|
|
400
|
+
const body = await readJSON(request);
|
|
401
|
+
const challenge = await runtime.challenges.redeemToken(body.token, "email-change");
|
|
402
|
+
const account = await accounts.changeEmail(challenge.subject, challenge.data.email);
|
|
403
|
+
runtime.recordAuth("account.email-changed", null, { subject: account.id });
|
|
404
|
+
return sendJSON(response, 200, { ok: true, email: account.email });
|
|
405
|
+
}
|
|
406
|
+
const { principal, token } = await identify(request);
|
|
407
|
+
const account = principal && token ? await accounts.get(principal.id) : null;
|
|
408
|
+
if (!principal || !token || !account)
|
|
409
|
+
throw new FeltKitError("UNAUTHORIZED", "Sign in to manage your account.");
|
|
410
|
+
if (pathname === "/api/account" && method === "GET") {
|
|
411
|
+
return sendJSON(response, 200, { ok: true, account: { ...(await accountView(runtime, account.id)), name: account.name ?? null, providers: account.providers }, available: accountsInfo(runtime) });
|
|
412
|
+
}
|
|
413
|
+
if (pathname === "/api/account/profile" && method === "POST") {
|
|
414
|
+
const body = await readJSON(request);
|
|
415
|
+
const updated = await accounts.updateProfile(account.id, { name: body.name });
|
|
416
|
+
return sendJSON(response, 200, { ok: true, name: updated.name });
|
|
417
|
+
}
|
|
418
|
+
if (pathname === "/api/account/password" && method === "POST") {
|
|
419
|
+
const body = await readJSON(request);
|
|
420
|
+
const updated = await accounts.changePassword(account.id, { current: body.current, password: body.password });
|
|
421
|
+
// Every other session ends, and this one is replaced (rotated): a stolen token stops working.
|
|
422
|
+
await runtime.sessions.revokePrincipal(account.id);
|
|
423
|
+
runtime.recordAuth("account.password-changed", principal, { subject: account.id });
|
|
424
|
+
const issued = await runtime.issueSession({ id: updated.id, type: "user", roles: updated.roles, displayName: updated.name ?? updated.email }, { kind: "account", label: "password changed", via: "http" });
|
|
425
|
+
return sendSession(request, response, 200, issued);
|
|
426
|
+
}
|
|
427
|
+
if (pathname === "/api/account/email" && method === "POST") {
|
|
428
|
+
if (!runtime.app.options.auth?.accounts?.email)
|
|
429
|
+
throw new FeltKitError("NOT_FOUND", "This app sends no account e-mail (auth.accounts.email).");
|
|
430
|
+
const body = await readJSON(request);
|
|
431
|
+
const email = normalizeEmail(body.email);
|
|
432
|
+
if (email === account.email)
|
|
433
|
+
throw new FeltKitError("INVALID_ARGUMENT", "That is already your address.");
|
|
434
|
+
// The same answer whether or not another account uses the address; confirming checks again.
|
|
435
|
+
if (await accounts.addressAvailable(email, account.id)) {
|
|
436
|
+
await runtime.sendChallenge({ purpose: "email-change", subject: account.id, recipient: `email:${email}`, data: { email } });
|
|
437
|
+
}
|
|
438
|
+
return sendJSON(response, 202, { ok: true, message: `We sent a confirmation link to ${email}. Your address changes when you open it.` });
|
|
439
|
+
}
|
|
440
|
+
if (pathname === "/api/account/providers/unlink" && method === "POST") {
|
|
441
|
+
const body = await readJSON(request);
|
|
442
|
+
const updated = await accounts.unlinkProvider(account.id, String(body.provider ?? ""), { magicLink: Boolean(runtime.app.options.auth?.accounts?.magicLink) });
|
|
443
|
+
runtime.recordAuth("account.provider-unlinked", principal, { subject: account.id, provider: String(body.provider) });
|
|
444
|
+
return sendJSON(response, 200, { ok: true, providers: updated.providers });
|
|
445
|
+
}
|
|
446
|
+
throw new FeltKitError("NOT_FOUND", `No API endpoint ${method} ${pathname}.`);
|
|
280
447
|
}
|
|
281
448
|
if (pathname === "/api/auth/dev" && method === "POST") {
|
|
282
449
|
if (!runtime.environment.development)
|
|
@@ -286,14 +453,58 @@ export async function startServer(options) {
|
|
|
286
453
|
if (!user)
|
|
287
454
|
throw new FeltKitError("NOT_FOUND", `No dev user "${String(body.userId)}". Declare dev users in feltkit({ dev: { users } }).`);
|
|
288
455
|
const issued = await runtime.issueSession({ id: user.id, type: user.type ?? "user", roles: user.roles, ...(user.name ? { displayName: user.name } : {}) }, { kind: "dev", label: "development sign-in", via: "http" });
|
|
289
|
-
return
|
|
456
|
+
return sendSession(request, response, 200, issued);
|
|
290
457
|
}
|
|
291
458
|
if (pathname === "/api/auth/signout" && method === "POST") {
|
|
292
|
-
const
|
|
293
|
-
if (
|
|
294
|
-
await runtime.sessions.delete(
|
|
459
|
+
const bearer = bearerToken(request);
|
|
460
|
+
if (bearer)
|
|
461
|
+
await runtime.sessions.delete(bearer);
|
|
462
|
+
else {
|
|
463
|
+
const cookie = cookieToken(request);
|
|
464
|
+
// Signing out needs no CSRF token (another site signing you out is a nuisance, not a takeover),
|
|
465
|
+
// but a foreign Origin is still refused.
|
|
466
|
+
if (cookie) {
|
|
467
|
+
checkCookieRequest(request, cookie, runtime.authSecret(), { token: false });
|
|
468
|
+
await runtime.sessions.delete(cookie);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
clearSessionCookie(response);
|
|
295
472
|
return sendJSON(response, 200, { ok: true });
|
|
296
473
|
}
|
|
474
|
+
// A bearer session from an older client becomes this browser's cookie (and leaves script-readable storage).
|
|
475
|
+
if (pathname === "/api/auth/cookie" && method === "POST") {
|
|
476
|
+
const bearer = bearerToken(request);
|
|
477
|
+
const principal = bearer ? await runtime.principalForToken(bearer) : null;
|
|
478
|
+
if (!bearer || !principal)
|
|
479
|
+
throw new FeltKitError("UNAUTHORIZED", "The session token is invalid or expired. Sign in again.");
|
|
480
|
+
const session = await runtime.sessions.get(bearer);
|
|
481
|
+
setSessionCookie(response, request, bearer, session?.expiresAt, sessionHttp(), production);
|
|
482
|
+
return sendJSON(response, 200, { ok: true, principal, csrf: csrfToken(runtime.authSecret(), bearer) });
|
|
483
|
+
}
|
|
484
|
+
// Your own sessions: list them, end one, or end all of them (optionally keeping this one).
|
|
485
|
+
if (pathname === "/api/auth/sessions" && method === "GET") {
|
|
486
|
+
const { principal, token } = await identify(request);
|
|
487
|
+
if (!principal || !token)
|
|
488
|
+
throw new FeltKitError("UNAUTHORIZED", "Sign in to see your sessions.");
|
|
489
|
+
return sendJSON(response, 200, { ok: true, sessions: await runtime.sessions.listFor(principal.id, token) });
|
|
490
|
+
}
|
|
491
|
+
if (pathname === "/api/auth/sessions/revoke" && method === "POST") {
|
|
492
|
+
const { principal, token } = await identify(request);
|
|
493
|
+
if (!principal || !token)
|
|
494
|
+
throw new FeltKitError("UNAUTHORIZED", "Sign in to manage your sessions.");
|
|
495
|
+
const body = await readJSON(request);
|
|
496
|
+
const everywhere = body.all === true;
|
|
497
|
+
const revoked = everywhere
|
|
498
|
+
? await runtime.sessions.revokePrincipal(principal.id, body.keepCurrent === true ? token : undefined)
|
|
499
|
+
: await runtime.sessions.revokeOwn(principal.id, String(body.ref ?? ""));
|
|
500
|
+
if (!everywhere && revoked === 0)
|
|
501
|
+
throw new FeltKitError("NOT_FOUND", "No such session.");
|
|
502
|
+
runtime.recordAuth("session.revoked", principal, { count: revoked, scope: everywhere ? (body.keepCurrent === true ? "others" : "all") : "one" });
|
|
503
|
+
const endedCurrent = everywhere ? body.keepCurrent !== true : (await runtime.sessions.get(token)) === undefined;
|
|
504
|
+
if (endedCurrent)
|
|
505
|
+
clearSessionCookie(response);
|
|
506
|
+
return sendJSON(response, 200, { ok: true, revoked, signedOut: endedCurrent });
|
|
507
|
+
}
|
|
297
508
|
if (pathname === "/api/events" && method === "GET") {
|
|
298
509
|
// Change notifications reveal when data changes. They go to signed-in callers, or to
|
|
299
510
|
// anyone when the application has a public query (which anonymous clients may watch).
|
|
@@ -304,14 +515,48 @@ export async function startServer(options) {
|
|
|
304
515
|
const visible = publicCollections(runtime);
|
|
305
516
|
const stream = startSSE(response);
|
|
306
517
|
stream.send("ready", { sequence: runtime.changes.position, generation: runtime.generation });
|
|
518
|
+
// Tenant-scoped collections: only changes to records of the subscriber's tenant are sent. The
|
|
519
|
+
// tenant is the session's when the stream opened; the session can switch elsewhere (another
|
|
520
|
+
// tab), so whenever a change is withheld the session is looked up again (at most every 2 s),
|
|
521
|
+
// and a switch is answered with "*" (re-run everything), so nothing visible is ever missed.
|
|
522
|
+
let tenant = principal?.tenant?.id ?? null;
|
|
523
|
+
let closed = false;
|
|
524
|
+
let recheck;
|
|
525
|
+
let lastCheck = Date.now();
|
|
526
|
+
const scheduleRecheck = () => {
|
|
527
|
+
if (recheck || closed)
|
|
528
|
+
return;
|
|
529
|
+
recheck = setTimeout(async () => {
|
|
530
|
+
recheck = undefined;
|
|
531
|
+
lastCheck = Date.now();
|
|
532
|
+
const now = await identify(request).then((found) => found.principal?.tenant?.id ?? null, () => null);
|
|
533
|
+
if (now !== tenant && !closed) {
|
|
534
|
+
tenant = now;
|
|
535
|
+
stream.send("change", { sequence: runtime.changes.position, collections: ["*"] });
|
|
536
|
+
}
|
|
537
|
+
}, Math.max(0, lastCheck + 2_000 - Date.now()));
|
|
538
|
+
recheck.unref();
|
|
539
|
+
};
|
|
307
540
|
const off = runtime.changes.subscribe((event) => {
|
|
308
|
-
const
|
|
309
|
-
if (
|
|
310
|
-
|
|
541
|
+
const change = liveChange(runtime, event, visible, tenant);
|
|
542
|
+
if (change.withheld)
|
|
543
|
+
scheduleRecheck();
|
|
544
|
+
if (change.collections.length)
|
|
545
|
+
stream.send("change", { sequence: event.sequence, collections: change.collections, ...(change.keys ? { keys: change.keys } : {}) });
|
|
546
|
+
});
|
|
547
|
+
// A membership change reaches only its own tenant's subscribers and the principal it concerns:
|
|
548
|
+
// their pages re-read their session (tenant, role) and the queries that read memberships.
|
|
549
|
+
const offMembership = runtime.tenancy?.onChange((tenantId, subject) => {
|
|
550
|
+
if (tenantId === tenant || (principal && subject === principal.id))
|
|
551
|
+
stream.send("change", { sequence: runtime.changes.position, collections: [MEMBERSHIPS_COLLECTION] });
|
|
311
552
|
});
|
|
312
553
|
const offReload = runtime.onReload(() => stream.send("reload", { generation: runtime.generation }));
|
|
313
554
|
request.on("close", () => {
|
|
555
|
+
closed = true;
|
|
556
|
+
if (recheck)
|
|
557
|
+
clearTimeout(recheck);
|
|
314
558
|
off();
|
|
559
|
+
offMembership?.();
|
|
315
560
|
offReload();
|
|
316
561
|
stream.close();
|
|
317
562
|
});
|
|
@@ -345,6 +590,15 @@ export async function startServer(options) {
|
|
|
345
590
|
// sites without a CORS preflight, which would let another site drive an app whose
|
|
346
591
|
// auth.authenticate hook reads a cookie. Require JSON for anything that executes.
|
|
347
592
|
requireJsonPost(request);
|
|
593
|
+
// The browser client subscribes to AppPort events with its session cookie (a GET stream, Origin
|
|
594
|
+
// checked). Every other AppPort request needs an explicit credential: cookies are not accepted there.
|
|
595
|
+
if (!bearerToken(request) && (request.method ?? "GET") === "GET" && pathname.startsWith("/appport/events")) {
|
|
596
|
+
const cookie = cookieToken(request);
|
|
597
|
+
if (cookie && (await runtime.principalForToken(cookie))) {
|
|
598
|
+
checkCookieRequest(request, cookie, runtime.authSecret());
|
|
599
|
+
request.headers.authorization = `Bearer ${cookie}`;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
348
602
|
// A credential that does not verify is an error, never a downgrade to anonymous.
|
|
349
603
|
const token = bearerToken(request);
|
|
350
604
|
if (token && !(await runtime.principalForToken(token))) {
|
|
@@ -498,25 +752,13 @@ ${options.dashboard ? `<p>Studio: open the Dashboard link <code>feltkit dev</cod
|
|
|
498
752
|
</main></body></html>`;
|
|
499
753
|
response.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:; frame-ancestors 'none'" }).end(html);
|
|
500
754
|
}
|
|
501
|
-
/** Account e-mail per account and purpose, per process: 5 an hour, so a form cannot flood an inbox. */
|
|
502
|
-
class SendBudget {
|
|
503
|
-
#sent = new Map();
|
|
504
|
-
take(key) {
|
|
505
|
-
const now = Date.now();
|
|
506
|
-
const recent = (this.#sent.get(key) ?? []).filter((at) => now - at < 3_600_000);
|
|
507
|
-
if (recent.length >= 5)
|
|
508
|
-
return false;
|
|
509
|
-
this.#sent.set(key, [...recent, now]);
|
|
510
|
-
if (this.#sent.size > 10_000)
|
|
511
|
-
this.#sent.clear();
|
|
512
|
-
return true;
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
755
|
/** What a sign-in screen needs to know about the app's accounts. */
|
|
516
756
|
function accountsInfo(runtime) {
|
|
517
757
|
const options = runtime.app.options.auth;
|
|
518
758
|
return {
|
|
519
759
|
signUp: runtime.accounts.signUpOpen,
|
|
760
|
+
password: options?.accounts?.password !== false,
|
|
761
|
+
magicLink: Boolean(options?.accounts?.magicLink && options.accounts.email && runtime.mail),
|
|
520
762
|
email: Boolean(options?.accounts?.email && runtime.mail),
|
|
521
763
|
verify: options?.accounts?.email ? options.accounts.email.verify ?? "optional" : null,
|
|
522
764
|
providers: signInProviders(runtime.app.options.auth?.providers).map(({ id, name }) => ({ id, name })),
|
|
@@ -524,7 +766,7 @@ function accountsInfo(runtime) {
|
|
|
524
766
|
}
|
|
525
767
|
async function accountView(runtime, id) {
|
|
526
768
|
const account = await runtime.accounts.get(id);
|
|
527
|
-
return account ? { email: account.email, emailVerified: account.emailVerified, hasPassword: account.hasPassword } : null;
|
|
769
|
+
return account ? { email: account.email, emailVerified: account.emailVerified, hasPassword: account.hasPassword, providers: account.providers } : null;
|
|
528
770
|
}
|
|
529
771
|
/**
|
|
530
772
|
* What a deployment manager needs to know this process is the deployment it started: the
|