@midsummer-ai/sdk 0.1.0-staging.3769 → 0.1.0-staging.3775
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/auth/contract.d.mts +2 -2
- package/auth/contract.mjs +1 -1
- package/auth/index.d.mts +2 -2
- package/auth/index.mjs +1 -1
- package/auth/password.mjs +1 -1
- package/auth/react.mjs +1 -1
- package/auth/stand-in.d.mts +1 -1
- package/{auth-B2k7Nwjx.mjs → auth-Bu4FIk-C.mjs} +115 -48
- package/{client-DMUFrqzg.d.mts → client-COPmSTKM.d.mts} +15 -3
- package/{client-D0gC0c1_.mjs → client-G20sA352.mjs} +52 -15
- package/database/client.d.mts +2 -2
- package/database/client.mjs +2 -2
- package/database/react.d.mts +1 -1
- package/{engine-BmiPioJ2.mjs → engine-o-3LFoL3.mjs} +4 -2
- package/{index-PL-07Sie.d.mts → index-q1gV7MyO.d.mts} +1 -1
- package/package.json +1 -1
- package/{store-DXHi6LCj.d.mts → store-BpA6Q5Z_.d.mts} +4 -3
package/auth/contract.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as AuthStore } from "../store-
|
|
1
|
+
import { n as AuthStore } from "../store-BpA6Q5Z_.mjs";
|
|
2
2
|
import { SignInMail } from "./mail.mjs";
|
|
3
|
-
import { a as Auth } from "../index-
|
|
3
|
+
import { a as Auth } from "../index-q1gV7MyO.mjs";
|
|
4
4
|
//#region src/auth/contract.d.ts
|
|
5
5
|
interface AuthHarness {
|
|
6
6
|
/** Sign-in over a store with no users, made with `scopes: CONTRACT_SCOPES`. */
|
package/auth/contract.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as LIMITS, l as LIMIT_WINDOW_MS, r as AuthError, u as SETTINGS_TTL_MS } from "../auth-
|
|
1
|
+
import { c as LIMITS, l as LIMIT_WINDOW_MS, r as AuthError, u as SETTINGS_TTL_MS } from "../auth-Bu4FIk-C.mjs";
|
|
2
2
|
import { IMPERSONATION_TOKEN_MS, startImpersonation } from "./impersonate.mjs";
|
|
3
3
|
//#region src/auth/contract.ts
|
|
4
4
|
/**
|
package/auth/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as AuthStore, r as databaseStore, t as AuthCall } from "../store-
|
|
1
|
+
import { n as AuthStore, r as databaseStore, t as AuthCall } from "../store-BpA6Q5Z_.mjs";
|
|
2
2
|
import { i as SignUpPolicy, n as CaptchaProvider, r as PublicSettings, t as AuthSettings } from "../settings-Dz3irtlu.mjs";
|
|
3
3
|
import { SignInMail, SignInMailKind, checkSignInMail, signInWords } from "./mail.mjs";
|
|
4
|
-
import { _ as AuthEvent, a as Auth, b as EventSend, c as AuthOptions, d as IMPERSONATION_S, f as SESSION_CACHE_S, g as createAuth, h as auth, i as AgentKey, l as AuthUser, m as SignedInAgent, n as AUTH_ROUTES, o as AuthError, p as SignedIn, r as AgentGrant, s as AuthErrorCode, t as AUTH_PATH, u as AuthUserRecord, v as AuthEventBatch, y as AuthEventType } from "../index-
|
|
4
|
+
import { _ as AuthEvent, a as Auth, b as EventSend, c as AuthOptions, d as IMPERSONATION_S, f as SESSION_CACHE_S, g as createAuth, h as auth, i as AgentKey, l as AuthUser, m as SignedInAgent, n as AUTH_ROUTES, o as AuthError, p as SignedIn, r as AgentGrant, s as AuthErrorCode, t as AUTH_PATH, u as AuthUserRecord, v as AuthEventBatch, y as AuthEventType } from "../index-q1gV7MyO.mjs";
|
|
5
5
|
import { i as authFiles } from "../files-B553U-d6.mjs";
|
|
6
6
|
export { AUTH_PATH, AUTH_ROUTES, AgentGrant, AgentKey, Auth, type AuthCall, AuthError, AuthErrorCode, type AuthEvent, type AuthEventBatch, type AuthEventType, AuthOptions, type AuthSettings, type AuthStore, AuthUser, AuthUserRecord, type CaptchaProvider, type EventSend, IMPERSONATION_S, type PublicSettings, SESSION_CACHE_S, type SignInMail, type SignInMailKind, type SignUpPolicy, SignedIn, SignedInAgent, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
|
package/auth/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as SESSION_CACHE_S, d as databaseStore, i as IMPERSONATION_S, n as AUTH_ROUTES, o as auth, r as AuthError, s as createAuth, t as AUTH_PATH } from "../auth-
|
|
1
|
+
import { a as SESSION_CACHE_S, d as databaseStore, i as IMPERSONATION_S, n as AUTH_ROUTES, o as auth, r as AuthError, s as createAuth, t as AUTH_PATH } from "../auth-Bu4FIk-C.mjs";
|
|
2
2
|
import { checkSignInMail, signInWords } from "./mail.mjs";
|
|
3
3
|
import { n as authFiles } from "../files-DhPeWwcT.mjs";
|
|
4
4
|
export { AUTH_PATH, AUTH_ROUTES, AuthError, IMPERSONATION_S, SESSION_CACHE_S, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
|
package/auth/password.mjs
CHANGED
package/auth/react.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-G20sA352.mjs";
|
|
2
2
|
import { DatabaseProvider } from "../database/react.mjs";
|
|
3
3
|
import { a as WORDS, c as deviceOf, i as CAPTCHA_WIDGETS, l as setupKeyOf, o as ago, r as AUTH_CSS, t as qrPath } from "../qr-Br1sOBmT.mjs";
|
|
4
4
|
import { AuthClientError, authClient } from "./client.mjs";
|
package/auth/stand-in.d.mts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { i as processEnv, r as platformApi, t as here } from "./here-BKjizr_N.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { d as userToken, o as connect, s as databaseUrl } from "./client-G20sA352.mjs";
|
|
3
3
|
import { sendSignInMail } from "./auth/mail.mjs";
|
|
4
4
|
import "./files-DhPeWwcT.mjs";
|
|
5
5
|
import { standIn } from "./auth/stand-in.mjs";
|
|
6
|
-
import { a as ourWords, c as agentOfToken, d as credentialOf, f as remembering, l as challenge, n as REFUSALS, p as resourceOf, r as buildEngine, s as agentOfKey, t as JoinRefused, u as consentPage } from "./engine-
|
|
6
|
+
import { a as ourWords, c as agentOfToken, d as credentialOf, f as remembering, l as challenge, n as REFUSALS, p as resourceOf, r as buildEngine, s as agentOfKey, t as JoinRefused, u as consentPage } from "./engine-o-3LFoL3.mjs";
|
|
7
7
|
import { a as WORDS, c as deviceOf, i as CAPTCHA_WIDGETS, l as setupKeyOf, n as qrSvg, o as ago, r as AUTH_CSS, s as defaultAppName } from "./qr-Br1sOBmT.mjs";
|
|
8
8
|
//#region src/auth/store.ts
|
|
9
9
|
const KIND = {
|
|
@@ -19,13 +19,16 @@ const KIND = {
|
|
|
19
19
|
increment: "mutation",
|
|
20
20
|
page: "query"
|
|
21
21
|
};
|
|
22
|
+
/** The longest sign-in waits for one call to the database, connecting included, before it answers that it couldn't. */
|
|
23
|
+
const STORE_CALL_MS = 1e4;
|
|
22
24
|
/**
|
|
23
25
|
* The app's database as sign-in's store: each call one of `db/auth.ts`'s functions. `database` gives the
|
|
24
26
|
* connection a call goes over; it is asked for one each call, so it can hand out the request's own. A function
|
|
25
|
-
* that isn't there means `db/auth.ts` was never deployed: the error says to run `midsummer auth init`.
|
|
27
|
+
* that isn't there means `db/auth.ts` was never deployed: the error says to run `midsummer auth init`. A call
|
|
28
|
+
* unanswered after `waitMs` (`STORE_CALL_MS`) throws, so a request never waits on the database for longer.
|
|
26
29
|
*/
|
|
27
|
-
function databaseStore(database) {
|
|
28
|
-
|
|
30
|
+
function databaseStore(database, waitMs = STORE_CALL_MS) {
|
|
31
|
+
const run = async (fn, args) => {
|
|
29
32
|
const db = await database();
|
|
30
33
|
try {
|
|
31
34
|
return KIND[fn] === "query" ? await db.query({
|
|
@@ -39,6 +42,17 @@ function databaseStore(database) {
|
|
|
39
42
|
if (/no function|not found|unknown function/i.test(String(error?.message))) throw new Error(`The database has no auth.${fn}: add sign-in's tables and functions with midsummer auth init, then deploy db/.`);
|
|
40
43
|
throw error;
|
|
41
44
|
}
|
|
45
|
+
};
|
|
46
|
+
return { async call(fn, args) {
|
|
47
|
+
let timer;
|
|
48
|
+
const late = new Promise((_, refuse) => {
|
|
49
|
+
timer = setTimeout(() => refuse(/* @__PURE__ */ new Error(`The database didn't answer auth.${fn} within ${waitMs / 1e3} seconds.`)), waitMs);
|
|
50
|
+
});
|
|
51
|
+
try {
|
|
52
|
+
return await Promise.race([run(fn, args), late]);
|
|
53
|
+
} finally {
|
|
54
|
+
clearTimeout(timer);
|
|
55
|
+
}
|
|
42
56
|
} };
|
|
43
57
|
}
|
|
44
58
|
//#endregion
|
|
@@ -139,13 +153,21 @@ function publicSettings(settings, appName) {
|
|
|
139
153
|
};
|
|
140
154
|
}
|
|
141
155
|
/**
|
|
142
|
-
* The app's settings from `store`, read again once `SETTINGS_TTL_MS` has passed since the last read.
|
|
143
|
-
* for while one is on its way share it
|
|
156
|
+
* The app's settings from `store`, read again once `SETTINGS_TTL_MS` has passed since the last read began. Only a
|
|
157
|
+
* read that has answered is kept. Reads asked for while one is on its way share it when `scope` gives them the same
|
|
158
|
+
* owner (a deployment's request, `here()`), or when it gives none: a request never waits on another request's read,
|
|
159
|
+
* which ends when that request does.
|
|
144
160
|
*/
|
|
145
|
-
function settingsReader(store, clock = Date.now) {
|
|
161
|
+
function settingsReader(store, clock = Date.now, scope = () => void 0) {
|
|
146
162
|
let kept;
|
|
163
|
+
const reading = /* @__PURE__ */ new WeakMap();
|
|
164
|
+
let unscoped;
|
|
147
165
|
return () => {
|
|
148
|
-
if (kept && kept.until > clock()) return kept.value;
|
|
166
|
+
if (kept && kept.until > clock()) return Promise.resolve(kept.value);
|
|
167
|
+
const owner = scope();
|
|
168
|
+
const pending = owner ? reading.get(owner) : unscoped;
|
|
169
|
+
if (pending) return pending;
|
|
170
|
+
const began = clock();
|
|
149
171
|
const value = store.call("findOne", {
|
|
150
172
|
model: "authSettings",
|
|
151
173
|
where: [{
|
|
@@ -153,13 +175,17 @@ function settingsReader(store, clock = Date.now) {
|
|
|
153
175
|
value: "settings"
|
|
154
176
|
}]
|
|
155
177
|
}).then(settingsOf);
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
178
|
+
value.then((settings) => {
|
|
179
|
+
kept = {
|
|
180
|
+
until: began + SETTINGS_TTL_MS,
|
|
181
|
+
value: settings
|
|
182
|
+
};
|
|
183
|
+
}, () => {}).finally(() => {
|
|
184
|
+
if (owner) reading.delete(owner);
|
|
185
|
+
else if (unscoped === value) unscoped = void 0;
|
|
162
186
|
});
|
|
187
|
+
if (owner) reading.set(owner, value);
|
|
188
|
+
else unscoped = value;
|
|
163
189
|
return value;
|
|
164
190
|
};
|
|
165
191
|
}
|
|
@@ -1201,6 +1227,23 @@ const METADATA_BYTES = 8192;
|
|
|
1201
1227
|
function originOf(request) {
|
|
1202
1228
|
return new URL(request.url).origin;
|
|
1203
1229
|
}
|
|
1230
|
+
/** The session's cookie, by its name over http and over https. */
|
|
1231
|
+
const SESSION_COOKIES = /* @__PURE__ */ new Set(["midsummer.session_token", "__Secure-midsummer.session_token"]);
|
|
1232
|
+
/** Whether a request carries a session's cookie: without one no one is signed in, and nothing need be read. */
|
|
1233
|
+
function hasSessionCookie(request) {
|
|
1234
|
+
const cookie = request.headers.get("cookie");
|
|
1235
|
+
if (!cookie) return false;
|
|
1236
|
+
return cookie.split(";").some((pair) => {
|
|
1237
|
+
const at = pair.indexOf("=");
|
|
1238
|
+
return at > 0 && SESSION_COOKIES.has(pair.slice(0, at).trim()) && pair.slice(at + 1).trim() !== "";
|
|
1239
|
+
});
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* The request as the runtime's own `Request`. A framework may hand its own kind (Next.js's `NextRequest`), which some
|
|
1243
|
+
* runtimes can't copy as a `Request` (`new Request(it, init)` reads it as the text `[object Request]`) but read
|
|
1244
|
+
* well as the options of a new one.
|
|
1245
|
+
*/
|
|
1246
|
+
const plainRequest = (request) => new Request(request.url, request);
|
|
1204
1247
|
/** The Database connection a request's sign-in uses: one per request in a deployment, one per process elsewhere. */
|
|
1205
1248
|
function requestDatabase(open, what) {
|
|
1206
1249
|
const perRequest = /* @__PURE__ */ new WeakMap();
|
|
@@ -1377,12 +1420,23 @@ function createAuth(options = {}) {
|
|
|
1377
1420
|
made = {
|
|
1378
1421
|
store,
|
|
1379
1422
|
env,
|
|
1380
|
-
settings: settingsReader(store, options.clock),
|
|
1423
|
+
settings: settingsReader(store, options.clock, here),
|
|
1381
1424
|
allow: rateLimiter(store, options.clock)
|
|
1382
1425
|
};
|
|
1383
1426
|
}
|
|
1384
1427
|
return made;
|
|
1385
1428
|
};
|
|
1429
|
+
/** The secret sessions are signed with; throws, saying how to set it, where there is none. */
|
|
1430
|
+
const secretOf = () => {
|
|
1431
|
+
const secret = options.secret || base().env.AUTH_SECRET;
|
|
1432
|
+
if (!secret) throw new AuthError("forbidden", "Sign-in needs AUTH_SECRET in this environment: midsummer env set <team>/<project> AUTH_SECRET --kind secret --generate --environment <environment>. Outside Midsummer, set it to 32 random characters or more.");
|
|
1433
|
+
return secret;
|
|
1434
|
+
};
|
|
1435
|
+
/** Throws what a misconfigured app is told (no database to keep rows in, no AUTH_SECRET), reading nothing: before any answer that needs no read. */
|
|
1436
|
+
const configured = () => {
|
|
1437
|
+
base();
|
|
1438
|
+
secretOf();
|
|
1439
|
+
};
|
|
1386
1440
|
/** The app's name: its settings', `appName`, `APP_NAME`, else the address it serves at (`shop.acme.dev`), which reads right in every screen and mail. */
|
|
1387
1441
|
const appNameOf = (settings, origin) => settings.branding.name ?? options.appName ?? base().env.APP_NAME ?? defaultAppName(origin);
|
|
1388
1442
|
/** Work that follows a request, such as the new-device mail, until it ends. */
|
|
@@ -1486,35 +1540,38 @@ function createAuth(options = {}) {
|
|
|
1486
1540
|
const { store, env, settings } = base();
|
|
1487
1541
|
const now = await settings(), appName = appNameOf(now, normal);
|
|
1488
1542
|
const id = `${normal}\n${appName}\n${now.confirmEmail}`;
|
|
1489
|
-
|
|
1490
|
-
if (
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
return found;
|
|
1543
|
+
const found = kept.get(id);
|
|
1544
|
+
if (found) return found;
|
|
1545
|
+
const secret = secretOf();
|
|
1546
|
+
const built = buildEngine({
|
|
1547
|
+
origin: normal,
|
|
1548
|
+
appName,
|
|
1549
|
+
secret,
|
|
1550
|
+
store,
|
|
1551
|
+
env,
|
|
1552
|
+
agents: settingsOfAgents,
|
|
1553
|
+
admit,
|
|
1554
|
+
changed: changed(normal),
|
|
1555
|
+
impersonationS: IMPERSONATION_S,
|
|
1556
|
+
cacheS: 300,
|
|
1557
|
+
confirmEmail: now.confirmEmail,
|
|
1558
|
+
invitationUrl: options.invitationUrl ?? ((from, invitation) => `${from}/api/auth/ui/invitation/${invitation}`),
|
|
1559
|
+
send: async (mail) => sendOne(await settings(), normal, mail)
|
|
1560
|
+
});
|
|
1561
|
+
await built.ready;
|
|
1562
|
+
if (kept.size >= KEPT_ORIGINS) kept.delete(kept.keys().next().value);
|
|
1563
|
+
kept.set(id, built);
|
|
1564
|
+
return built;
|
|
1512
1565
|
};
|
|
1513
1566
|
const declared = (scope, what) => {
|
|
1514
1567
|
if (!Object.hasOwn(settingsOfAgents.scopes, scope)) throw new AuthError("invalid", `${what} the scope ${scope}, which the app doesn't declare: add it to createAuth({ scopes }).`);
|
|
1515
1568
|
};
|
|
1516
|
-
/** The person signed in themselves, with their session's cookie. */
|
|
1569
|
+
/** The person signed in themselves, with their session's cookie; null at once, reading nothing, for a request without one. */
|
|
1517
1570
|
async function person(request, fresh = false) {
|
|
1571
|
+
if (!hasSessionCookie(request)) {
|
|
1572
|
+
configured();
|
|
1573
|
+
return null;
|
|
1574
|
+
}
|
|
1518
1575
|
const found = await (await at(originOf(request))).api.getSession({
|
|
1519
1576
|
headers: request.headers,
|
|
1520
1577
|
...fresh ? { query: { disableCookieCache: true } } : {}
|
|
@@ -1792,7 +1849,7 @@ function createAuth(options = {}) {
|
|
|
1792
1849
|
/**
|
|
1793
1850
|
* `GET /api/auth/database-token`, for the page's `signedInDatabase()`: the address of the database sign-in keeps its
|
|
1794
1851
|
* rows in, and for someone signed in a ten-minute token that runs the app's public functions as them (`userToken`),
|
|
1795
|
-
* never internal ones. Someone not signed in gets the address alone, to connect as no one. On Midsummer it needs no
|
|
1852
|
+
* never internal ones, carrying their name and email as claims (on Midsummer; a key's token carries their id alone). Someone not signed in gets the address alone, to connect as no one. On Midsummer it needs no
|
|
1796
1853
|
* key, previews and `midsummer dev` included; elsewhere it uses the database key sign-in uses.
|
|
1797
1854
|
*/
|
|
1798
1855
|
async function databaseToken(request) {
|
|
@@ -1814,18 +1871,26 @@ function createAuth(options = {}) {
|
|
|
1814
1871
|
if (!signedIn) return answer(200, { url: await databaseUrl(where) });
|
|
1815
1872
|
return answer(200, await userToken({
|
|
1816
1873
|
...where,
|
|
1817
|
-
as: signedIn.user.id
|
|
1874
|
+
as: signedIn.user.id,
|
|
1875
|
+
profile: {
|
|
1876
|
+
name: signedIn.user.name,
|
|
1877
|
+
email: signedIn.user.email
|
|
1878
|
+
}
|
|
1818
1879
|
}));
|
|
1819
1880
|
}
|
|
1820
1881
|
/** Serves one request under `/api/auth`: settings, account calls, hosted pages, the guard, then the engine. */
|
|
1821
1882
|
async function serve(request) {
|
|
1822
1883
|
const origin = originOf(request), { pathname } = new URL(request.url);
|
|
1884
|
+
const path = pathname.startsWith(`/api/auth/`) ? pathname.slice(9) : void 0;
|
|
1885
|
+
if (path === "/session" && request.method === "GET" && !hasSessionCookie(request)) {
|
|
1886
|
+
configured();
|
|
1887
|
+
return Response.json(null, { headers: { "Cache-Control": "no-store" } });
|
|
1888
|
+
}
|
|
1823
1889
|
const { settings: read, env, allow } = base();
|
|
1824
1890
|
const settings = await read();
|
|
1825
|
-
const
|
|
1826
|
-
if (pathname === "/.well-known/oauth-authorization-server") return
|
|
1827
|
-
if (
|
|
1828
|
-
const path = pathname.slice(9);
|
|
1891
|
+
const appName = appNameOf(settings, origin);
|
|
1892
|
+
if (pathname === "/.well-known/oauth-authorization-server") return (await at(origin)).handler(new Request(`${origin}/.well-known/oauth-authorization-server${AUTH_PATH}`, request));
|
|
1893
|
+
if (path === void 0) return (await at(origin)).handler(request);
|
|
1829
1894
|
const shown = publicSettings(settings, appName), keyed = (name) => !!(env[`${name}_CLIENT_ID`] && env[`${name}_CLIENT_SECRET`]);
|
|
1830
1895
|
const offered = {
|
|
1831
1896
|
...shown,
|
|
@@ -1841,12 +1906,13 @@ function createAuth(options = {}) {
|
|
|
1841
1906
|
}, { headers: { "Cache-Control": "no-store" } });
|
|
1842
1907
|
if (`/api/auth${path}` === "/api/auth/database-token" && request.method === "GET") return databaseToken(request);
|
|
1843
1908
|
if (path.startsWith("/account/")) return account(request, path.slice(8), origin);
|
|
1844
|
-
if (pathname === CONSENT_PATH && settingsOfAgents.consentPage === CONSENT_PATH) return consent(request, origin, engine, appName);
|
|
1845
1909
|
if (path.startsWith("/ui/")) return hostedPage(request, path.slice(3), {
|
|
1846
1910
|
auth,
|
|
1847
1911
|
settings: offered,
|
|
1848
1912
|
scopes: settingsOfAgents.scopes
|
|
1849
1913
|
});
|
|
1914
|
+
const engine = await at(origin);
|
|
1915
|
+
if (pathname === CONSENT_PATH && settingsOfAgents.consentPage === CONSENT_PATH) return consent(request, origin, engine, appName);
|
|
1850
1916
|
const route = Object.hasOwn(AUTH_ROUTES, path) ? path : void 0;
|
|
1851
1917
|
if (route && request.method !== AUTH_ROUTES[route].method) return refusal(405, "METHOD_NOT_ALLOWED", `${AUTH_PATH}${route} takes ${AUTH_ROUTES[route].method}.`);
|
|
1852
1918
|
const inner = route ? new Request(`${origin}${AUTH_PATH}${AUTH_ROUTES[route].engine}${new URL(request.url).search}`, request) : request;
|
|
@@ -1885,7 +1951,8 @@ function createAuth(options = {}) {
|
|
|
1885
1951
|
});
|
|
1886
1952
|
const fits = (value) => value === void 0 || JSON.stringify(value ?? null).length <= METADATA_BYTES;
|
|
1887
1953
|
const auth = {
|
|
1888
|
-
async handler(
|
|
1954
|
+
async handler(given) {
|
|
1955
|
+
const request = plainRequest(given);
|
|
1889
1956
|
const current = here();
|
|
1890
1957
|
if (!current || held.has(current)) return serve(request).catch(failed);
|
|
1891
1958
|
held.set(current, []);
|
|
@@ -66,7 +66,7 @@ interface DatabaseToken {
|
|
|
66
66
|
*/
|
|
67
67
|
interface BoundDatabases {
|
|
68
68
|
token(binding: string): Promise<DatabaseToken>;
|
|
69
|
-
userToken?(binding: string, as: string): Promise<DatabaseToken>;
|
|
69
|
+
userToken?(binding: string, as: string, profile?: UserProfile): Promise<DatabaseToken>;
|
|
70
70
|
/**
|
|
71
71
|
* Where the app's server calls the Database bound as `binding`, with its token and when that runs out, handed in
|
|
72
72
|
* with the request, so connecting asks for nothing. Undefined where the request was handed none: `token` serves.
|
|
@@ -80,10 +80,21 @@ interface BoundDatabases {
|
|
|
80
80
|
/** Adds an entry to the `Server-Timing` of the request's response, where Midsummer turned that on for its own diagnostics. */
|
|
81
81
|
note?(entry: string): void;
|
|
82
82
|
}
|
|
83
|
+
/** What a user's token says of them beside their id, as the OIDC claims `name` and `email`, each at most `PROFILE_MOST` characters. */
|
|
84
|
+
interface UserProfile {
|
|
85
|
+
readonly name?: string;
|
|
86
|
+
readonly email?: string;
|
|
87
|
+
}
|
|
88
|
+
/** The most characters a `UserProfile`'s name or email carries. */
|
|
89
|
+
declare const PROFILE_MOST = 320;
|
|
90
|
+
/** The profile a token carries: each of its fields that is text of 1 to `PROFILE_MOST` characters, else left out. */
|
|
91
|
+
declare function profileClaims(profile: UserProfile | undefined): UserProfile;
|
|
83
92
|
/**
|
|
84
93
|
* A token for one signed-in user of your app, for your server to hand to that user's browser, which connects with
|
|
85
94
|
* it (`signedInDatabase()`, `@midsummer-ai/sdk/react`'s `DatabaseProvider`, or `connect({ url, token, refresh })`).
|
|
86
|
-
* Your server gives the user's id as `as`; your functions see that id as `ctx.auth.subject`.
|
|
95
|
+
* Your server gives the user's id as `as`; your functions see that id as `ctx.auth.subject`. On Midsummer, `profile`
|
|
96
|
+
* puts the user's name and email in the token too, as the claims `name` and `email`; a token exchanged for a
|
|
97
|
+
* database key carries the id alone. The token
|
|
87
98
|
* runs public functions only, never internal ones. It lasts ten minutes: the browser asks your server again before
|
|
88
99
|
* then. With Auth, `auth.handler` serves it already, at `/api/auth/database-token`.
|
|
89
100
|
*
|
|
@@ -96,6 +107,7 @@ interface BoundDatabases {
|
|
|
96
107
|
*/
|
|
97
108
|
declare function userToken(options: {
|
|
98
109
|
readonly as: string;
|
|
110
|
+
readonly profile?: UserProfile;
|
|
99
111
|
readonly binding?: string;
|
|
100
112
|
readonly key?: string;
|
|
101
113
|
readonly api?: string;
|
|
@@ -208,4 +220,4 @@ declare function clerk(getToken: (options: {
|
|
|
208
220
|
*/
|
|
209
221
|
declare function oidc(getToken: (forceRefresh: boolean) => Promise<string | null | undefined> | string | null | undefined): FetchToken;
|
|
210
222
|
//#endregion
|
|
211
|
-
export {
|
|
223
|
+
export { userToken as S, connect as _, DATABASE_TOKEN_PATH as a, profileClaims as b, DatabaseToken as c, Reference as d, ReturnsOf as f, clerk as g, auth0 as h, ConnectOptions as i, FetchToken as l, UserProfile as m, AuthState as n, Database as o, SignedInDatabase as p, BoundDatabases as r, DatabaseClient as s, ArgsOf as t, PROFILE_MOST as u, databaseUrl as v, signedInDatabase as x, oidc as y };
|
|
@@ -12,15 +12,19 @@ import { t as callKey } from "./key-BrRdFY-n.mjs";
|
|
|
12
12
|
* const token = devToken("ada") // as one of the app's users
|
|
13
13
|
* const server = devToken("site:dev") // as the app's server, as `midsummer dev` hands its servers
|
|
14
14
|
*/
|
|
15
|
-
/**
|
|
16
|
-
|
|
17
|
-
|
|
15
|
+
/**
|
|
16
|
+
* A token for the development server: an unsigned JWT naming `subject`, good for a day, with the user's `name` and
|
|
17
|
+
* `email` when `profile` gives them. Never accepted by a Database.
|
|
18
|
+
*/
|
|
19
|
+
function devToken(subject, profile = {}) {
|
|
20
|
+
const encode = (value) => btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(value)))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
18
21
|
return `${encode({
|
|
19
22
|
alg: "none",
|
|
20
23
|
typ: "JWT"
|
|
21
24
|
})}.${encode({
|
|
22
25
|
iss: "midsummer-dev",
|
|
23
26
|
sub: subject,
|
|
27
|
+
...profile,
|
|
24
28
|
exp: Math.floor(Date.now() / 1e3) + 86400
|
|
25
29
|
})}.`;
|
|
26
30
|
}
|
|
@@ -76,6 +80,16 @@ function devToken(subject) {
|
|
|
76
80
|
* db.setAuth(clerk(getToken, { template: "midsummer" }))
|
|
77
81
|
* db.clearAuth() // signed out
|
|
78
82
|
*/
|
|
83
|
+
/** The most characters a `UserProfile`'s name or email carries. */
|
|
84
|
+
const PROFILE_MOST = 320;
|
|
85
|
+
/** The profile a token carries: each of its fields that is text of 1 to `PROFILE_MOST` characters, else left out. */
|
|
86
|
+
function profileClaims(profile) {
|
|
87
|
+
const fits = (value) => typeof value === "string" && value.length > 0 && value.length <= 320;
|
|
88
|
+
return {
|
|
89
|
+
...fits(profile?.name) ? { name: profile.name } : {},
|
|
90
|
+
...fits(profile?.email) ? { email: profile.email } : {}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
79
93
|
/** The subjects the platform's own tokens use, which never name one of an app's users. */
|
|
80
94
|
const SERVER_SUBJECT = /^(?:key|site|workload):/u;
|
|
81
95
|
/** Why `as` can't name one of the app's users, or undefined when it can: the platform's rule for them. */
|
|
@@ -109,7 +123,9 @@ async function exchange(api, proof) {
|
|
|
109
123
|
/**
|
|
110
124
|
* A token for one signed-in user of your app, for your server to hand to that user's browser, which connects with
|
|
111
125
|
* it (`signedInDatabase()`, `@midsummer-ai/sdk/react`'s `DatabaseProvider`, or `connect({ url, token, refresh })`).
|
|
112
|
-
* Your server gives the user's id as `as`; your functions see that id as `ctx.auth.subject`.
|
|
126
|
+
* Your server gives the user's id as `as`; your functions see that id as `ctx.auth.subject`. On Midsummer, `profile`
|
|
127
|
+
* puts the user's name and email in the token too, as the claims `name` and `email`; a token exchanged for a
|
|
128
|
+
* database key carries the id alone. The token
|
|
113
129
|
* runs public functions only, never internal ones. It lasts ten minutes: the browser asks your server again before
|
|
114
130
|
* then. With Auth, `auth.handler` serves it already, at `/api/auth/database-token`.
|
|
115
131
|
*
|
|
@@ -138,10 +154,11 @@ async function userToken(options) {
|
|
|
138
154
|
const found = bound(binding);
|
|
139
155
|
if ("handle" in found) {
|
|
140
156
|
if (!found.handle.userToken) throw new DatabaseError("unavailable", `This deployment's runtime gives no user tokens for the database bound as ${binding}. That's Midsummer's fault, not your code's: ship again, and if it goes on, tell Midsummer.`);
|
|
141
|
-
|
|
157
|
+
const profile = profileClaims(options.profile);
|
|
158
|
+
return Object.keys(profile).length ? found.handle.userToken(binding, options.as, profile) : found.handle.userToken(binding, options.as);
|
|
142
159
|
}
|
|
143
160
|
if ("dev" in found) return {
|
|
144
|
-
token: devToken(options.as),
|
|
161
|
+
token: devToken(options.as, profileClaims(options.profile)),
|
|
145
162
|
url: found.dev,
|
|
146
163
|
expiresAt: Date.now() + 864e5
|
|
147
164
|
};
|
|
@@ -427,10 +444,16 @@ async function opened(url, token, refresh, server, key) {
|
|
|
427
444
|
}
|
|
428
445
|
/** How long before its token runs out a door's calls renew it first. Every token a request hands has a minute or more left. */
|
|
429
446
|
const DOOR_RENEW_MS = 3e4;
|
|
447
|
+
/** How long one request to a door may take, its answer read included, before it counts as no answer and is sent again. */
|
|
448
|
+
const DOOR_CALL_MS = 1e4;
|
|
430
449
|
/** The most calls one request to a door carries; more made at once go in as many requests as they need. */
|
|
431
450
|
const DOOR_BATCH = 256;
|
|
432
|
-
/**
|
|
433
|
-
|
|
451
|
+
/**
|
|
452
|
+
* The remakes asked for, by the request's handle and door: that request's calls at once that found their Database gone
|
|
453
|
+
* wait on one ask. Another request asks for itself (the dispatcher makes it once for them all), so no request waits on
|
|
454
|
+
* an ask that ends with another request.
|
|
455
|
+
*/
|
|
456
|
+
const remaking = /* @__PURE__ */ new WeakMap();
|
|
434
457
|
/**
|
|
435
458
|
* A Deployment's server's calls to its Database, sent straight to the Database's door (`<door>/call`) with the token
|
|
436
459
|
* its request handed in: stateless HTTPS, no hop through Midsummer and no socket. The calls made in one turn go
|
|
@@ -480,7 +503,7 @@ function doorCalls(handle, binding, first) {
|
|
|
480
503
|
});
|
|
481
504
|
}
|
|
482
505
|
const started = performance.now();
|
|
483
|
-
let response;
|
|
506
|
+
let response, text;
|
|
484
507
|
try {
|
|
485
508
|
response = await fetchAt(`${door.url}/call`, {
|
|
486
509
|
method: "POST",
|
|
@@ -488,8 +511,10 @@ function doorCalls(handle, binding, first) {
|
|
|
488
511
|
authorization: `Bearer ${token}`,
|
|
489
512
|
"content-type": "application/json"
|
|
490
513
|
},
|
|
491
|
-
body
|
|
514
|
+
body,
|
|
515
|
+
signal: AbortSignal.timeout(DOOR_CALL_MS)
|
|
492
516
|
});
|
|
517
|
+
text = await response.text();
|
|
493
518
|
} catch (error) {
|
|
494
519
|
if (tries < 2) continue;
|
|
495
520
|
return all({
|
|
@@ -498,7 +523,6 @@ function doorCalls(handle, binding, first) {
|
|
|
498
523
|
error: `couldn't reach the database bound as ${binding} (${error instanceof Error ? error.message : String(error)})`
|
|
499
524
|
});
|
|
500
525
|
}
|
|
501
|
-
const text = await response.text();
|
|
502
526
|
now().note?.(`db-call;dur=${(performance.now() - started).toFixed(1)};desc="${response.status}, ${ops.length} call${ops.length === 1 ? "" : "s"}"`);
|
|
503
527
|
if (response.status === 401 && tries === 0) {
|
|
504
528
|
try {
|
|
@@ -515,13 +539,19 @@ function doorCalls(handle, binding, first) {
|
|
|
515
539
|
if (response.status === 404 && refused.error === "not_found" && !remade && asker.remake) {
|
|
516
540
|
remade = true;
|
|
517
541
|
const at = door.url;
|
|
518
|
-
let
|
|
542
|
+
let asked = remaking.get(asker);
|
|
543
|
+
if (!asked) {
|
|
544
|
+
asked = /* @__PURE__ */ new Map();
|
|
545
|
+
remaking.set(asker, asked);
|
|
546
|
+
}
|
|
547
|
+
const mine = asked;
|
|
548
|
+
let asking = mine.get(at);
|
|
519
549
|
if (!asking) {
|
|
520
550
|
const made = asker.remake(binding, since).catch(() => false).finally(() => {
|
|
521
|
-
if (
|
|
551
|
+
if (mine.get(at) === made) mine.delete(at);
|
|
522
552
|
});
|
|
523
553
|
asking = made;
|
|
524
|
-
|
|
554
|
+
mine.set(at, made);
|
|
525
555
|
}
|
|
526
556
|
if (await asking) continue;
|
|
527
557
|
}
|
|
@@ -558,6 +588,13 @@ function doorCalls(handle, binding, first) {
|
|
|
558
588
|
...each.op
|
|
559
589
|
}))).then((answerOf) => {
|
|
560
590
|
part.forEach((each, n) => each.done(answerOf(n + 1)));
|
|
591
|
+
}, (error) => {
|
|
592
|
+
part.forEach((each, n) => each.done({
|
|
593
|
+
i: n + 1,
|
|
594
|
+
ok: false,
|
|
595
|
+
why: "unavailable",
|
|
596
|
+
error: `the call to the database bound as ${binding} failed (${error instanceof Error ? error.message : String(error)})`
|
|
597
|
+
}));
|
|
561
598
|
});
|
|
562
599
|
}
|
|
563
600
|
};
|
|
@@ -1080,4 +1117,4 @@ function oidc(getToken) {
|
|
|
1080
1117
|
return async ({ forceRefreshToken }) => await getToken(forceRefreshToken) || null;
|
|
1081
1118
|
}
|
|
1082
1119
|
//#endregion
|
|
1083
|
-
export {
|
|
1120
|
+
export { clerk as a, oidc as c, userToken as d, auth0 as i, profileClaims as l, DatabaseClient as n, connect as o, PROFILE_MOST as r, databaseUrl as s, DATABASE_TOKEN_PATH as t, signedInDatabase as u };
|
package/database/client.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { n as DatabaseErrorCode, t as DatabaseError } from "../errors-CnQduDOt.mjs";
|
|
2
|
-
import { _ as
|
|
3
|
-
export { ArgsOf, AuthState, BoundDatabases, ConnectOptions, DATABASE_TOKEN_PATH, Database, DatabaseClient, DatabaseError, type DatabaseErrorCode, DatabaseToken, FetchToken, Reference, ReturnsOf, SignedInDatabase, auth0, clerk, connect, databaseUrl, oidc, signedInDatabase, userToken };
|
|
2
|
+
import { S as userToken, _ as connect, a as DATABASE_TOKEN_PATH, b as profileClaims, c as DatabaseToken, d as Reference, f as ReturnsOf, g as clerk, h as auth0, i as ConnectOptions, l as FetchToken, m as UserProfile, n as AuthState, o as Database, p as SignedInDatabase, r as BoundDatabases, s as DatabaseClient, t as ArgsOf, u as PROFILE_MOST, v as databaseUrl, x as signedInDatabase, y as oidc } from "../client-COPmSTKM.mjs";
|
|
3
|
+
export { ArgsOf, AuthState, BoundDatabases, ConnectOptions, DATABASE_TOKEN_PATH, Database, DatabaseClient, DatabaseError, type DatabaseErrorCode, DatabaseToken, FetchToken, PROFILE_MOST, Reference, ReturnsOf, SignedInDatabase, UserProfile, auth0, clerk, connect, databaseUrl, oidc, profileClaims, signedInDatabase, userToken };
|
package/database/client.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { DatabaseError } from "./errors.mjs";
|
|
2
|
-
import { a as
|
|
3
|
-
export { DATABASE_TOKEN_PATH, DatabaseClient, DatabaseError, auth0, clerk, connect, databaseUrl, oidc, signedInDatabase, userToken };
|
|
2
|
+
import { a as clerk, c as oidc, d as userToken, i as auth0, l as profileClaims, n as DatabaseClient, o as connect, r as PROFILE_MOST, s as databaseUrl, t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-G20sA352.mjs";
|
|
3
|
+
export { DATABASE_TOKEN_PATH, DatabaseClient, DatabaseError, PROFILE_MOST, auth0, clerk, connect, databaseUrl, oidc, profileClaims, signedInDatabase, userToken };
|
package/database/react.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as DatabaseError } from "../errors-CnQduDOt.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { d as Reference, o as Database } from "../client-COPmSTKM.mjs";
|
|
3
3
|
import { ReactNode } from "react";
|
|
4
4
|
//#region src/database/react.d.ts
|
|
5
5
|
type ArgsOf<F> = F extends Reference<any, infer A, any> ? A : never;
|
|
@@ -233,7 +233,8 @@ const repairHint = {
|
|
|
233
233
|
prisma: "Make the listed fields optional in your Prisma schema, give them defaults, or remove them."
|
|
234
234
|
};
|
|
235
235
|
const migrationHint = {
|
|
236
|
-
|
|
236
|
+
drizzle: applyHint.drizzle,
|
|
237
|
+
prisma: applyHint.prisma,
|
|
237
238
|
database: "Run `npx auth migrate` to add the missing tables and columns."
|
|
238
239
|
};
|
|
239
240
|
function formatSchemaMismatch(findings, source) {
|
|
@@ -48434,7 +48435,8 @@ function buildEngine(config) {
|
|
|
48434
48435
|
return {
|
|
48435
48436
|
handler: (request) => instance.handler(request),
|
|
48436
48437
|
api: instance.api,
|
|
48437
|
-
findUser: async (id) => await (await instance.$context).internalAdapter.findUserById(id) ?? null
|
|
48438
|
+
findUser: async (id) => await (await instance.$context).internalAdapter.findUserById(id) ?? null,
|
|
48439
|
+
ready: instance.$context.then(() => void 0)
|
|
48438
48440
|
};
|
|
48439
48441
|
}
|
|
48440
48442
|
//#endregion
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as AuthStore } from "./store-
|
|
1
|
+
import { n as AuthStore } from "./store-BpA6Q5Z_.mjs";
|
|
2
2
|
import { n as CaptchaProvider, t as AuthSettings } from "./settings-Dz3irtlu.mjs";
|
|
3
3
|
import { SignInMail } from "./auth/mail.mjs";
|
|
4
4
|
//#region src/auth/events.d.ts
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@midsummer-ai/sdk",
|
|
3
|
-
"version": "0.1.0-staging.
|
|
3
|
+
"version": "0.1.0-staging.3775",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Midsummer's handles for an app's code: its Database, Storage, Queues, Vector DB, AI, Email and Agents, with stand-ins for tests.",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { o as Database } from "./client-
|
|
1
|
+
import { o as Database } from "./client-COPmSTKM.mjs";
|
|
2
2
|
//#region src/auth/store.d.ts
|
|
3
3
|
/** One of `db/auth.ts`'s functions. */
|
|
4
4
|
type AuthCall = "create" | "findOne" | "findMany" | "count" | "update" | "updateMany" | "upsert" | "deleteMany" | "consume" | "increment" | "page";
|
|
@@ -9,8 +9,9 @@ interface AuthStore {
|
|
|
9
9
|
/**
|
|
10
10
|
* The app's database as sign-in's store: each call one of `db/auth.ts`'s functions. `database` gives the
|
|
11
11
|
* connection a call goes over; it is asked for one each call, so it can hand out the request's own. A function
|
|
12
|
-
* that isn't there means `db/auth.ts` was never deployed: the error says to run `midsummer auth init`.
|
|
12
|
+
* that isn't there means `db/auth.ts` was never deployed: the error says to run `midsummer auth init`. A call
|
|
13
|
+
* unanswered after `waitMs` (`STORE_CALL_MS`) throws, so a request never waits on the database for longer.
|
|
13
14
|
*/
|
|
14
|
-
declare function databaseStore(database: () => Promise<Database
|
|
15
|
+
declare function databaseStore(database: () => Promise<Database>, waitMs?: number): AuthStore;
|
|
15
16
|
//#endregion
|
|
16
17
|
export { AuthStore as n, databaseStore as r, AuthCall as t };
|