@feltdb/feltkit 0.3.16 → 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 +222 -5
- package/dist/app.js +178 -3
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.d.ts +57 -0
- package/dist/appboundry/build.js +54 -2
- package/dist/appboundry/build.js.map +1 -1
- package/dist/appboundry/guest.js +73 -1
- package/dist/appboundry/guest.js.map +1 -1
- package/dist/appboundry/host.d.ts +15 -0
- package/dist/appboundry/host.js +45 -1
- package/dist/appboundry/host.js.map +1 -1
- package/dist/authorize.d.ts +3 -2
- package/dist/authorize.js +5 -3
- 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 +242 -5
- package/dist/client/index.js +413 -29
- 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/event-stage.d.ts +13 -0
- package/dist/event-stage.js +15 -0
- package/dist/event-stage.js.map +1 -0
- package/dist/index.d.ts +5 -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 +17 -18
- package/dist/react/index.js +21 -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 +9 -1
- package/dist/runtime/authority.js +14 -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/content.d.ts +32 -0
- package/dist/runtime/content.js +42 -1
- package/dist/runtime/content.js.map +1 -1
- package/dist/runtime/context.d.ts +50 -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/events.d.ts +21 -0
- package/dist/runtime/events.js +65 -0
- package/dist/runtime/events.js.map +1 -0
- 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 +307 -36
- 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/services.d.ts +45 -0
- package/dist/runtime/services.js +90 -0
- package/dist/runtime/services.js.map +1 -1
- 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/schema.d.ts +2 -1
- package/dist/schema.js +1 -1
- package/dist/schema.js.map +1 -1
- package/dist/server/http.d.ts +1 -0
- package/dist/server/http.js +14 -0
- package/dist/server/http.js.map +1 -1
- package/dist/server/index.d.ts +2 -1
- package/dist/server/index.js +325 -59
- 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 +58 -4
- package/docs/README.md +3 -2
- package/docs/SECURITY.md +3 -2
- package/docs/TRANSACTIONS.md +98 -1
- package/docs/UPSTREAM-GAPS.md +3 -0
- package/package.json +11 -9
- 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";
|
|
33
|
-
import {
|
|
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";
|
|
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);
|
|
@@ -168,16 +229,53 @@ export async function startServer(options) {
|
|
|
168
229
|
return sendJSON(response, statusFor(result.error.code), result);
|
|
169
230
|
return sendJSON(response, 200, kind === "query" ? result : { ok: true, value: result.value, requestId: result.requestId });
|
|
170
231
|
}
|
|
232
|
+
// File links (ctx.services.files.link / uploadLink): the token is the authority, issued by a
|
|
233
|
+
// function that authorized the caller. No session is read, so links work as <a href> and <img src>.
|
|
234
|
+
const fileLink = /^\/api\/files\/(fkf_[A-Za-z0-9_-]{20,})$/.exec(pathname);
|
|
235
|
+
if (fileLink && (method === "GET" || method === "HEAD")) {
|
|
236
|
+
const { file, bytes, disposition } = await runtime.services.redeemDownload(fileLink[1]);
|
|
237
|
+
const type = file.contentType && /^[\w.+-]+\/[\w.+-]+(;\s*charset=[\w-]+)?$/i.test(file.contentType) ? file.contentType : "application/octet-stream";
|
|
238
|
+
response.writeHead(200, {
|
|
239
|
+
"Content-Type": type,
|
|
240
|
+
"Content-Length": bytes.byteLength,
|
|
241
|
+
"Content-Disposition": `${disposition}; filename*=UTF-8''${encodeURIComponent(file.name)}`,
|
|
242
|
+
// Uploaded content is never run as this origin's page, even when shown inline.
|
|
243
|
+
"Content-Security-Policy": "default-src 'none'; img-src 'self' data:; media-src 'self'; style-src 'unsafe-inline'; sandbox",
|
|
244
|
+
"Cache-Control": "private, no-store",
|
|
245
|
+
});
|
|
246
|
+
response.end(method === "HEAD" ? undefined : Buffer.from(bytes));
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if (fileLink && method === "PUT") {
|
|
250
|
+
const file = await runtime.services.redeemUpload(fileLink[1], (limit) => readBytes(request, limit), {
|
|
251
|
+
...(typeof request.headers["x-file-name"] === "string" ? { name: decodeURIComponent(request.headers["x-file-name"]) } : {}),
|
|
252
|
+
...(typeof request.headers["content-type"] === "string" ? { contentType: request.headers["content-type"] } : {}),
|
|
253
|
+
});
|
|
254
|
+
return sendJSON(response, 201, { ok: true, file });
|
|
255
|
+
}
|
|
256
|
+
if (await handleTenancy({ runtime, identify, sendSession }, request, response, pathname))
|
|
257
|
+
return;
|
|
171
258
|
if (pathname === "/api/session" && method === "GET") {
|
|
172
259
|
let principal = null;
|
|
260
|
+
let current = {};
|
|
173
261
|
try {
|
|
174
|
-
|
|
262
|
+
const found = await identify(request);
|
|
263
|
+
principal = found.principal;
|
|
264
|
+
current = found;
|
|
175
265
|
}
|
|
176
266
|
catch {
|
|
177
267
|
principal = null;
|
|
178
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);
|
|
179
272
|
return sendJSON(response, 200, {
|
|
180
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,
|
|
181
279
|
permissions: runtime.authority.permissionsFor(principal),
|
|
182
280
|
application: runtime.app.name,
|
|
183
281
|
environment: { name: runtime.environment.name, production },
|
|
@@ -192,28 +290,42 @@ export async function startServer(options) {
|
|
|
192
290
|
const accounts = runtime.accounts;
|
|
193
291
|
if (!accounts)
|
|
194
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.");
|
|
195
295
|
const body = await readJSON(request);
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
|
|
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
|
+
}
|
|
199
312
|
// A new account gets its verification e-mail (when the app sends account e-mail).
|
|
200
|
-
if (pathname === "/api/auth/signup" && runtime.mail
|
|
201
|
-
await runtime.
|
|
202
|
-
.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() })
|
|
203
|
-
.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)}`));
|
|
204
315
|
}
|
|
205
316
|
// Sign-up with required verification: the account exists, and signs in once verified.
|
|
206
317
|
if (pathname === "/api/auth/signup" && accounts.requireVerified) {
|
|
207
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." });
|
|
208
319
|
}
|
|
209
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" });
|
|
210
|
-
return
|
|
321
|
+
return sendSession(request, response, pathname === "/api/auth/signup" ? 201 : 200, issued);
|
|
211
322
|
}
|
|
212
323
|
if (pathname.startsWith("/api/auth/providers/") && (await handleProvider(runtime, request, response, pathname, new URL(request.url ?? "/", "http://local"))))
|
|
213
324
|
return;
|
|
214
|
-
// Account e-mail (auth.accounts.email): ask for a verification or
|
|
215
|
-
// A request answers the same whether or not the address has an account
|
|
216
|
-
|
|
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 = () => {
|
|
217
329
|
const accounts = runtime.accounts;
|
|
218
330
|
if (!accounts)
|
|
219
331
|
throw new FeltKitError("NOT_FOUND", "This app has no accounts.");
|
|
@@ -221,38 +333,117 @@ export async function startServer(options) {
|
|
|
221
333
|
throw new FeltKitError("NOT_FOUND", "This app sends no account e-mail (auth.accounts.email).");
|
|
222
334
|
if (!runtime.mail)
|
|
223
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();
|
|
224
340
|
const body = await readJSON(request);
|
|
225
341
|
const purpose = pathname === "/api/auth/reset/request" ? "reset" : "verify";
|
|
226
342
|
const account = await accounts.findByEmail(body.email);
|
|
227
|
-
if (account && (purpose === "reset" || !account.emailVerified)
|
|
228
|
-
await runtime.
|
|
229
|
-
recipient: account.id,
|
|
230
|
-
type: purpose === "reset" ? "account.password-reset" : "account.verify-email",
|
|
231
|
-
title: purpose === "reset" ? "Reset your password" : "Verify your e-mail address",
|
|
232
|
-
data: { purpose },
|
|
233
|
-
expiresAt: new Date(Date.now() + 60 * 60_000).toISOString(),
|
|
234
|
-
});
|
|
343
|
+
if (account && !account.disabled && (purpose === "reset" || !account.emailVerified)) {
|
|
344
|
+
await runtime.sendChallenge({ purpose, subject: account.id, recipient: account.id });
|
|
235
345
|
}
|
|
236
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." });
|
|
237
347
|
}
|
|
238
348
|
if ((pathname === "/api/auth/verify" || pathname === "/api/auth/reset") && method === "POST") {
|
|
239
|
-
const accounts =
|
|
240
|
-
if (!accounts || !runtime.app.options.auth?.accounts?.email)
|
|
241
|
-
throw new FeltKitError("NOT_FOUND", "This app sends no account e-mail (auth.accounts.email).");
|
|
349
|
+
const accounts = emailAccounts();
|
|
242
350
|
const body = await readJSON(request);
|
|
243
351
|
const purpose = pathname === "/api/auth/reset" ? "reset" : "verify";
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
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);
|
|
248
355
|
if (purpose === "verify") {
|
|
249
|
-
const account = await accounts.markVerified(
|
|
356
|
+
const account = await accounts.markVerified(challenge.subject);
|
|
357
|
+
runtime.recordAuth("account.verified", null, { subject: account.id });
|
|
250
358
|
return sendJSON(response, 200, { ok: true, email: account.email, emailVerified: true });
|
|
251
359
|
}
|
|
252
|
-
const account = await accounts.setPassword(
|
|
360
|
+
const account = await accounts.setPassword(challenge.subject, body.password);
|
|
253
361
|
await runtime.sessions.revokePrincipal(account.id);
|
|
362
|
+
runtime.recordAuth("account.password-reset", null, { subject: account.id });
|
|
254
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" });
|
|
255
|
-
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}.`);
|
|
256
447
|
}
|
|
257
448
|
if (pathname === "/api/auth/dev" && method === "POST") {
|
|
258
449
|
if (!runtime.environment.development)
|
|
@@ -262,14 +453,58 @@ export async function startServer(options) {
|
|
|
262
453
|
if (!user)
|
|
263
454
|
throw new FeltKitError("NOT_FOUND", `No dev user "${String(body.userId)}". Declare dev users in feltkit({ dev: { users } }).`);
|
|
264
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" });
|
|
265
|
-
return
|
|
456
|
+
return sendSession(request, response, 200, issued);
|
|
266
457
|
}
|
|
267
458
|
if (pathname === "/api/auth/signout" && method === "POST") {
|
|
268
|
-
const
|
|
269
|
-
if (
|
|
270
|
-
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);
|
|
271
472
|
return sendJSON(response, 200, { ok: true });
|
|
272
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
|
+
}
|
|
273
508
|
if (pathname === "/api/events" && method === "GET") {
|
|
274
509
|
// Change notifications reveal when data changes. They go to signed-in callers, or to
|
|
275
510
|
// anyone when the application has a public query (which anonymous clients may watch).
|
|
@@ -280,14 +515,48 @@ export async function startServer(options) {
|
|
|
280
515
|
const visible = publicCollections(runtime);
|
|
281
516
|
const stream = startSSE(response);
|
|
282
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
|
+
};
|
|
283
540
|
const off = runtime.changes.subscribe((event) => {
|
|
284
|
-
const
|
|
285
|
-
if (
|
|
286
|
-
|
|
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] });
|
|
287
552
|
});
|
|
288
553
|
const offReload = runtime.onReload(() => stream.send("reload", { generation: runtime.generation }));
|
|
289
554
|
request.on("close", () => {
|
|
555
|
+
closed = true;
|
|
556
|
+
if (recheck)
|
|
557
|
+
clearTimeout(recheck);
|
|
290
558
|
off();
|
|
559
|
+
offMembership?.();
|
|
291
560
|
offReload();
|
|
292
561
|
stream.close();
|
|
293
562
|
});
|
|
@@ -321,6 +590,15 @@ export async function startServer(options) {
|
|
|
321
590
|
// sites without a CORS preflight, which would let another site drive an app whose
|
|
322
591
|
// auth.authenticate hook reads a cookie. Require JSON for anything that executes.
|
|
323
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
|
+
}
|
|
324
602
|
// A credential that does not verify is an error, never a downgrade to anonymous.
|
|
325
603
|
const token = bearerToken(request);
|
|
326
604
|
if (token && !(await runtime.principalForToken(token))) {
|
|
@@ -474,25 +752,13 @@ ${options.dashboard ? `<p>Studio: open the Dashboard link <code>feltkit dev</cod
|
|
|
474
752
|
</main></body></html>`;
|
|
475
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);
|
|
476
754
|
}
|
|
477
|
-
/** Account e-mail per account and purpose, per process: 5 an hour, so a form cannot flood an inbox. */
|
|
478
|
-
class SendBudget {
|
|
479
|
-
#sent = new Map();
|
|
480
|
-
take(key) {
|
|
481
|
-
const now = Date.now();
|
|
482
|
-
const recent = (this.#sent.get(key) ?? []).filter((at) => now - at < 3_600_000);
|
|
483
|
-
if (recent.length >= 5)
|
|
484
|
-
return false;
|
|
485
|
-
this.#sent.set(key, [...recent, now]);
|
|
486
|
-
if (this.#sent.size > 10_000)
|
|
487
|
-
this.#sent.clear();
|
|
488
|
-
return true;
|
|
489
|
-
}
|
|
490
|
-
}
|
|
491
755
|
/** What a sign-in screen needs to know about the app's accounts. */
|
|
492
756
|
function accountsInfo(runtime) {
|
|
493
757
|
const options = runtime.app.options.auth;
|
|
494
758
|
return {
|
|
495
759
|
signUp: runtime.accounts.signUpOpen,
|
|
760
|
+
password: options?.accounts?.password !== false,
|
|
761
|
+
magicLink: Boolean(options?.accounts?.magicLink && options.accounts.email && runtime.mail),
|
|
496
762
|
email: Boolean(options?.accounts?.email && runtime.mail),
|
|
497
763
|
verify: options?.accounts?.email ? options.accounts.email.verify ?? "optional" : null,
|
|
498
764
|
providers: signInProviders(runtime.app.options.auth?.providers).map(({ id, name }) => ({ id, name })),
|
|
@@ -500,7 +766,7 @@ function accountsInfo(runtime) {
|
|
|
500
766
|
}
|
|
501
767
|
async function accountView(runtime, id) {
|
|
502
768
|
const account = await runtime.accounts.get(id);
|
|
503
|
-
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;
|
|
504
770
|
}
|
|
505
771
|
/**
|
|
506
772
|
* What a deployment manager needs to know this process is the deployment it started: the
|