@geekmidas/constructs 10.0.0-alpha.147 → 10.0.0-alpha.148
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/{Cron-CQoDSu-n.d.mts → Cron-D8mB_cPX.d.mts} +2 -2
- package/dist/{Cron-CFkpEys6.d.cts.map → Cron-D8mB_cPX.d.mts.map} +1 -1
- package/dist/{Cron-CFkpEys6.d.cts → Cron-D_sfaMGz.d.cts} +2 -2
- package/dist/{Cron-CQoDSu-n.d.mts.map → Cron-D_sfaMGz.d.cts.map} +1 -1
- package/dist/{CronBuilder-OaCRRFVk.d.cts → CronBuilder-C91MVLSr.d.cts} +4 -4
- package/dist/{CronBuilder-1W-G_i15.d.mts.map → CronBuilder-C91MVLSr.d.cts.map} +1 -1
- package/dist/{CronBuilder-1W-G_i15.d.mts → CronBuilder-Cmajva3g.d.mts} +4 -4
- package/dist/{CronBuilder-OaCRRFVk.d.cts.map → CronBuilder-Cmajva3g.d.mts.map} +1 -1
- package/dist/{Endpoint-BcUorcBa.cjs → Endpoint-52z1P0Ue.cjs} +9 -4
- package/dist/Endpoint-52z1P0Ue.cjs.map +1 -0
- package/dist/{Endpoint-DTXDggNl.d.mts → Endpoint-BbHh3Qoc.d.mts} +5 -5
- package/dist/{Endpoint-BEh-jW-f.d.cts.map → Endpoint-BbHh3Qoc.d.mts.map} +1 -1
- package/dist/{Endpoint-BEh-jW-f.d.cts → Endpoint-YYwjqtS1.d.cts} +5 -5
- package/dist/{Endpoint-DTXDggNl.d.mts.map → Endpoint-YYwjqtS1.d.cts.map} +1 -1
- package/dist/{Endpoint-BgvG36NO.mjs → Endpoint-sUOU7uLx.mjs} +9 -4
- package/dist/Endpoint-sUOU7uLx.mjs.map +1 -0
- package/dist/{EndpointFactory-C1NlpCAS.mjs → EndpointFactory-Bzi9Sl7r.mjs} +2 -2
- package/dist/{EndpointFactory-C1NlpCAS.mjs.map → EndpointFactory-Bzi9Sl7r.mjs.map} +1 -1
- package/dist/{EndpointFactory-gqmIRVWg.cjs → EndpointFactory-Cf_Cs1ym.cjs} +2 -2
- package/dist/{EndpointFactory-gqmIRVWg.cjs.map → EndpointFactory-Cf_Cs1ym.cjs.map} +1 -1
- package/dist/{EndpointFactory-B2dCS9dy.d.cts → EndpointFactory-Hh1r6J_C.d.cts} +5 -5
- package/dist/{EndpointFactory-B2dCS9dy.d.cts.map → EndpointFactory-Hh1r6J_C.d.cts.map} +1 -1
- package/dist/{EndpointFactory-D2HXcUrJ.d.mts → EndpointFactory-qcLzi4f-.d.mts} +5 -5
- package/dist/{EndpointFactory-D2HXcUrJ.d.mts.map → EndpointFactory-qcLzi4f-.d.mts.map} +1 -1
- package/dist/{HonoEndpointAdaptor-BJlj20fQ.cjs → HonoEndpointAdaptor-BXBdb2Bt.cjs} +2 -2
- package/dist/{HonoEndpointAdaptor-BJlj20fQ.cjs.map → HonoEndpointAdaptor-BXBdb2Bt.cjs.map} +1 -1
- package/dist/{HonoEndpointAdaptor-BlbkUDNo.mjs → HonoEndpointAdaptor-DR3j7S35.mjs} +2 -2
- package/dist/{HonoEndpointAdaptor-BlbkUDNo.mjs.map → HonoEndpointAdaptor-DR3j7S35.mjs.map} +1 -1
- package/dist/{ObjectSubscriberBuilder-CzgYmOUH.d.mts → ObjectSubscriberBuilder-Cv8C7yS1.d.mts} +2 -2
- package/dist/{ObjectSubscriberBuilder-BuuaYcrm.d.cts.map → ObjectSubscriberBuilder-Cv8C7yS1.d.mts.map} +1 -1
- package/dist/{ObjectSubscriberBuilder-BuuaYcrm.d.cts → ObjectSubscriberBuilder-LWkey_oq.d.cts} +2 -2
- package/dist/{ObjectSubscriberBuilder-CzgYmOUH.d.mts.map → ObjectSubscriberBuilder-LWkey_oq.d.cts.map} +1 -1
- package/dist/{ProcessorBuilder-B2_stA8f.d.mts → ProcessorBuilder-CwfP-M33.d.mts} +2 -2
- package/dist/{ProcessorBuilder-B2_stA8f.d.mts.map → ProcessorBuilder-CwfP-M33.d.mts.map} +1 -1
- package/dist/{ProcessorBuilder-C62bIOwj.d.cts → ProcessorBuilder-_jdZlbfW.d.cts} +2 -2
- package/dist/{ProcessorBuilder-C62bIOwj.d.cts.map → ProcessorBuilder-_jdZlbfW.d.cts.map} +1 -1
- package/dist/{QueueBuilder-B3vL1ED2.d.mts → QueueBuilder-DmwFtLzQ.d.mts} +2 -2
- package/dist/{QueueBuilder-B3vL1ED2.d.mts.map → QueueBuilder-DmwFtLzQ.d.mts.map} +1 -1
- package/dist/{QueueBuilder-BcPBQSSX.d.cts → QueueBuilder-SQli59An.d.cts} +2 -2
- package/dist/{QueueBuilder-BcPBQSSX.d.cts.map → QueueBuilder-SQli59An.d.cts.map} +1 -1
- package/dist/adaptors/aws.cjs +1 -1
- package/dist/adaptors/aws.d.cts +2 -2
- package/dist/adaptors/aws.d.mts +2 -2
- package/dist/adaptors/aws.mjs +1 -1
- package/dist/adaptors/hono.cjs +1 -1
- package/dist/adaptors/hono.d.cts +1 -1
- package/dist/adaptors/hono.d.mts +1 -1
- package/dist/adaptors/hono.mjs +1 -1
- package/dist/adaptors/testing.cjs +2 -2
- package/dist/adaptors/testing.d.cts +4 -4
- package/dist/adaptors/testing.d.mts +4 -4
- package/dist/adaptors/testing.mjs +2 -2
- package/dist/{auth-D_0788uW.d.mts → auth-BqWz2JxC.d.cts} +13 -7
- package/dist/{auth-BMCJN30Y.d.cts.map → auth-BqWz2JxC.d.cts.map} +1 -1
- package/dist/{auth-BMCJN30Y.d.cts → auth-DnB9H9KL.d.mts} +13 -7
- package/dist/{auth-D_0788uW.d.mts.map → auth-DnB9H9KL.d.mts.map} +1 -1
- package/dist/auth.cjs +70 -15
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.d.cts +1 -1
- package/dist/auth.d.mts +1 -1
- package/dist/auth.mjs +71 -16
- package/dist/auth.mjs.map +1 -1
- package/dist/{cache-5QZzh5Er.d.mts → cache-CQjMNPrC.d.cts} +3 -3
- package/dist/{cache-5QZzh5Er.d.mts.map → cache-CQjMNPrC.d.cts.map} +1 -1
- package/dist/{cache-DnGDGly3.d.cts → cache-e3tfMQ9g.d.mts} +3 -3
- package/dist/{cache-DnGDGly3.d.cts.map → cache-e3tfMQ9g.d.mts.map} +1 -1
- package/dist/cache.d.cts +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/{construct-interface-B1AfqRl4.d.cts → construct-interface-CSA9VeWM.d.mts} +9 -4
- package/dist/{construct-interface-B1AfqRl4.d.cts.map → construct-interface-CSA9VeWM.d.mts.map} +1 -1
- package/dist/{construct-interface-ZvYQbivO.d.mts → construct-interface-DugP0E5q.d.cts} +9 -4
- package/dist/{construct-interface-ZvYQbivO.d.mts.map → construct-interface-DugP0E5q.d.cts.map} +1 -1
- package/dist/construct-interface.cjs +8 -0
- package/dist/construct-interface.cjs.map +1 -1
- package/dist/construct-interface.d.cts +2 -2
- package/dist/construct-interface.d.mts +2 -2
- package/dist/construct-interface.mjs +8 -1
- package/dist/construct-interface.mjs.map +1 -1
- package/dist/credential.d.cts +1 -1
- package/dist/credential.d.mts +1 -1
- package/dist/crons/index.d.cts +2 -2
- package/dist/crons/index.d.mts +2 -2
- package/dist/database/kysely.d.cts +1 -1
- package/dist/database/kysely.d.mts +1 -1
- package/dist/email.d.cts +1 -1
- package/dist/email.d.mts +1 -1
- package/dist/encryption.d.cts +1 -1
- package/dist/encryption.d.mts +1 -1
- package/dist/endpoints/index.cjs +2 -2
- package/dist/endpoints/index.d.cts +2 -2
- package/dist/endpoints/index.d.mts +2 -2
- package/dist/endpoints/index.mjs +2 -2
- package/dist/external-api.d.cts +1 -1
- package/dist/external-api.d.mts +1 -1
- package/dist/{fake-D472nkKb.d.mts → fake-BqhP8RRQ.d.mts} +2 -2
- package/dist/{fake-BUgcX2Dk.d.cts.map → fake-BqhP8RRQ.d.mts.map} +1 -1
- package/dist/{fake-BUgcX2Dk.d.cts → fake-DqieDYYA.d.cts} +2 -2
- package/dist/{fake-D472nkKb.d.mts.map → fake-DqieDYYA.d.cts.map} +1 -1
- package/dist/file-server.d.cts +3 -3
- package/dist/file-server.d.mts +3 -3
- package/dist/functions/index.d.cts +1 -1
- package/dist/functions/index.d.mts +1 -1
- package/dist/{inbox-DqaxrpEk.d.cts → inbox-CR3L1fOI.d.cts} +2 -2
- package/dist/{inbox-DZdICa8F.d.mts.map → inbox-CR3L1fOI.d.cts.map} +1 -1
- package/dist/{inbox-DZdICa8F.d.mts → inbox-CjxpLVkH.d.mts} +2 -2
- package/dist/{inbox-DqaxrpEk.d.cts.map → inbox-CjxpLVkH.d.mts.map} +1 -1
- package/dist/inbox.d.cts +1 -1
- package/dist/inbox.d.mts +1 -1
- package/dist/{index-DuriFjYD.d.mts → index-DCkDQkwj.d.mts} +2 -2
- package/dist/{index-BtzMzhMA.d.cts.map → index-DCkDQkwj.d.mts.map} +1 -1
- package/dist/{index-BtzMzhMA.d.cts → index-DPTHa6Ud.d.cts} +2 -2
- package/dist/{index-DuriFjYD.d.mts.map → index-DPTHa6Ud.d.cts.map} +1 -1
- package/dist/{kysely-BHYV-WC-.d.cts → kysely-CebjCWTl.d.cts} +3 -3
- package/dist/{kysely-BHYV-WC-.d.cts.map → kysely-CebjCWTl.d.cts.map} +1 -1
- package/dist/{kysely-CAW3QSqp.d.mts → kysely-DE4kADWD.d.mts} +3 -3
- package/dist/{kysely-CAW3QSqp.d.mts.map → kysely-DE4kADWD.d.mts.map} +1 -1
- package/dist/mobile-app.d.cts +1 -1
- package/dist/mobile-app.d.mts +1 -1
- package/dist/object-storage.d.cts +1 -1
- package/dist/object-storage.d.mts +1 -1
- package/dist/processors/index.d.cts +1 -1
- package/dist/processors/index.d.mts +1 -1
- package/dist/queue/index.d.cts +1 -1
- package/dist/queue/index.d.mts +1 -1
- package/dist/random-password.d.cts +1 -1
- package/dist/random-password.d.mts +1 -1
- package/dist/rest-api.cjs +12 -1
- package/dist/rest-api.cjs.map +1 -1
- package/dist/rest-api.d.cts +12 -5
- package/dist/rest-api.d.cts.map +1 -1
- package/dist/rest-api.d.mts +12 -5
- package/dist/rest-api.d.mts.map +1 -1
- package/dist/rest-api.mjs +14 -3
- package/dist/rest-api.mjs.map +1 -1
- package/dist/site.cjs +21 -4
- package/dist/site.cjs.map +1 -1
- package/dist/site.d.cts +10 -3
- package/dist/site.d.cts.map +1 -1
- package/dist/site.d.mts +10 -3
- package/dist/site.d.mts.map +1 -1
- package/dist/site.mjs +23 -6
- package/dist/site.mjs.map +1 -1
- package/dist/subscribers/index.d.cts +1 -1
- package/dist/subscribers/index.d.mts +1 -1
- package/dist/{telemetry-B48RLjyk.d.cts → telemetry-C1oqncFY.d.cts} +2 -2
- package/dist/{telemetry-B48RLjyk.d.cts.map → telemetry-C1oqncFY.d.cts.map} +1 -1
- package/dist/{telemetry-BEoBn6GO.d.mts → telemetry-CObow3Dn.d.mts} +2 -2
- package/dist/{telemetry-BEoBn6GO.d.mts.map → telemetry-CObow3Dn.d.mts.map} +1 -1
- package/dist/telemetry.d.cts +1 -1
- package/dist/telemetry.d.mts +1 -1
- package/dist/websocket-api.d.cts +2 -2
- package/dist/websocket-api.d.mts +2 -2
- package/dist/worker.d.cts +8 -8
- package/dist/worker.d.mts +8 -8
- package/package.json +31 -31
- package/dist/Endpoint-BcUorcBa.cjs.map +0 -1
- package/dist/Endpoint-BgvG36NO.mjs.map +0 -1
package/dist/auth.mjs
CHANGED
|
@@ -1,7 +1,34 @@
|
|
|
1
1
|
import { edgeTo } from "./construct-interface.mjs";
|
|
2
2
|
import { n as injectTraceContext } from "./tracing-Bbj1uoFJ.mjs";
|
|
3
|
-
import { CLIENT_IP_HEADER, canonicalId, environmentCase, isWebOrigin, provideKey, serviceKey } from "@geekmidas/manifest";
|
|
3
|
+
import { CLIENT_IP_HEADER, EDGE_TOKEN_HEADER, EDGE_TOKEN_KEY, canonicalId, environmentCase, isWebOrigin, provideKey, serviceKey } from "@geekmidas/manifest";
|
|
4
|
+
import { timingSafeEqual } from "node:crypto";
|
|
4
5
|
//#region src/auth.ts
|
|
6
|
+
/**
|
|
7
|
+
* `BetterAuth` — a declared auth server.
|
|
8
|
+
*
|
|
9
|
+
* It is three things at once, which is what makes it the construct that
|
|
10
|
+
* exercises most of the model: a consumer of a database, a producer of an
|
|
11
|
+
* authorizer, and a set of endpoints. This lands the first two.
|
|
12
|
+
*
|
|
13
|
+
* Its tables live in a schema tenant it is *given* — `orders.schema('AuthDb')`
|
|
14
|
+
* — rather than one it invents. The tenant declares the schema and the role;
|
|
15
|
+
* this declares the one thing left, the signing secret, and reads back the keys
|
|
16
|
+
* it needs.
|
|
17
|
+
*
|
|
18
|
+
* :::caution
|
|
19
|
+
* The isolation that arrangement is *for* — the application's own role holding
|
|
20
|
+
* no grant on these tables, so a compromised handler cannot read sessions — does
|
|
21
|
+
* **not hold yet**. No target creates the per-schema role: both connect as the
|
|
22
|
+
* database owner, so today the tenant is a `search_path`, which is a namespace
|
|
23
|
+
* and not a privilege boundary. See "Roles are declared and never created" in
|
|
24
|
+
* `docs/design/constructs-outstanding.md`.
|
|
25
|
+
* :::
|
|
26
|
+
*
|
|
27
|
+
* It declares its own surface, so where it answers, who may call it, and the
|
|
28
|
+
* domain its cookies are scoped to all arrive as environment resolved by the
|
|
29
|
+
* target — none of them guessed from a port, and none of them listed by hand in
|
|
30
|
+
* application config.
|
|
31
|
+
*/
|
|
5
32
|
const DEFAULT_BASE_PATH = "/api/auth";
|
|
6
33
|
var BetterAuth = class {
|
|
7
34
|
config;
|
|
@@ -101,9 +128,12 @@ var BetterAuth = class {
|
|
|
101
128
|
* that is all there is — so this is everything it can know.
|
|
102
129
|
*/
|
|
103
130
|
client(envParser) {
|
|
104
|
-
const { url } = envParser.create((get) => ({
|
|
131
|
+
const { url, edgeToken } = envParser.create((get) => ({
|
|
132
|
+
url: get(this.keys.url).string(),
|
|
133
|
+
edgeToken: get(EDGE_TOKEN_KEY).string().optional()
|
|
134
|
+
})).parse();
|
|
105
135
|
const endpoint = `${url.replace(/\/$/, "")}${this.basePath}`;
|
|
106
|
-
return { api: { getSession: ({ headers }) => fetchSession(this.id, endpoint, new Headers(headers)) } };
|
|
136
|
+
return { api: { getSession: ({ headers }) => fetchSession(this.id, endpoint, new Headers(headers), edgeToken) } };
|
|
107
137
|
}
|
|
108
138
|
/**
|
|
109
139
|
* The tenant this server keeps its tables in — whose migrations folder,
|
|
@@ -165,7 +195,10 @@ var BetterAuth = class {
|
|
|
165
195
|
const { cors } = await import("hono/cors");
|
|
166
196
|
const app = new Hono();
|
|
167
197
|
const server = await this.connect(options);
|
|
168
|
-
const { origins } = options.envParser.create((get) => ({
|
|
198
|
+
const { origins, edgeToken } = options.envParser.create((get) => ({
|
|
199
|
+
edgeToken: get(EDGE_TOKEN_KEY).string().optional(),
|
|
200
|
+
origins: get(this.keys.trustedOrigins).string().default("").transform((value) => value.split(",").map((origin) => origin.trim()).filter(Boolean))
|
|
201
|
+
})).parse();
|
|
169
202
|
app.use("*", cors({
|
|
170
203
|
origin: origins,
|
|
171
204
|
credentials: true,
|
|
@@ -181,7 +214,7 @@ var BetterAuth = class {
|
|
|
181
214
|
"DELETE",
|
|
182
215
|
"OPTIONS"
|
|
183
216
|
] : [endpoint.method];
|
|
184
|
-
app.on([...methods], endpoint.path, (c) => server.handler(withTrustedClientIp(c.req.raw, remoteAddressOf(c))));
|
|
217
|
+
app.on([...methods], endpoint.path, (c) => server.handler(withTrustedClientIp(c.req.raw, remoteAddressOf(c), edgeToken)));
|
|
185
218
|
}
|
|
186
219
|
return {
|
|
187
220
|
app,
|
|
@@ -306,27 +339,42 @@ var ExpoPluginRequired = class extends Error {
|
|
|
306
339
|
this.name = "ExpoPluginRequired";
|
|
307
340
|
}
|
|
308
341
|
};
|
|
309
|
-
/**
|
|
310
|
-
|
|
342
|
+
/**
|
|
343
|
+
* What is forwarded to the auth server: the headers a session travels in, and
|
|
344
|
+
* the origin the request came from. The API calls the auth server at its
|
|
345
|
+
* public address, through the edge, which marks the call as outside traffic;
|
|
346
|
+
* the origin is what lets the auth server continue the trace exactly when
|
|
347
|
+
* the API did — for a request from one of the sites both trust.
|
|
348
|
+
*/
|
|
349
|
+
const SESSION_HEADERS = [
|
|
350
|
+
"cookie",
|
|
351
|
+
"authorization",
|
|
352
|
+
"origin"
|
|
353
|
+
];
|
|
311
354
|
/**
|
|
312
355
|
* `GET <basePath>/get-session`, read the way Better Auth answers it.
|
|
313
356
|
*
|
|
314
357
|
* Whose request it is travels in {@link CLIENT_IP_HEADER} — the server
|
|
315
358
|
* rate-limits `/get-session` by the client's address, so without it every
|
|
316
|
-
* caller shares the API's one bucket — and never as `X-Forwarded-For
|
|
317
|
-
*
|
|
318
|
-
*
|
|
319
|
-
*
|
|
320
|
-
*
|
|
359
|
+
* caller shares the API's one bucket — and never as `X-Forwarded-For`, which
|
|
360
|
+
* marks a request as outside traffic. The call goes to the auth server's
|
|
361
|
+
* public address, through the stack's edge, so the stack's token goes with
|
|
362
|
+
* it ({@link EDGE_TOKEN_HEADER}): the edge keeps gkm's header only on a
|
|
363
|
+
* request carrying it, and the auth server honours it from one. The
|
|
364
|
+
* request's `Origin` is passed on so the trace is continued for a site both
|
|
365
|
+
* trust.
|
|
321
366
|
*/
|
|
322
|
-
async function fetchSession(authenticator, endpoint, given) {
|
|
367
|
+
async function fetchSession(authenticator, endpoint, given, edgeToken) {
|
|
323
368
|
const headers = new Headers();
|
|
324
369
|
for (const name of SESSION_HEADERS) {
|
|
325
370
|
const value = given.get(name);
|
|
326
371
|
if (value) headers.set(name, value);
|
|
327
372
|
}
|
|
328
373
|
const client = given.get("x-forwarded-for");
|
|
329
|
-
if (client)
|
|
374
|
+
if (client) {
|
|
375
|
+
headers.set(CLIENT_IP_HEADER, client);
|
|
376
|
+
if (edgeToken) headers.set(EDGE_TOKEN_HEADER, edgeToken);
|
|
377
|
+
}
|
|
330
378
|
injectTraceContext(headers);
|
|
331
379
|
const url = `${endpoint}/get-session`;
|
|
332
380
|
let response;
|
|
@@ -394,13 +442,20 @@ const FORWARDING_HEADERS = [
|
|
|
394
442
|
* does not — a platform's proxy, a port published straight to the internet —
|
|
395
443
|
* so a stranger cannot pick the address Better Auth rate-limits them by.
|
|
396
444
|
*/
|
|
397
|
-
function withTrustedClientIp(request, remoteAddress) {
|
|
445
|
+
function withTrustedClientIp(request, remoteAddress, edgeToken) {
|
|
398
446
|
if (!request.headers.has(CLIENT_IP_HEADER)) return request;
|
|
399
|
-
if (!request.headers.has("origin") && !FORWARDING_HEADERS.some((name) => request.headers.has(name)) && isPrivateAddress(remoteAddress)) return request;
|
|
447
|
+
if (!request.headers.has("origin") && !FORWARDING_HEADERS.some((name) => request.headers.has(name)) && isPrivateAddress(remoteAddress) || sameToken(request.headers.get(EDGE_TOKEN_HEADER), edgeToken)) return request;
|
|
400
448
|
const headers = new Headers(request.headers);
|
|
401
449
|
headers.delete(CLIENT_IP_HEADER);
|
|
402
450
|
return new Request(request, { headers });
|
|
403
451
|
}
|
|
452
|
+
/** Whether a request's token is the stack's, compared in constant time. */
|
|
453
|
+
function sameToken(sent, expected) {
|
|
454
|
+
if (!sent || !expected) return false;
|
|
455
|
+
const a = Buffer.from(sent);
|
|
456
|
+
const b = Buffer.from(expected);
|
|
457
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
458
|
+
}
|
|
404
459
|
/** The TCP peer of a request served by `@hono/node-server`, when there is one. */
|
|
405
460
|
function remoteAddressOf(c) {
|
|
406
461
|
return c.env?.incoming?.socket?.remoteAddress;
|
package/dist/auth.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.mjs","names":[],"sources":["../src/auth.ts"],"sourcesContent":["/**\n * `BetterAuth` — a declared auth server.\n *\n * It is three things at once, which is what makes it the construct that\n * exercises most of the model: a consumer of a database, a producer of an\n * authorizer, and a set of endpoints. This lands the first two.\n *\n * Its tables live in a schema tenant it is *given* — `orders.schema('AuthDb')`\n * — rather than one it invents. The tenant declares the schema and the role;\n * this declares the one thing left, the signing secret, and reads back the keys\n * it needs.\n *\n * :::caution\n * The isolation that arrangement is *for* — the application's own role holding\n * no grant on these tables, so a compromised handler cannot read sessions — does\n * **not hold yet**. No target creates the per-schema role: both connect as the\n * database owner, so today the tenant is a `search_path`, which is a namespace\n * and not a privilege boundary. See \"Roles are declared and never created\" in\n * `docs/design/constructs-outstanding.md`.\n * :::\n *\n * It declares its own surface, so where it answers, who may call it, and the\n * domain its cookies are scoped to all arrive as environment resolved by the\n * target — none of them guessed from a port, and none of them listed by hand in\n * application config.\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport {\n\tCLIENT_IP_HEADER,\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tenvironmentCase,\n\tisWebOrigin,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type {\n\tService,\n\tServiceRecord,\n\tServiceRegisterOptions,\n} from '@geekmidas/services';\n// Types only: the server is built in `connect()`, from a dynamic import, so a\n// process that only holds the client never loads better-auth to get it.\nimport type { betterAuth } from 'better-auth';\nimport type { Hono } from 'hono';\nimport type { Kysely } from 'kysely';\nimport {\n\ttype Authenticator,\n\ttype Construct,\n\ttype Consumable,\n\tedgeTo,\n\ttype ServicesOf,\n} from './construct-interface';\nimport type { Telemetry } from './telemetry';\nimport { injectTraceContext } from './tracing';\n\n/** The server better-auth hands back. */\nexport type AuthServer = ReturnType<typeof betterAuth>;\n\n/** A signed-in session as better-auth hands it back: `{ user, session }`. */\nexport type AuthSession = AuthServer['$Infer']['Session'];\n\n/**\n * What `.dependsOn([auth])` hands a handler: the auth server, over HTTP.\n *\n * The server itself — its secret, its tenant's connection, its mailer — lives\n * in the auth app's own process and nowhere else. Every other process is a\n * caller of it, so what it is given is an address and this, with the one\n * call handlers make kept in Better Auth's shape: `api.getSession({ headers })`\n * answers `{ user, session }` or `null`, as the server's own `api` does.\n */\nexport interface AuthClient {\n\treadonly api: {\n\t\t/**\n\t\t * The session the request's cookie or bearer token belongs to, or `null`\n\t\t * when there is none — asked of `<basePath>/get-session` at the auth\n\t\t * server's URL. Only `cookie` and `authorization` are forwarded, with\n\t\t * the client's address as `x-gkm-client-ip` (read from the request's\n\t\t * `x-forwarded-for`) and the active trace context.\n\t\t *\n\t\t * @throws {AuthServerUnreachable} when the request does not get there.\n\t\t * @throws {SessionCheckFailed} when the server answers with a failure.\n\t\t */\n\t\tgetSession(input: {\n\t\t\theaders: ConstructorParameters<typeof Headers>[0];\n\t\t}): Promise<AuthSession | null>;\n\t};\n}\n\n/** Everything better-auth takes, minus what the construct owns. */\nexport type BetterAuthOptions = Omit<\n\tParameters<typeof betterAuth>[0],\n\t'database' | 'secret' | 'basePath' | 'baseURL'\n>;\n\n/**\n * What an `options` callback is handed: the options this construct was\n * registered with, and a client for each construct its `dependsOn` names —\n * keyed by service name, exactly as an endpoint's handler receives them.\n */\nexport type BetterAuthOptionsContext<TUses extends readonly Consumable[]> =\n\tServiceRegisterOptions & {\n\t\tservices: ServiceRecord<[...ServicesOf<TUses>]>;\n\t};\n\nexport interface BetterAuthConfig<\n\tTDatabase extends Consumable,\n\tTUses extends readonly Consumable[] = readonly [],\n> {\n\t/**\n\t * The schema tenant its tables live in.\n\t *\n\t * A construct rather than a URL: the tenant already declares its schema and\n\t * its role, and taking the declaration is what puts the edge in the graph\n\t * instead of a connection string in two places.\n\t */\n\tdatabase: TDatabase;\n\t/**\n\t * The app that serves this auth server, relative to the workspace root —\n\t * `'apps/auth'`.\n\t *\n\t * Required, for the reason `RestApi.path` is. Not to be confused with\n\t * `basePath`, which is where its routes are mounted in a URL.\n\t */\n\tpath: string;\n\t/**\n\t * The label it answers on under a stage's domain — `api` for\n\t * `api.myapp.com`, from `domains` — and under the project locally,\n\t * `api.myapp.localhost`. Absent, its id kebab-cased.\n\t */\n\tsubdomain?: string;\n\t/**\n\t * Where the auth routes are mounted, e.g. `/api/auth`.\n\t *\n\t * Structural — it is part of the URL every client calls, so it cannot differ\n\t * between stages the way the host can.\n\t */\n\tbasePath?: string;\n\t/**\n\t * The constructs `options` uses — the mailer a magic link goes through,\n\t * most often.\n\t *\n\t * One list, two jobs, the way an endpoint's `.dependsOn()` has: each is an\n\t * edge on the server's handler, so whatever is composed from the edges (a\n\t * container's environment, a deploy's grants) includes it; and each is\n\t * handed to `options` as a client in `services`, so there is no other way\n\t * for `options` to reach it — nothing to import and register by hand, and\n\t * so nothing that can be used without being declared.\n\t */\n\tdependsOn?: TUses;\n\t/**\n\t * What the auth server's process emits — the `Telemetry` construct, passed\n\t * like a `RestApi`'s. An edge to the node: the deploy hands the process the\n\t * `OTEL_*` keys its stage resolves.\n\t */\n\ttelemetry?: Telemetry;\n\t/**\n\t * The rest of better-auth's options: providers, plugins, email settings.\n\t *\n\t * A function when they need another construct — a magic-link plugin has to\n\t * *send* the link. It is handed the options this construct was registered\n\t * with, and `services`: a client for each construct in `dependsOn`.\n\t */\n\toptions?:\n\t\t| BetterAuthOptions\n\t\t| ((\n\t\t\t\tcontext: BetterAuthOptionsContext<TUses>,\n\t\t ) => BetterAuthOptions | Promise<BetterAuthOptions>);\n}\n\nconst DEFAULT_BASE_PATH = '/api/auth';\n\nexport class BetterAuth<\n\tTName extends string = string,\n\tTDatabase extends Consumable = Consumable,\n\tconst TUses extends readonly Consumable[] = readonly [],\n> implements Construct<TName, AuthClient>, Authenticator<AuthSession>\n{\n\treadonly id: TName;\n\t/**\n\t * What `.dependsOn([auth])` injects: an {@link AuthClient}, never the server.\n\t *\n\t * Which of the two a process holds is decided by how it reaches the\n\t * construct, not by asking where it is running. The auth app's process is\n\t * its generated entry, which calls {@link server} and nothing else — a\n\t * self-serving surface has no endpoints of its own for a `dependsOn` to sit\n\t * on. Every other process reaches it through this. So the API, a worker, a\n\t * test's in-process endpoints all get the client, and none of them needs\n\t * the signing secret, the auth tenant's URL or the mailer to start.\n\t */\n\treadonly service: Service<Uncapitalize<TName>, AuthClient>;\n\treadonly basePath: string;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the keys the\n\t * target publishes and the keys the server reads cannot drift.\n\t */\n\tprivate readonly keys: {\n\t\tsecretId: string;\n\t\tsecret: string;\n\t\turl: string;\n\t\ttrustedOrigins: string;\n\t\tcookieDomain: string;\n\t};\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: BetterAuthConfig<TDatabase, TUses>,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.basePath = config.basePath ?? DEFAULT_BASE_PATH;\n\n\t\t// A secret's name is its key: `Auth` signs with `AUTH_SECRET`, which is\n\t\t// also what better-auth's own tooling looks for.\n\t\tconst secretId = `${canonical}Secret`;\n\t\tthis.keys = {\n\t\t\tsecretId,\n\t\t\tsecret: environmentCase(secretId),\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\ttrustedOrigins: provideKey(canonical, 'trustedOrigins'),\n\t\t\tcookieDomain: provideKey(canonical, 'cookieDomain'),\n\t\t};\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (options) => this.client(options.envParser),\n\t\t};\n\t}\n\n\t/**\n\t * A signing secret and a surface.\n\t *\n\t * The database is *not* declared here — the tenant that was passed in\n\t * declares it, and declaring it twice is the duplication the whole model\n\t * removes. What is declared is what this construct owns: the key it signs\n\t * with, and the routes it answers on.\n\t *\n\t * One endpoint, wildcarded. Better Auth routes internally and the set of\n\t * paths depends on which capabilities are enabled, so enumerating them here\n\t * would be a copy of its router that goes stale on its next release. The\n\t * surface's job is to send everything under `basePath` to one handler, which\n\t * is exactly what the declaration says.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'secret',\n\t\t\t\tid: this.keys.secretId,\n\t\t\t\tprovides: [this.keys.secret],\n\t\t\t},\n\t\t\t{\n\t\t\t\tkind: 'rest-api',\n\t\t\t\tid: this.id,\n\t\t\t\tpath: this.config.path,\n\t\t\t\t...(this.config.subdomain ? { subdomain: this.config.subdomain } : {}),\n\t\t\t\t...(this.config.telemetry\n\t\t\t\t\t? { telemetry: this.config.telemetry.id }\n\t\t\t\t\t: {}),\n\t\t\t\tprovides: [\n\t\t\t\t\tthis.keys.url,\n\t\t\t\t\tthis.keys.trustedOrigins,\n\t\t\t\t\tthis.keys.cookieDomain,\n\t\t\t\t],\n\t\t\t\tservesItself: true,\n\t\t\t\tendpoints: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: `${this.id}Handler`,\n\t\t\t\t\t\thandler: `${this.id}.handler`,\n\t\t\t\t\t\tmethod: 'ANY',\n\t\t\t\t\t\tpath: `${this.basePath}/*`,\n\t\t\t\t\t\t// Read off the tenant rather than written down: this\n\t\t\t\t\t\t// construct takes whatever database it is given, and a\n\t\t\t\t\t\t// hardcoded kind is a second statement of a fact the\n\t\t\t\t\t\t// tenant already makes.\n\t\t\t\t\t\tdependencies: [\n\t\t\t\t\t\t\tedgeTo(this.config.database),\n\t\t\t\t\t\t\t...(this.config.dependsOn ?? []).map(edgeTo),\n\t\t\t\t\t\t],\n\t\t\t\t\t\trequires: [this.keys.secret],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * Whose request this is: the session for these headers, or `null`.\n\t *\n\t * Asked of the auth server over HTTP, at the URL the `.auth()` edge injects —\n\t * so it is the same call whether the server runs in this process, beside\n\t * it, or behind MSW in a test. The same call {@link AuthClient} makes.\n\t */\n\tasync verify(\n\t\theaders: Headers,\n\t\tenvParser: EnvironmentParser<{}>,\n\t): Promise<AuthSession | null> {\n\t\treturn this.client(envParser).api.getSession({ headers });\n\t}\n\n\t/**\n\t * The client a caller of this server holds: its URL and nothing else.\n\t *\n\t * `<ID>_URL` is the one key a consumer is given for an edge to a surface —\n\t * the compose network's address between containers, the public one where\n\t * that is all there is — so this is everything it can know.\n\t */\n\tclient(envParser: EnvironmentParser<{}>): AuthClient {\n\t\tconst { url } = envParser\n\t\t\t.create((get) => ({ url: get(this.keys.url).string() }))\n\t\t\t.parse();\n\t\tconst endpoint = `${url.replace(/\\/$/, '')}${this.basePath}`;\n\n\t\treturn {\n\t\t\tapi: {\n\t\t\t\tgetSession: ({ headers }) =>\n\t\t\t\t\tfetchSession(this.id, endpoint, new Headers(headers)),\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * The tenant this server keeps its tables in — whose migrations folder,\n\t * `db/<tenant>/`, Better Auth's schema is written into.\n\t */\n\tget databaseId(): string {\n\t\treturn this.config.database.id;\n\t}\n\n\t/**\n\t * The SQL that brings the tenant up to Better Auth's schema, or `undefined`\n\t * when it already matches.\n\t *\n\t * What `gkm migration` writes as the tenant's next migration, so Better\n\t * Auth's tables are committed, reviewed and applied like any other — rather\n\t * than diffed against the database at runtime, where a change nobody wrote\n\t * down happens on whichever machine migrates first.\n\t *\n\t * Compared as the owner, against the tenant `gkm migrate` has already brought\n\t * up to date: what comes back is only what the committed files are missing.\n\t */\n\tasync pendingMigration(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<string | undefined> {\n\t\t// The options, not a server built from them: better-auth checks its\n\t\t// schema when a server starts, and before the migration that creates the\n\t\t// tables it can only report them missing.\n\t\tconst resolved = await this.optionsFor(options, { owner: true });\n\t\tconst db = (resolved.database as { db: Kysely<Record<string, never>> }).db;\n\n\t\ttry {\n\t\t\t// better-auth 1.7 split the migration builder out of `better-auth/db`\n\t\t\t// into its own entry, so importing it no longer drags the whole db\n\t\t\t// layer in behind it.\n\t\t\tconst { getMigrations } = await import('better-auth/db/migration');\n\t\t\tconst { toBeCreated, toBeAdded, toBeAddedIndexes, compileMigrations } =\n\t\t\t\tawait getMigrations(resolved);\n\n\t\t\tif (\n\t\t\t\ttoBeCreated.length === 0 &&\n\t\t\t\ttoBeAdded.length === 0 &&\n\t\t\t\ttoBeAddedIndexes.length === 0\n\t\t\t) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\n\t\t\treturn idempotent(await compileMigrations());\n\t\t} finally {\n\t\t\t// Its own pool: left open, it keeps the process that asked alive.\n\t\t\tawait db.destroy();\n\t\t}\n\t}\n\n\t/**\n\t * The server this surface runs as, built from its own declaration.\n\t *\n\t * A surface is a deploy unit, so something has to serve it, and the thing\n\t * that knows how is the construct — not a generator writing a mount into\n\t * somebody else's entry point. That is how the auth server came to be\n\t * mounted by a hook in the application it was supposed to be separate from,\n\t * and then to be served by nothing at all when the hook was deleted.\n\t *\n\t * The routes come from {@link declare}: one wildcard under `basePath`, read\n\t * off the same declaration the manifest carries, so the surface the graph\n\t * describes and the surface that answers requests cannot disagree.\n\t *\n\t * ```ts\n\t * // .gkm/server/app.ts — the whole generated entry\n\t * import { auth } from '@acme/constructs/auth.js';\n\t * export const { app } = await auth.server({ envParser });\n\t * ```\n\t *\n\t * The only way to the server: it is what reads the signing secret, opens\n\t * the tenant and builds the mailer, so it is built here, in the auth app's\n\t * own process, and `.dependsOn([auth])` everywhere else gets\n\t * {@link AuthClient}. `auth` is the better-auth instance behind the app.\n\t */\n\tasync server(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<{ app: Hono; auth: AuthServer }> {\n\t\tconst { Hono } = await import('hono');\n\t\tconst { cors } = await import('hono/cors');\n\t\tconst app = new Hono();\n\t\tconst server = await this.connect(options);\n\n\t\t// Who may call this surface, read off the graph. The same list Better\n\t\t// Auth checks for CSRF — it arrives as `<ID>_TRUSTED_ORIGINS`, composed\n\t\t// by the target from whatever declared an edge to this construct, so a\n\t\t// site that depends on the auth server is allowed to reach it and\n\t\t// nothing else is. Nobody writes an origin down.\n\t\tconst { origins } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\torigins: get(this.keys.trustedOrigins)\n\t\t\t\t\t.string()\n\t\t\t\t\t.default('')\n\t\t\t\t\t.transform((value: string) =>\n\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t.split(',')\n\t\t\t\t\t\t\t.map((origin) => origin.trim())\n\t\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t\t),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\tapp.use('*', cors({ origin: origins, credentials: true, maxAge: 3600 }));\n\n\t\t// Read off the declaration rather than restated here. `ANY` is every\n\t\t// method Better Auth routes internally, which is the reason the\n\t\t// declaration wildcards rather than enumerating.\n\t\tconst [surface] = this.declare().filter(\n\t\t\t(d): d is Extract<Declaration, { kind: 'rest-api' }> =>\n\t\t\t\td.kind === 'rest-api',\n\t\t);\n\n\t\tfor (const endpoint of surface?.endpoints ?? []) {\n\t\t\tconst methods =\n\t\t\t\tendpoint.method === 'ANY'\n\t\t\t\t\t? (['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const)\n\t\t\t\t\t: ([endpoint.method] as const);\n\n\t\t\tapp.on([...methods], endpoint.path, (c) =>\n\t\t\t\tserver.handler(withTrustedClientIp(c.req.raw, remoteAddressOf(c))),\n\t\t\t);\n\t\t}\n\n\t\treturn { app, auth: server };\n\t}\n\n\t/**\n\t * The ids of the better-auth plugins this server runs — what a client has\n\t * to pair its own plugins with (`magic-link` with `magicLinkClient`).\n\t * Resolved the way the server resolves them, options callback included.\n\t */\n\tasync pluginIds(options: ServiceRegisterOptions): Promise<string[]> {\n\t\tconst { plugins = [] } = await this.configured(options);\n\t\treturn plugins.map(({ id }) => id);\n\t}\n\n\t/** Better-auth's options as given — a value, or a callback of the environment. */\n\tprivate async configured(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<BetterAuthOptions> {\n\t\t// Hoisted: narrowing a property of `this` is not preserved across the\n\t\t// await, and the false branch is the plain-object form.\n\t\tconst configure = this.config.options;\n\t\tif (typeof configure !== 'function') return configure ?? {};\n\n\t\t// A client for each declared construct, from the options this call was\n\t\t// given — not the process-wide discovery, which keeps whichever env\n\t\t// parser reached it first.\n\t\tconst services: Record<string, unknown> = {};\n\t\tfor (const construct of this.config.dependsOn ?? []) {\n\t\t\tservices[construct.service.serviceName] =\n\t\t\t\tawait construct.service.register(options);\n\t\t}\n\n\t\treturn configure({\n\t\t\t...options,\n\t\t\tservices,\n\t\t} as BetterAuthOptionsContext<TUses>);\n\t}\n\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<AuthServer> {\n\t\tconst { betterAuth } = await import('better-auth');\n\t\t// `Auth<O>` is invariant in its options in better-auth 1.7, so the value\n\t\t// built from a concrete literal is not assignable to the `AuthServer`\n\t\t// alias, which names the constraint. The runtime object is the same one\n\t\t// either way; the assertion keeps the variance where it happens instead\n\t\t// of spreading a generic through the construct's public type.\n\t\treturn betterAuth(await this.optionsFor(options, as)) as AuthServer;\n\t}\n\n\t/**\n\t * Everything better-auth is given: the app's options, and what the construct\n\t * owns — its secret, its URL, its tenant's connection, the origins and cookie\n\t * domain its graph derives. One place, so the server and its migrations are\n\t * built from the same options.\n\t */\n\tprivate async optionsFor(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<Parameters<typeof betterAuth>[0]> {\n\t\tconst { secret, baseUrl, trustedOrigins, cookieDomain, deviceUrl } =\n\t\t\toptions.envParser\n\t\t\t\t.create((get) => ({\n\t\t\t\t\tsecret: get(this.keys.secret).string(),\n\t\t\t\t\t// The surface's own URL, resolved by the target — not guessed from\n\t\t\t\t\t// a port, which was wrong the moment the server moved to 3001.\n\t\t\t\t\tbaseUrl: get(this.keys.url).string(),\n\t\t\t\t\t// Better Auth's CSRF check applies to every caller, not just\n\t\t\t\t\t// browsers, so an API calling the auth server is rejected unless\n\t\t\t\t\t// its origin is trusted. The list is derived from the graph and\n\t\t\t\t\t// arrives as one comma-separated value, for the same reason every\n\t\t\t\t\t// other derived value arrives as a string: it crosses a process\n\t\t\t\t\t// boundary as env.\n\t\t\t\t\ttrustedOrigins: get(this.keys.trustedOrigins)\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.default('')\n\t\t\t\t\t\t.transform((value) =>\n\t\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t\t.split(',')\n\t\t\t\t\t\t\t\t.map((origin) => origin.trim())\n\t\t\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t\t\t),\n\t\t\t\t\t// The domain a session cookie has to carry to be readable by a\n\t\t\t\t\t// frontend on a sibling host. Optional because there is often\n\t\t\t\t\t// nothing to widen to: locally everything shares `localhost`,\n\t\t\t\t\t// where cookies ignore the port and a `Domain` would only be a\n\t\t\t\t\t// value the browser refuses.\n\t\t\t\t\tcookieDomain: get(this.keys.cookieDomain).string().optional(),\n\t\t\t\t\t// Where a phone reaches this server, on a local stage with a mobile\n\t\t\t\t\t// app: its own port on the LAN address. Never deployed.\n\t\t\t\t\tdeviceUrl: get(provideKey(this.id, 'deviceUrl')).string().optional(),\n\t\t\t\t}))\n\t\t\t\t.parse();\n\n\t\t// The tenant's own client: one construct, one connection, so what auth\n\t\t// writes and what the browser inspects cannot be two different databases.\n\t\t// A migration asks the tenant for its owner connection, which the tenant\n\t\t// exposes as a `Service` and not as anything `.dependsOn()` would take.\n\t\tconst tenant = this.config.database as Consumable & {\n\t\t\towner?: Service<string, unknown>;\n\t\t};\n\t\tconst source = as.owner && tenant.owner ? tenant.owner : tenant.service;\n\n\t\tconst db = (await source.register(options)) as Kysely<\n\t\t\tRecord<string, never>\n\t\t>;\n\n\t\tconst configured = await this.configured(options);\n\n\t\t// Whatever the app added wins over the derived list rather than\n\t\t// replacing it: an origin nobody declared is still sometimes real.\n\t\tconst origins = [\n\t\t\t...trustedOrigins,\n\t\t\t...(configured.trustedOrigins && Array.isArray(configured.trustedOrigins)\n\t\t\t\t? configured.trustedOrigins\n\t\t\t\t: []),\n\t\t];\n\n\t\tconst plugins = [...(configured.plugins ?? [])];\n\t\t// A mobile app depends on this server: the graph put its scheme among\n\t\t// the derived origins. It signs in through Better Auth's Expo plugin —\n\t\t// the app sends its scheme as the origin, and the plugin is what reads\n\t\t// it — so a server without it would refuse every request the app made.\n\t\t// Asked of the app rather than imported here: a package this one\n\t\t// imported would have to be its peer, and an optional peer gives every\n\t\t// differently-resolving workspace package its own copy of this one.\n\t\tconst mobile = trustedOrigins.filter((origin) => !isWebOrigin(origin));\n\t\tif (mobile.length > 0 && !plugins.some((plugin) => plugin.id === 'expo')) {\n\t\t\tthrow new ExpoPluginRequired(this.id, mobile);\n\t\t}\n\t\t// A sign-in link the app asked for is opened on the phone, which cannot\n\t\t// resolve this server's local hostname; on a local stage it is built on\n\t\t// the address the phone reaches it on instead.\n\t\tif (deviceUrl) {\n\t\t\tfor (const plugin of plugins) reachableFromDevice(plugin, deviceUrl);\n\t\t}\n\n\t\treturn {\n\t\t\t...configured,\n\t\t\tsecret,\n\t\t\tbaseURL: baseUrl,\n\t\t\tbasePath: this.basePath,\n\t\t\tdatabase: { db, type: 'postgres' },\n\t\t\tplugins,\n\t\t\ttrustedOrigins: origins,\n\t\t\tadvanced: {\n\t\t\t\t...configured.advanced,\n\t\t\t\t// The client's address on a call from one of this stack's own\n\t\t\t\t// services comes in gkm's header, ahead of whatever the app reads\n\t\t\t\t// otherwise — `X-Forwarded-For` by default, as Better Auth reads a\n\t\t\t\t// request that reached it through a proxy. The header is honoured\n\t\t\t\t// only from an internal caller: see `withTrustedClientIp`.\n\t\t\t\tipAddress: {\n\t\t\t\t\t...configured.advanced?.ipAddress,\n\t\t\t\t\tipAddressHeaders: [\n\t\t\t\t\t\tCLIENT_IP_HEADER,\n\t\t\t\t\t\t...(\n\t\t\t\t\t\t\tconfigured.advanced?.ipAddress?.ipAddressHeaders ?? [\n\t\t\t\t\t\t\t\t'x-forwarded-for',\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t).filter((name) => name.toLowerCase() !== CLIENT_IP_HEADER),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t// Only when a domain was derived. Better Auth reads the presence\n\t\t\t\t// of this block as intent, so enabling it with no domain would\n\t\t\t\t// widen the cookie to whatever host happened to set it — and the\n\t\t\t\t// case with nothing to widen to is the common one, not an error.\n\t\t\t\t...(cookieDomain\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcrossSubDomainCookies: {\n\t\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\t\tdomain: cookieDomain,\n\t\t\t\t\t\t\t\t...configured.advanced?.crossSubDomainCookies,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** Links already rewritten — an `options` object is reused across builds. */\nconst rewritten = new WeakSet<object>();\n\n/**\n * Build the magic links an app asked for on the address a phone reaches.\n *\n * An app's link carries its scheme as the `callbackURL` (`shop://…`)\n * where a browser's carries a path or an `http(s)` URL — which is how the two\n * are told apart. A browser's link is left alone: it is opened on this\n * machine, where the server's own hostname resolves.\n *\n * Better Auth's magic-link plugin calls `sendMagicLink` through the options\n * object it returns, so wrapping it there is wrapping the call.\n */\nfunction reachableFromDevice(plugin: { id: string }, deviceUrl: string): void {\n\tif (plugin.id !== 'magic-link') return;\n\tconst options = (plugin as { options?: MagicLinkOptions }).options;\n\tif (!options?.sendMagicLink || rewritten.has(options)) return;\n\trewritten.add(options);\n\n\tconst send = options.sendMagicLink;\n\toptions.sendMagicLink = (data, ...rest) =>\n\t\tsend({ ...data, url: deviceLink(data.url, deviceUrl) }, ...rest);\n}\n\ninterface MagicLinkOptions {\n\tsendMagicLink?: (\n\t\tdata: { email: string; url: string; token: string },\n\t\t...rest: unknown[]\n\t) => unknown;\n}\n\n/** A magic link moved to the device address when an app is its destination. */\nexport function deviceLink(url: string, deviceUrl: string): string {\n\ttry {\n\t\tconst link = new URL(url);\n\t\tconst callback = link.searchParams.get('callbackURL') ?? '/';\n\t\tif (callback.startsWith('/') || isWebOrigin(callback)) return url;\n\t\treturn new URL(`${link.pathname}${link.search}`, deviceUrl).toString();\n\t} catch {\n\t\treturn url;\n\t}\n}\n\n/** A mobile app depends on this auth server, which has no Expo plugin. */\nexport class ExpoPluginRequired extends Error {\n\tconstructor(\n\t\treadonly server: string,\n\t\t/** The schemes the graph says call it — what made the plugin necessary. */\n\t\treadonly origins: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${server}' is called by a mobile app (${origins[0]}), and a mobile app ` +\n\t\t\t\t`signs in through Better Auth's Expo plugin: add expo() from ` +\n\t\t\t\t`'@better-auth/expo' to this auth server's plugins.`,\n\t\t);\n\t\tthis.name = 'ExpoPluginRequired';\n\t}\n}\n\n/** What is forwarded to the auth server: the headers a session travels in. */\nconst SESSION_HEADERS = ['cookie', 'authorization'] as const;\n\n/**\n * `GET <basePath>/get-session`, read the way Better Auth answers it.\n *\n * Whose request it is travels in {@link CLIENT_IP_HEADER} — the server\n * rate-limits `/get-session` by the client's address, so without it every\n * caller shares the API's one bucket — and never as `X-Forwarded-For`. A\n * forwarding header is what marks a request as outside traffic, so the auth\n * server would start its span in a trace of its own rather than continue the\n * API's. Without one, this is an internal caller's request, and the trace\n * context it carries is continued.\n */\nasync function fetchSession(\n\tauthenticator: string,\n\tendpoint: string,\n\tgiven: Headers,\n): Promise<AuthSession | null> {\n\tconst headers = new Headers();\n\tfor (const name of SESSION_HEADERS) {\n\t\tconst value = given.get(name);\n\t\tif (value) headers.set(name, value);\n\t}\n\t// The chain as the API received it, so the auth server reads it exactly\n\t// as it would have read `X-Forwarded-For` (its `trustedProxies` included).\n\t// Never a `CLIENT_IP_HEADER` the API was sent: this process cannot tell\n\t// here whether its own caller was internal, and the auth server trusts\n\t// whatever an internal caller — this one — says.\n\tconst client = given.get('x-forwarded-for');\n\tif (client) headers.set(CLIENT_IP_HEADER, client);\n\tinjectTraceContext(headers);\n\n\tconst url = `${endpoint}/get-session`;\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, { headers });\n\t} catch (cause) {\n\t\tthrow new AuthServerUnreachable(authenticator, url, cause);\n\t}\n\n\t// Better Auth answers `null` for a request with no session, and a 401 is\n\t// the same answer from anything in front of it. Anything else that is not\n\t// a 200 is the server failing, which is not \"signed out\" and must not be\n\t// read as it.\n\tif (response.status === 401) return null;\n\tif (!response.ok) {\n\t\tthrow new SessionCheckFailed(authenticator, response.status);\n\t}\n\n\treturn (await response.json()) as AuthSession | null;\n}\n\n/** The auth server answered a session check with a failure. */\nexport class SessionCheckFailed extends Error {\n\tconstructor(\n\t\treadonly authenticator: string,\n\t\treadonly status: number,\n\t) {\n\t\tsuper(\n\t\t\t`'${authenticator}' answered a session check with ${status}. ` +\n\t\t\t\t`A request with no session gets 200 and null, or 401; this is the ` +\n\t\t\t\t`server failing — check its logs, and that it is running at its URL.`,\n\t\t);\n\t\tthis.name = 'SessionCheckFailed';\n\t}\n}\n\n/** A session check never reached the auth server. */\nexport class AuthServerUnreachable extends Error {\n\tconstructor(\n\t\treadonly authenticator: string,\n\t\treadonly url: string,\n\t\tcause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`'${authenticator}' could not be reached at ${url} to check a session. ` +\n\t\t\t\t`Check that the auth app is running and that this app's ` +\n\t\t\t\t`${provideKey(authenticator, 'url')} points at it.`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'AuthServerUnreachable';\n\t}\n}\n\n/**\n * Better Auth's DDL, safe to run where its tables already exist.\n *\n * Its SQL is Kysely's, so its shape is known: `create table \"…\"`, `create index\n * \"…\"`, `alter table \"…\" add column \"…\"`. A database that has been running\n * already has those — Better Auth used to create them at runtime — and the\n * first committed migration would fail on them rather than recording that they\n * are there.\n */\nexport function idempotent(statements: string): string {\n\treturn statements\n\t\t.replace(/\\bcreate table \"/gi, 'create table if not exists \"')\n\t\t.replace(\n\t\t\t/\\bcreate (unique )?index \"/gi,\n\t\t\t(_, unique = '') => `create ${unique}index if not exists \"`,\n\t\t)\n\t\t.replace(/\\badd column \"/gi, 'add column if not exists \"');\n}\n\n/** Headers a reverse proxy or CDN adds on the way in. */\nconst FORWARDING_HEADERS = [\n\t'forwarded',\n\t'x-forwarded-for',\n\t'x-forwarded-host',\n\t'x-real-ip',\n\t'cf-connecting-ip',\n\t'true-client-ip',\n\t'fastly-client-ip',\n\t'x-client-ip',\n];\n\n/**\n * `request`, without {@link CLIENT_IP_HEADER} unless an internal caller sent\n * it — no `Origin`, no forwarding header, a loopback or private peer: the\n * rule a request's span continues a trace by (`@geekmidas/telescope`'s\n * `isInternalCaller`).\n *\n * The stack's own edges strip the header already. This holds wherever one\n * does not — a platform's proxy, a port published straight to the internet —\n * so a stranger cannot pick the address Better Auth rate-limits them by.\n */\nexport function withTrustedClientIp(\n\trequest: Request,\n\tremoteAddress: string | undefined,\n): Request {\n\tif (!request.headers.has(CLIENT_IP_HEADER)) return request;\n\tconst internal =\n\t\t!request.headers.has('origin') &&\n\t\t!FORWARDING_HEADERS.some((name) => request.headers.has(name)) &&\n\t\tisPrivateAddress(remoteAddress);\n\tif (internal) return request;\n\n\tconst headers = new Headers(request.headers);\n\theaders.delete(CLIENT_IP_HEADER);\n\treturn new Request(request, { headers });\n}\n\n/** The TCP peer of a request served by `@hono/node-server`, when there is one. */\nfunction remoteAddressOf(c: { env: unknown }): string | undefined {\n\tconst env = c.env as\n\t\t| { incoming?: { socket?: { remoteAddress?: string } } }\n\t\t| undefined;\n\treturn env?.incoming?.socket?.remoteAddress;\n}\n\n/**\n * Whether `address` is loopback or private: 127/8, 10/8, 172.16/12,\n * 192.168/16, 169.254/16, `::1`, `fc00::/7`, `fe80::/10`, and an IPv4 one\n * mapped into IPv6.\n */\nfunction isPrivateAddress(address: string | undefined): boolean {\n\tif (!address) return false;\n\tconst ip = address.toLowerCase().replace(/^::ffff:/, '');\n\n\tconst v4 = ip.match(/^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/);\n\tif (v4) {\n\t\tconst [a, b] = [Number(v4[1]), Number(v4[2])];\n\t\treturn (\n\t\t\ta === 127 ||\n\t\t\ta === 10 ||\n\t\t\t(a === 172 && b >= 16 && b <= 31) ||\n\t\t\t(a === 192 && b === 168) ||\n\t\t\t(a === 169 && b === 254)\n\t\t);\n\t}\n\n\tif (ip === '::1') return true;\n\treturn /^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,OAAO,sBACtC,CAAC,CACA,QAAQ,oBAAoB,6BAA4B;AAC3D;;AAGA,MAAM,qBAAqB;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;;;;;;AAYA,SAAgB,oBACf,SACA,eACU;CACV,IAAI,CAAC,QAAQ,QAAQ,IAAI,gBAAgB,GAAG,OAAO;CAKnD,IAHC,CAAC,QAAQ,QAAQ,IAAI,QAAQ,KAC7B,CAAC,mBAAmB,MAAM,SAAS,QAAQ,QAAQ,IAAI,IAAI,CAAC,KAC5D,iBAAiB,aAAa,GACjB,OAAO;CAErB,MAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;CAC3C,QAAQ,OAAO,gBAAgB;CAC/B,OAAO,IAAI,QAAQ,SAAS,EAAE,QAAQ,CAAC;AACxC;;AAGA,SAAS,gBAAgB,GAAyC;CAIjE,OAHY,EAAE,KAGF,UAAU,QAAQ;AAC/B;;;;;;AAOA,SAAS,iBAAiB,SAAsC;CAC/D,IAAI,CAAC,SAAS,OAAO;CACrB,MAAM,KAAK,QAAQ,YAAY,CAAC,CAAC,QAAQ,YAAY,EAAE;CAEvD,MAAM,KAAK,GAAG,MAAM,8CAA8C;CAClE,IAAI,IAAI;EACP,MAAM,CAAC,GAAG,KAAK,CAAC,OAAO,GAAG,EAAE,GAAG,OAAO,GAAG,EAAE,CAAC;EAC5C,OACC,MAAM,OACN,MAAM,MACL,MAAM,OAAO,KAAK,MAAM,KAAK,MAC7B,MAAM,OAAO,MAAM,OACnB,MAAM,OAAO,MAAM;CAEtB;CAEA,IAAI,OAAO,OAAO,OAAO;CACzB,OAAO,qBAAqB,KAAK,EAAE,KAAK,qBAAqB,KAAK,EAAE;AACrE"}
|
|
1
|
+
{"version":3,"file":"auth.mjs","names":[],"sources":["../src/auth.ts"],"sourcesContent":["/**\n * `BetterAuth` — a declared auth server.\n *\n * It is three things at once, which is what makes it the construct that\n * exercises most of the model: a consumer of a database, a producer of an\n * authorizer, and a set of endpoints. This lands the first two.\n *\n * Its tables live in a schema tenant it is *given* — `orders.schema('AuthDb')`\n * — rather than one it invents. The tenant declares the schema and the role;\n * this declares the one thing left, the signing secret, and reads back the keys\n * it needs.\n *\n * :::caution\n * The isolation that arrangement is *for* — the application's own role holding\n * no grant on these tables, so a compromised handler cannot read sessions — does\n * **not hold yet**. No target creates the per-schema role: both connect as the\n * database owner, so today the tenant is a `search_path`, which is a namespace\n * and not a privilege boundary. See \"Roles are declared and never created\" in\n * `docs/design/constructs-outstanding.md`.\n * :::\n *\n * It declares its own surface, so where it answers, who may call it, and the\n * domain its cookies are scoped to all arrive as environment resolved by the\n * target — none of them guessed from a port, and none of them listed by hand in\n * application config.\n */\n\nimport { timingSafeEqual } from 'node:crypto';\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport {\n\tCLIENT_IP_HEADER,\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tEDGE_TOKEN_HEADER,\n\tEDGE_TOKEN_KEY,\n\tenvironmentCase,\n\tisWebOrigin,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type {\n\tService,\n\tServiceRecord,\n\tServiceRegisterOptions,\n} from '@geekmidas/services';\n// Types only: the server is built in `connect()`, from a dynamic import, so a\n// process that only holds the client never loads better-auth to get it.\nimport type { betterAuth } from 'better-auth';\nimport type { Hono } from 'hono';\nimport type { Kysely } from 'kysely';\nimport {\n\ttype Authenticator,\n\ttype Construct,\n\ttype Consumable,\n\tedgeTo,\n\ttype ServicesOf,\n} from './construct-interface';\nimport type { Telemetry } from './telemetry';\nimport { injectTraceContext } from './tracing';\n\n/** The server better-auth hands back. */\nexport type AuthServer = ReturnType<typeof betterAuth>;\n\n/** A signed-in session as better-auth hands it back: `{ user, session }`. */\nexport type AuthSession = AuthServer['$Infer']['Session'];\n\n/**\n * What `.dependsOn([auth])` hands a handler: the auth server, over HTTP.\n *\n * The server itself — its secret, its tenant's connection, its mailer — lives\n * in the auth app's own process and nowhere else. Every other process is a\n * caller of it, so what it is given is an address and this, with the one\n * call handlers make kept in Better Auth's shape: `api.getSession({ headers })`\n * answers `{ user, session }` or `null`, as the server's own `api` does.\n */\nexport interface AuthClient {\n\treadonly api: {\n\t\t/**\n\t\t * The session the request's cookie or bearer token belongs to, or `null`\n\t\t * when there is none — asked of `<basePath>/get-session` at the auth\n\t\t * server's URL. Only `cookie` and `authorization` are forwarded, with\n\t\t * the client's address as `x-gkm-client-ip` (read from the request's\n\t\t * `x-forwarded-for`) and the active trace context.\n\t\t *\n\t\t * @throws {AuthServerUnreachable} when the request does not get there.\n\t\t * @throws {SessionCheckFailed} when the server answers with a failure.\n\t\t */\n\t\tgetSession(input: {\n\t\t\theaders: ConstructorParameters<typeof Headers>[0];\n\t\t}): Promise<AuthSession | null>;\n\t};\n}\n\n/** Everything better-auth takes, minus what the construct owns. */\nexport type BetterAuthOptions = Omit<\n\tParameters<typeof betterAuth>[0],\n\t'database' | 'secret' | 'basePath' | 'baseURL'\n>;\n\n/**\n * What an `options` callback is handed: the options this construct was\n * registered with, and a client for each construct its `dependsOn` names —\n * keyed by service name, exactly as an endpoint's handler receives them.\n */\nexport type BetterAuthOptionsContext<TUses extends readonly Consumable[]> =\n\tServiceRegisterOptions & {\n\t\tservices: ServiceRecord<[...ServicesOf<TUses>]>;\n\t};\n\nexport interface BetterAuthConfig<\n\tTDatabase extends Consumable,\n\tTUses extends readonly Consumable[] = readonly [],\n> {\n\t/**\n\t * The schema tenant its tables live in.\n\t *\n\t * A construct rather than a URL: the tenant already declares its schema and\n\t * its role, and taking the declaration is what puts the edge in the graph\n\t * instead of a connection string in two places.\n\t */\n\tdatabase: TDatabase;\n\t/**\n\t * The app that serves this auth server, relative to the workspace root —\n\t * `'apps/auth'`.\n\t *\n\t * Required, for the reason `RestApi.path` is. Not to be confused with\n\t * `basePath`, which is where its routes are mounted in a URL.\n\t */\n\tpath: string;\n\t/**\n\t * The label it answers on under a stage's domain — `api` for\n\t * `api.myapp.com`, from `domains` — and under the project locally,\n\t * `api.myapp.localhost`. Absent, its id kebab-cased.\n\t */\n\tsubdomain?: string;\n\t/**\n\t * Where the auth routes are mounted, e.g. `/api/auth`.\n\t *\n\t * Structural — it is part of the URL every client calls, so it cannot differ\n\t * between stages the way the host can.\n\t */\n\tbasePath?: string;\n\t/**\n\t * The constructs `options` uses — the mailer a magic link goes through,\n\t * most often.\n\t *\n\t * One list, two jobs, the way an endpoint's `.dependsOn()` has: each is an\n\t * edge on the server's handler, so whatever is composed from the edges (a\n\t * container's environment, a deploy's grants) includes it; and each is\n\t * handed to `options` as a client in `services`, so there is no other way\n\t * for `options` to reach it — nothing to import and register by hand, and\n\t * so nothing that can be used without being declared.\n\t */\n\tdependsOn?: TUses;\n\t/**\n\t * What the auth server's process emits — the `Telemetry` construct, passed\n\t * like a `RestApi`'s. An edge to the node: the deploy hands the process the\n\t * `OTEL_*` keys its stage resolves.\n\t */\n\ttelemetry?: Telemetry;\n\t/**\n\t * The rest of better-auth's options: providers, plugins, email settings.\n\t *\n\t * A function when they need another construct — a magic-link plugin has to\n\t * *send* the link. It is handed the options this construct was registered\n\t * with, and `services`: a client for each construct in `dependsOn`.\n\t */\n\toptions?:\n\t\t| BetterAuthOptions\n\t\t| ((\n\t\t\t\tcontext: BetterAuthOptionsContext<TUses>,\n\t\t ) => BetterAuthOptions | Promise<BetterAuthOptions>);\n}\n\nconst DEFAULT_BASE_PATH = '/api/auth';\n\nexport class BetterAuth<\n\tTName extends string = string,\n\tTDatabase extends Consumable = Consumable,\n\tconst TUses extends readonly Consumable[] = readonly [],\n> implements Construct<TName, AuthClient>, Authenticator<AuthSession>\n{\n\treadonly id: TName;\n\t/**\n\t * What `.dependsOn([auth])` injects: an {@link AuthClient}, never the server.\n\t *\n\t * Which of the two a process holds is decided by how it reaches the\n\t * construct, not by asking where it is running. The auth app's process is\n\t * its generated entry, which calls {@link server} and nothing else — a\n\t * self-serving surface has no endpoints of its own for a `dependsOn` to sit\n\t * on. Every other process reaches it through this. So the API, a worker, a\n\t * test's in-process endpoints all get the client, and none of them needs\n\t * the signing secret, the auth tenant's URL or the mailer to start.\n\t */\n\treadonly service: Service<Uncapitalize<TName>, AuthClient>;\n\treadonly basePath: string;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the keys the\n\t * target publishes and the keys the server reads cannot drift.\n\t */\n\tprivate readonly keys: {\n\t\tsecretId: string;\n\t\tsecret: string;\n\t\turl: string;\n\t\ttrustedOrigins: string;\n\t\tcookieDomain: string;\n\t};\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: BetterAuthConfig<TDatabase, TUses>,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.basePath = config.basePath ?? DEFAULT_BASE_PATH;\n\n\t\t// A secret's name is its key: `Auth` signs with `AUTH_SECRET`, which is\n\t\t// also what better-auth's own tooling looks for.\n\t\tconst secretId = `${canonical}Secret`;\n\t\tthis.keys = {\n\t\t\tsecretId,\n\t\t\tsecret: environmentCase(secretId),\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\ttrustedOrigins: provideKey(canonical, 'trustedOrigins'),\n\t\t\tcookieDomain: provideKey(canonical, 'cookieDomain'),\n\t\t};\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (options) => this.client(options.envParser),\n\t\t};\n\t}\n\n\t/**\n\t * A signing secret and a surface.\n\t *\n\t * The database is *not* declared here — the tenant that was passed in\n\t * declares it, and declaring it twice is the duplication the whole model\n\t * removes. What is declared is what this construct owns: the key it signs\n\t * with, and the routes it answers on.\n\t *\n\t * One endpoint, wildcarded. Better Auth routes internally and the set of\n\t * paths depends on which capabilities are enabled, so enumerating them here\n\t * would be a copy of its router that goes stale on its next release. The\n\t * surface's job is to send everything under `basePath` to one handler, which\n\t * is exactly what the declaration says.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'secret',\n\t\t\t\tid: this.keys.secretId,\n\t\t\t\tprovides: [this.keys.secret],\n\t\t\t},\n\t\t\t{\n\t\t\t\tkind: 'rest-api',\n\t\t\t\tid: this.id,\n\t\t\t\tpath: this.config.path,\n\t\t\t\t...(this.config.subdomain ? { subdomain: this.config.subdomain } : {}),\n\t\t\t\t...(this.config.telemetry\n\t\t\t\t\t? { telemetry: this.config.telemetry.id }\n\t\t\t\t\t: {}),\n\t\t\t\tprovides: [\n\t\t\t\t\tthis.keys.url,\n\t\t\t\t\tthis.keys.trustedOrigins,\n\t\t\t\t\tthis.keys.cookieDomain,\n\t\t\t\t],\n\t\t\t\tservesItself: true,\n\t\t\t\tendpoints: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: `${this.id}Handler`,\n\t\t\t\t\t\thandler: `${this.id}.handler`,\n\t\t\t\t\t\tmethod: 'ANY',\n\t\t\t\t\t\tpath: `${this.basePath}/*`,\n\t\t\t\t\t\t// Read off the tenant rather than written down: this\n\t\t\t\t\t\t// construct takes whatever database it is given, and a\n\t\t\t\t\t\t// hardcoded kind is a second statement of a fact the\n\t\t\t\t\t\t// tenant already makes.\n\t\t\t\t\t\tdependencies: [\n\t\t\t\t\t\t\tedgeTo(this.config.database),\n\t\t\t\t\t\t\t...(this.config.dependsOn ?? []).map(edgeTo),\n\t\t\t\t\t\t],\n\t\t\t\t\t\trequires: [this.keys.secret],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * Whose request this is: the session for these headers, or `null`.\n\t *\n\t * Asked of the auth server over HTTP, at the URL the `.auth()` edge injects —\n\t * so it is the same call whether the server runs in this process, beside\n\t * it, or behind MSW in a test. The same call {@link AuthClient} makes.\n\t */\n\tasync verify(\n\t\theaders: Headers,\n\t\tenvParser: EnvironmentParser<{}>,\n\t): Promise<AuthSession | null> {\n\t\treturn this.client(envParser).api.getSession({ headers });\n\t}\n\n\t/**\n\t * The client a caller of this server holds: its URL and nothing else.\n\t *\n\t * `<ID>_URL` is the one key a consumer is given for an edge to a surface —\n\t * the compose network's address between containers, the public one where\n\t * that is all there is — so this is everything it can know.\n\t */\n\tclient(envParser: EnvironmentParser<{}>): AuthClient {\n\t\tconst { url, edgeToken } = envParser\n\t\t\t.create((get) => ({\n\t\t\t\turl: get(this.keys.url).string(),\n\t\t\t\tedgeToken: get(EDGE_TOKEN_KEY).string().optional(),\n\t\t\t}))\n\t\t\t.parse();\n\t\tconst endpoint = `${url.replace(/\\/$/, '')}${this.basePath}`;\n\n\t\treturn {\n\t\t\tapi: {\n\t\t\t\tgetSession: ({ headers }) =>\n\t\t\t\t\tfetchSession(this.id, endpoint, new Headers(headers), edgeToken),\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * The tenant this server keeps its tables in — whose migrations folder,\n\t * `db/<tenant>/`, Better Auth's schema is written into.\n\t */\n\tget databaseId(): string {\n\t\treturn this.config.database.id;\n\t}\n\n\t/**\n\t * The SQL that brings the tenant up to Better Auth's schema, or `undefined`\n\t * when it already matches.\n\t *\n\t * What `gkm migration` writes as the tenant's next migration, so Better\n\t * Auth's tables are committed, reviewed and applied like any other — rather\n\t * than diffed against the database at runtime, where a change nobody wrote\n\t * down happens on whichever machine migrates first.\n\t *\n\t * Compared as the owner, against the tenant `gkm migrate` has already brought\n\t * up to date: what comes back is only what the committed files are missing.\n\t */\n\tasync pendingMigration(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<string | undefined> {\n\t\t// The options, not a server built from them: better-auth checks its\n\t\t// schema when a server starts, and before the migration that creates the\n\t\t// tables it can only report them missing.\n\t\tconst resolved = await this.optionsFor(options, { owner: true });\n\t\tconst db = (resolved.database as { db: Kysely<Record<string, never>> }).db;\n\n\t\ttry {\n\t\t\t// better-auth 1.7 split the migration builder out of `better-auth/db`\n\t\t\t// into its own entry, so importing it no longer drags the whole db\n\t\t\t// layer in behind it.\n\t\t\tconst { getMigrations } = await import('better-auth/db/migration');\n\t\t\tconst { toBeCreated, toBeAdded, toBeAddedIndexes, compileMigrations } =\n\t\t\t\tawait getMigrations(resolved);\n\n\t\t\tif (\n\t\t\t\ttoBeCreated.length === 0 &&\n\t\t\t\ttoBeAdded.length === 0 &&\n\t\t\t\ttoBeAddedIndexes.length === 0\n\t\t\t) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\n\t\t\treturn idempotent(await compileMigrations());\n\t\t} finally {\n\t\t\t// Its own pool: left open, it keeps the process that asked alive.\n\t\t\tawait db.destroy();\n\t\t}\n\t}\n\n\t/**\n\t * The server this surface runs as, built from its own declaration.\n\t *\n\t * A surface is a deploy unit, so something has to serve it, and the thing\n\t * that knows how is the construct — not a generator writing a mount into\n\t * somebody else's entry point. That is how the auth server came to be\n\t * mounted by a hook in the application it was supposed to be separate from,\n\t * and then to be served by nothing at all when the hook was deleted.\n\t *\n\t * The routes come from {@link declare}: one wildcard under `basePath`, read\n\t * off the same declaration the manifest carries, so the surface the graph\n\t * describes and the surface that answers requests cannot disagree.\n\t *\n\t * ```ts\n\t * // .gkm/server/app.ts — the whole generated entry\n\t * import { auth } from '@acme/constructs/auth.js';\n\t * export const { app } = await auth.server({ envParser });\n\t * ```\n\t *\n\t * The only way to the server: it is what reads the signing secret, opens\n\t * the tenant and builds the mailer, so it is built here, in the auth app's\n\t * own process, and `.dependsOn([auth])` everywhere else gets\n\t * {@link AuthClient}. `auth` is the better-auth instance behind the app.\n\t */\n\tasync server(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<{ app: Hono; auth: AuthServer }> {\n\t\tconst { Hono } = await import('hono');\n\t\tconst { cors } = await import('hono/cors');\n\t\tconst app = new Hono();\n\t\tconst server = await this.connect(options);\n\n\t\t// Who may call this surface, read off the graph. The same list Better\n\t\t// Auth checks for CSRF — it arrives as `<ID>_TRUSTED_ORIGINS`, composed\n\t\t// by the target from whatever declared an edge to this construct, so a\n\t\t// site that depends on the auth server is allowed to reach it and\n\t\t// nothing else is. Nobody writes an origin down.\n\t\tconst { origins, edgeToken } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\t// The stack's token, which its own services send when they call\n\t\t\t\t// this server through the edge — see `withTrustedClientIp`.\n\t\t\t\tedgeToken: get(EDGE_TOKEN_KEY).string().optional(),\n\t\t\t\torigins: get(this.keys.trustedOrigins)\n\t\t\t\t\t.string()\n\t\t\t\t\t.default('')\n\t\t\t\t\t.transform((value: string) =>\n\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t.split(',')\n\t\t\t\t\t\t\t.map((origin) => origin.trim())\n\t\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t\t),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\tapp.use('*', cors({ origin: origins, credentials: true, maxAge: 3600 }));\n\n\t\t// Read off the declaration rather than restated here. `ANY` is every\n\t\t// method Better Auth routes internally, which is the reason the\n\t\t// declaration wildcards rather than enumerating.\n\t\tconst [surface] = this.declare().filter(\n\t\t\t(d): d is Extract<Declaration, { kind: 'rest-api' }> =>\n\t\t\t\td.kind === 'rest-api',\n\t\t);\n\n\t\tfor (const endpoint of surface?.endpoints ?? []) {\n\t\t\tconst methods =\n\t\t\t\tendpoint.method === 'ANY'\n\t\t\t\t\t? (['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const)\n\t\t\t\t\t: ([endpoint.method] as const);\n\n\t\t\tapp.on([...methods], endpoint.path, (c) =>\n\t\t\t\tserver.handler(\n\t\t\t\t\twithTrustedClientIp(c.req.raw, remoteAddressOf(c), edgeToken),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\treturn { app, auth: server };\n\t}\n\n\t/**\n\t * The ids of the better-auth plugins this server runs — what a client has\n\t * to pair its own plugins with (`magic-link` with `magicLinkClient`).\n\t * Resolved the way the server resolves them, options callback included.\n\t */\n\tasync pluginIds(options: ServiceRegisterOptions): Promise<string[]> {\n\t\tconst { plugins = [] } = await this.configured(options);\n\t\treturn plugins.map(({ id }) => id);\n\t}\n\n\t/** Better-auth's options as given — a value, or a callback of the environment. */\n\tprivate async configured(\n\t\toptions: ServiceRegisterOptions,\n\t): Promise<BetterAuthOptions> {\n\t\t// Hoisted: narrowing a property of `this` is not preserved across the\n\t\t// await, and the false branch is the plain-object form.\n\t\tconst configure = this.config.options;\n\t\tif (typeof configure !== 'function') return configure ?? {};\n\n\t\t// A client for each declared construct, from the options this call was\n\t\t// given — not the process-wide discovery, which keeps whichever env\n\t\t// parser reached it first.\n\t\tconst services: Record<string, unknown> = {};\n\t\tfor (const construct of this.config.dependsOn ?? []) {\n\t\t\tservices[construct.service.serviceName] =\n\t\t\t\tawait construct.service.register(options);\n\t\t}\n\n\t\treturn configure({\n\t\t\t...options,\n\t\t\tservices,\n\t\t} as BetterAuthOptionsContext<TUses>);\n\t}\n\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<AuthServer> {\n\t\tconst { betterAuth } = await import('better-auth');\n\t\t// `Auth<O>` is invariant in its options in better-auth 1.7, so the value\n\t\t// built from a concrete literal is not assignable to the `AuthServer`\n\t\t// alias, which names the constraint. The runtime object is the same one\n\t\t// either way; the assertion keeps the variance where it happens instead\n\t\t// of spreading a generic through the construct's public type.\n\t\treturn betterAuth(await this.optionsFor(options, as)) as AuthServer;\n\t}\n\n\t/**\n\t * Everything better-auth is given: the app's options, and what the construct\n\t * owns — its secret, its URL, its tenant's connection, the origins and cookie\n\t * domain its graph derives. One place, so the server and its migrations are\n\t * built from the same options.\n\t */\n\tprivate async optionsFor(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<Parameters<typeof betterAuth>[0]> {\n\t\tconst { secret, baseUrl, trustedOrigins, cookieDomain, deviceUrl } =\n\t\t\toptions.envParser\n\t\t\t\t.create((get) => ({\n\t\t\t\t\tsecret: get(this.keys.secret).string(),\n\t\t\t\t\t// The surface's own URL, resolved by the target — not guessed from\n\t\t\t\t\t// a port, which was wrong the moment the server moved to 3001.\n\t\t\t\t\tbaseUrl: get(this.keys.url).string(),\n\t\t\t\t\t// Better Auth's CSRF check applies to every caller, not just\n\t\t\t\t\t// browsers, so an API calling the auth server is rejected unless\n\t\t\t\t\t// its origin is trusted. The list is derived from the graph and\n\t\t\t\t\t// arrives as one comma-separated value, for the same reason every\n\t\t\t\t\t// other derived value arrives as a string: it crosses a process\n\t\t\t\t\t// boundary as env.\n\t\t\t\t\ttrustedOrigins: get(this.keys.trustedOrigins)\n\t\t\t\t\t\t.string()\n\t\t\t\t\t\t.default('')\n\t\t\t\t\t\t.transform((value) =>\n\t\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t\t.split(',')\n\t\t\t\t\t\t\t\t.map((origin) => origin.trim())\n\t\t\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t\t\t),\n\t\t\t\t\t// The domain a session cookie has to carry to be readable by a\n\t\t\t\t\t// frontend on a sibling host. Optional because there is often\n\t\t\t\t\t// nothing to widen to: locally everything shares `localhost`,\n\t\t\t\t\t// where cookies ignore the port and a `Domain` would only be a\n\t\t\t\t\t// value the browser refuses.\n\t\t\t\t\tcookieDomain: get(this.keys.cookieDomain).string().optional(),\n\t\t\t\t\t// Where a phone reaches this server, on a local stage with a mobile\n\t\t\t\t\t// app: its own port on the LAN address. Never deployed.\n\t\t\t\t\tdeviceUrl: get(provideKey(this.id, 'deviceUrl')).string().optional(),\n\t\t\t\t}))\n\t\t\t\t.parse();\n\n\t\t// The tenant's own client: one construct, one connection, so what auth\n\t\t// writes and what the browser inspects cannot be two different databases.\n\t\t// A migration asks the tenant for its owner connection, which the tenant\n\t\t// exposes as a `Service` and not as anything `.dependsOn()` would take.\n\t\tconst tenant = this.config.database as Consumable & {\n\t\t\towner?: Service<string, unknown>;\n\t\t};\n\t\tconst source = as.owner && tenant.owner ? tenant.owner : tenant.service;\n\n\t\tconst db = (await source.register(options)) as Kysely<\n\t\t\tRecord<string, never>\n\t\t>;\n\n\t\tconst configured = await this.configured(options);\n\n\t\t// Whatever the app added wins over the derived list rather than\n\t\t// replacing it: an origin nobody declared is still sometimes real.\n\t\tconst origins = [\n\t\t\t...trustedOrigins,\n\t\t\t...(configured.trustedOrigins && Array.isArray(configured.trustedOrigins)\n\t\t\t\t? configured.trustedOrigins\n\t\t\t\t: []),\n\t\t];\n\n\t\tconst plugins = [...(configured.plugins ?? [])];\n\t\t// A mobile app depends on this server: the graph put its scheme among\n\t\t// the derived origins. It signs in through Better Auth's Expo plugin —\n\t\t// the app sends its scheme as the origin, and the plugin is what reads\n\t\t// it — so a server without it would refuse every request the app made.\n\t\t// Asked of the app rather than imported here: a package this one\n\t\t// imported would have to be its peer, and an optional peer gives every\n\t\t// differently-resolving workspace package its own copy of this one.\n\t\tconst mobile = trustedOrigins.filter((origin) => !isWebOrigin(origin));\n\t\tif (mobile.length > 0 && !plugins.some((plugin) => plugin.id === 'expo')) {\n\t\t\tthrow new ExpoPluginRequired(this.id, mobile);\n\t\t}\n\t\t// A sign-in link the app asked for is opened on the phone, which cannot\n\t\t// resolve this server's local hostname; on a local stage it is built on\n\t\t// the address the phone reaches it on instead.\n\t\tif (deviceUrl) {\n\t\t\tfor (const plugin of plugins) reachableFromDevice(plugin, deviceUrl);\n\t\t}\n\n\t\treturn {\n\t\t\t...configured,\n\t\t\tsecret,\n\t\t\tbaseURL: baseUrl,\n\t\t\tbasePath: this.basePath,\n\t\t\tdatabase: { db, type: 'postgres' },\n\t\t\tplugins,\n\t\t\ttrustedOrigins: origins,\n\t\t\tadvanced: {\n\t\t\t\t...configured.advanced,\n\t\t\t\t// The client's address on a call from one of this stack's own\n\t\t\t\t// services comes in gkm's header, ahead of whatever the app reads\n\t\t\t\t// otherwise — `X-Forwarded-For` by default, as Better Auth reads a\n\t\t\t\t// request that reached it through a proxy. The header is honoured\n\t\t\t\t// only from an internal caller: see `withTrustedClientIp`.\n\t\t\t\tipAddress: {\n\t\t\t\t\t...configured.advanced?.ipAddress,\n\t\t\t\t\tipAddressHeaders: [\n\t\t\t\t\t\tCLIENT_IP_HEADER,\n\t\t\t\t\t\t...(\n\t\t\t\t\t\t\tconfigured.advanced?.ipAddress?.ipAddressHeaders ?? [\n\t\t\t\t\t\t\t\t'x-forwarded-for',\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t).filter((name) => name.toLowerCase() !== CLIENT_IP_HEADER),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t// Only when a domain was derived. Better Auth reads the presence\n\t\t\t\t// of this block as intent, so enabling it with no domain would\n\t\t\t\t// widen the cookie to whatever host happened to set it — and the\n\t\t\t\t// case with nothing to widen to is the common one, not an error.\n\t\t\t\t...(cookieDomain\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcrossSubDomainCookies: {\n\t\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\t\tdomain: cookieDomain,\n\t\t\t\t\t\t\t\t...configured.advanced?.crossSubDomainCookies,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** Links already rewritten — an `options` object is reused across builds. */\nconst rewritten = new WeakSet<object>();\n\n/**\n * Build the magic links an app asked for on the address a phone reaches.\n *\n * An app's link carries its scheme as the `callbackURL` (`shop://…`)\n * where a browser's carries a path or an `http(s)` URL — which is how the two\n * are told apart. A browser's link is left alone: it is opened on this\n * machine, where the server's own hostname resolves.\n *\n * Better Auth's magic-link plugin calls `sendMagicLink` through the options\n * object it returns, so wrapping it there is wrapping the call.\n */\nfunction reachableFromDevice(plugin: { id: string }, deviceUrl: string): void {\n\tif (plugin.id !== 'magic-link') return;\n\tconst options = (plugin as { options?: MagicLinkOptions }).options;\n\tif (!options?.sendMagicLink || rewritten.has(options)) return;\n\trewritten.add(options);\n\n\tconst send = options.sendMagicLink;\n\toptions.sendMagicLink = (data, ...rest) =>\n\t\tsend({ ...data, url: deviceLink(data.url, deviceUrl) }, ...rest);\n}\n\ninterface MagicLinkOptions {\n\tsendMagicLink?: (\n\t\tdata: { email: string; url: string; token: string },\n\t\t...rest: unknown[]\n\t) => unknown;\n}\n\n/** A magic link moved to the device address when an app is its destination. */\nexport function deviceLink(url: string, deviceUrl: string): string {\n\ttry {\n\t\tconst link = new URL(url);\n\t\tconst callback = link.searchParams.get('callbackURL') ?? '/';\n\t\tif (callback.startsWith('/') || isWebOrigin(callback)) return url;\n\t\treturn new URL(`${link.pathname}${link.search}`, deviceUrl).toString();\n\t} catch {\n\t\treturn url;\n\t}\n}\n\n/** A mobile app depends on this auth server, which has no Expo plugin. */\nexport class ExpoPluginRequired extends Error {\n\tconstructor(\n\t\treadonly server: string,\n\t\t/** The schemes the graph says call it — what made the plugin necessary. */\n\t\treadonly origins: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`'${server}' is called by a mobile app (${origins[0]}), and a mobile app ` +\n\t\t\t\t`signs in through Better Auth's Expo plugin: add expo() from ` +\n\t\t\t\t`'@better-auth/expo' to this auth server's plugins.`,\n\t\t);\n\t\tthis.name = 'ExpoPluginRequired';\n\t}\n}\n\n/**\n * What is forwarded to the auth server: the headers a session travels in, and\n * the origin the request came from. The API calls the auth server at its\n * public address, through the edge, which marks the call as outside traffic;\n * the origin is what lets the auth server continue the trace exactly when\n * the API did — for a request from one of the sites both trust.\n */\nconst SESSION_HEADERS = ['cookie', 'authorization', 'origin'] as const;\n\n/**\n * `GET <basePath>/get-session`, read the way Better Auth answers it.\n *\n * Whose request it is travels in {@link CLIENT_IP_HEADER} — the server\n * rate-limits `/get-session` by the client's address, so without it every\n * caller shares the API's one bucket — and never as `X-Forwarded-For`, which\n * marks a request as outside traffic. The call goes to the auth server's\n * public address, through the stack's edge, so the stack's token goes with\n * it ({@link EDGE_TOKEN_HEADER}): the edge keeps gkm's header only on a\n * request carrying it, and the auth server honours it from one. The\n * request's `Origin` is passed on so the trace is continued for a site both\n * trust.\n */\nasync function fetchSession(\n\tauthenticator: string,\n\tendpoint: string,\n\tgiven: Headers,\n\t/** The stack's token, which keeps the client's address through the edge. */\n\tedgeToken?: string,\n): Promise<AuthSession | null> {\n\tconst headers = new Headers();\n\tfor (const name of SESSION_HEADERS) {\n\t\tconst value = given.get(name);\n\t\tif (value) headers.set(name, value);\n\t}\n\t// The chain as the API received it, so the auth server reads it exactly\n\t// as it would have read `X-Forwarded-For` (its `trustedProxies` included).\n\t// Never a `CLIENT_IP_HEADER` the API was sent: this process cannot tell\n\t// here whether its own caller was internal, and the auth server trusts\n\t// whatever an internal caller — this one — says.\n\tconst client = given.get('x-forwarded-for');\n\tif (client) {\n\t\theaders.set(CLIENT_IP_HEADER, client);\n\t\t// Through the edge, which keeps gkm's header only on a request that\n\t\t// proves it comes from a service of this stack.\n\t\tif (edgeToken) headers.set(EDGE_TOKEN_HEADER, edgeToken);\n\t}\n\tinjectTraceContext(headers);\n\n\tconst url = `${endpoint}/get-session`;\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, { headers });\n\t} catch (cause) {\n\t\tthrow new AuthServerUnreachable(authenticator, url, cause);\n\t}\n\n\t// Better Auth answers `null` for a request with no session, and a 401 is\n\t// the same answer from anything in front of it. Anything else that is not\n\t// a 200 is the server failing, which is not \"signed out\" and must not be\n\t// read as it.\n\tif (response.status === 401) return null;\n\tif (!response.ok) {\n\t\tthrow new SessionCheckFailed(authenticator, response.status);\n\t}\n\n\treturn (await response.json()) as AuthSession | null;\n}\n\n/** The auth server answered a session check with a failure. */\nexport class SessionCheckFailed extends Error {\n\tconstructor(\n\t\treadonly authenticator: string,\n\t\treadonly status: number,\n\t) {\n\t\tsuper(\n\t\t\t`'${authenticator}' answered a session check with ${status}. ` +\n\t\t\t\t`A request with no session gets 200 and null, or 401; this is the ` +\n\t\t\t\t`server failing — check its logs, and that it is running at its URL.`,\n\t\t);\n\t\tthis.name = 'SessionCheckFailed';\n\t}\n}\n\n/** A session check never reached the auth server. */\nexport class AuthServerUnreachable extends Error {\n\tconstructor(\n\t\treadonly authenticator: string,\n\t\treadonly url: string,\n\t\tcause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`'${authenticator}' could not be reached at ${url} to check a session. ` +\n\t\t\t\t`Check that the auth app is running and that this app's ` +\n\t\t\t\t`${provideKey(authenticator, 'url')} points at it.`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'AuthServerUnreachable';\n\t}\n}\n\n/**\n * Better Auth's DDL, safe to run where its tables already exist.\n *\n * Its SQL is Kysely's, so its shape is known: `create table \"…\"`, `create index\n * \"…\"`, `alter table \"…\" add column \"…\"`. A database that has been running\n * already has those — Better Auth used to create them at runtime — and the\n * first committed migration would fail on them rather than recording that they\n * are there.\n */\nexport function idempotent(statements: string): string {\n\treturn statements\n\t\t.replace(/\\bcreate table \"/gi, 'create table if not exists \"')\n\t\t.replace(\n\t\t\t/\\bcreate (unique )?index \"/gi,\n\t\t\t(_, unique = '') => `create ${unique}index if not exists \"`,\n\t\t)\n\t\t.replace(/\\badd column \"/gi, 'add column if not exists \"');\n}\n\n/** Headers a reverse proxy or CDN adds on the way in. */\nconst FORWARDING_HEADERS = [\n\t'forwarded',\n\t'x-forwarded-for',\n\t'x-forwarded-host',\n\t'x-real-ip',\n\t'cf-connecting-ip',\n\t'true-client-ip',\n\t'fastly-client-ip',\n\t'x-client-ip',\n];\n\n/**\n * `request`, without {@link CLIENT_IP_HEADER} unless an internal caller sent\n * it — no `Origin`, no forwarding header, a loopback or private peer: the\n * rule a request's span continues a trace by (`@geekmidas/telescope`'s\n * `isInternalCaller`).\n *\n * The stack's own edges strip the header already. This holds wherever one\n * does not — a platform's proxy, a port published straight to the internet —\n * so a stranger cannot pick the address Better Auth rate-limits them by.\n */\nexport function withTrustedClientIp(\n\trequest: Request,\n\tremoteAddress: string | undefined,\n\t/**\n\t * The stack's token. A request carrying it came from one of the stack's\n\t * own services through its edge — which keeps the header only then — so\n\t * the forwarding header the edge added does not make it outside traffic.\n\t */\n\tedgeToken?: string,\n): Request {\n\tif (!request.headers.has(CLIENT_IP_HEADER)) return request;\n\tconst internal =\n\t\t!request.headers.has('origin') &&\n\t\t!FORWARDING_HEADERS.some((name) => request.headers.has(name)) &&\n\t\tisPrivateAddress(remoteAddress);\n\tif (\n\t\tinternal ||\n\t\tsameToken(request.headers.get(EDGE_TOKEN_HEADER), edgeToken)\n\t) {\n\t\treturn request;\n\t}\n\n\tconst headers = new Headers(request.headers);\n\theaders.delete(CLIENT_IP_HEADER);\n\treturn new Request(request, { headers });\n}\n\n/** Whether a request's token is the stack's, compared in constant time. */\nfunction sameToken(sent: string | null, expected: string | undefined): boolean {\n\tif (!sent || !expected) return false;\n\tconst a = Buffer.from(sent);\n\tconst b = Buffer.from(expected);\n\treturn a.length === b.length && timingSafeEqual(a, b);\n}\n\n/** The TCP peer of a request served by `@hono/node-server`, when there is one. */\nfunction remoteAddressOf(c: { env: unknown }): string | undefined {\n\tconst env = c.env as\n\t\t| { incoming?: { socket?: { remoteAddress?: string } } }\n\t\t| undefined;\n\treturn env?.incoming?.socket?.remoteAddress;\n}\n\n/**\n * Whether `address` is loopback or private: 127/8, 10/8, 172.16/12,\n * 192.168/16, 169.254/16, `::1`, `fc00::/7`, `fe80::/10`, and an IPv4 one\n * mapped into IPv6.\n */\nfunction isPrivateAddress(address: string | undefined): boolean {\n\tif (!address) return false;\n\tconst ip = address.toLowerCase().replace(/^::ffff:/, '');\n\n\tconst v4 = ip.match(/^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/);\n\tif (v4) {\n\t\tconst [a, b] = [Number(v4[1]), Number(v4[2])];\n\t\treturn (\n\t\t\ta === 127 ||\n\t\t\ta === 10 ||\n\t\t\t(a === 172 && b >= 16 && b <= 31) ||\n\t\t\t(a === 192 && b === 168) ||\n\t\t\t(a === 169 && b === 254)\n\t\t);\n\t}\n\n\tif (ip === '::1') return true;\n\treturn /^f[cd][0-9a-f]{2}:/.test(ip) || /^fe[89ab][0-9a-f]:/.test(ip);\n}\n"],"mappings":";;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AAC,GAAG,KAAK,CAAC,OAAO,GAAG,EAAE,GAAG,OAAO,GAAG,EAAE,CAAC;EAC5C,OACC,MAAM,OACN,MAAM,MACL,MAAM,OAAO,KAAK,MAAM,KAAK,MAC7B,MAAM,OAAO,MAAM,OACnB,MAAM,OAAO,MAAM;CAEtB;CAEA,IAAI,OAAO,OAAO,OAAO;CACzB,OAAO,qBAAqB,KAAK,EAAE,KAAK,qBAAqB,KAAK,EAAE;AACrE"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as Construct } from "./construct-interface-
|
|
1
|
+
import { n as Construct } from "./construct-interface-DugP0E5q.cjs";
|
|
2
|
+
import { Service } from "@geekmidas/services";
|
|
2
3
|
import { ConstructName, Declaration } from "@geekmidas/manifest";
|
|
3
4
|
import { Cache } from "@geekmidas/cache";
|
|
4
|
-
import { Service } from "@geekmidas/services";
|
|
5
5
|
//#region src/cache.d.ts
|
|
6
6
|
interface CacheOptions {
|
|
7
7
|
/**
|
|
@@ -41,4 +41,4 @@ declare class Cache$1<TName extends string = string> implements Construct<TName,
|
|
|
41
41
|
}
|
|
42
42
|
//#endregion
|
|
43
43
|
export { CacheOptions as n, Cache$1 as t };
|
|
44
|
-
//# sourceMappingURL=cache-
|
|
44
|
+
//# sourceMappingURL=cache-CQjMNPrC.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-
|
|
1
|
+
{"version":3,"file":"cache-CQjMNPrC.d.cts","names":["Cache","CacheClient"],"sources":["../src/cache.ts"],"mappings":";;;;;UA6BiB;;;;;;;;EAQhB;;EAEA;;cAGYA,QAAM,0CACP,UAAU,OAAOC;mBAaV;WAXT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQA;;;;;mBAM9B;EAEjB,YACC,IAAI,cAAc,QACD,UAAS;EAc3B,WAAW;;;;;;;;;;;;UAuBG"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as Construct } from "./construct-interface-
|
|
2
|
-
import { Service } from "@geekmidas/services";
|
|
1
|
+
import { n as Construct } from "./construct-interface-CSA9VeWM.mjs";
|
|
3
2
|
import { ConstructName, Declaration } from "@geekmidas/manifest";
|
|
4
3
|
import { Cache } from "@geekmidas/cache";
|
|
4
|
+
import { Service } from "@geekmidas/services";
|
|
5
5
|
//#region src/cache.d.ts
|
|
6
6
|
interface CacheOptions {
|
|
7
7
|
/**
|
|
@@ -41,4 +41,4 @@ declare class Cache$1<TName extends string = string> implements Construct<TName,
|
|
|
41
41
|
}
|
|
42
42
|
//#endregion
|
|
43
43
|
export { CacheOptions as n, Cache$1 as t };
|
|
44
|
-
//# sourceMappingURL=cache-
|
|
44
|
+
//# sourceMappingURL=cache-e3tfMQ9g.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-
|
|
1
|
+
{"version":3,"file":"cache-e3tfMQ9g.d.mts","names":["Cache","CacheClient"],"sources":["../src/cache.ts"],"mappings":";;;;;UA6BiB;;;;;;;;EAQhB;;EAEA;;cAGYA,QAAM,0CACP,UAAU,OAAOC;mBAaV;WAXT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQA;;;;;mBAM9B;EAEjB,YACC,IAAI,cAAc,QACD,UAAS;EAc3B,WAAW;;;;;;;;;;;;UAuBG"}
|
package/dist/cache.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as CacheOptions, t as Cache } from "./cache-
|
|
1
|
+
import { n as CacheOptions, t as Cache } from "./cache-CQjMNPrC.cjs";
|
|
2
2
|
export { Cache, CacheOptions };
|
package/dist/cache.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as CacheOptions, t as Cache } from "./cache-
|
|
1
|
+
import { n as CacheOptions, t as Cache } from "./cache-e3tfMQ9g.mjs";
|
|
2
2
|
export { Cache, CacheOptions };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
2
|
-
import { Service } from "@geekmidas/services";
|
|
3
1
|
import { Declaration, Dependency } from "@geekmidas/manifest";
|
|
2
|
+
import { Service, ServiceRegisterOptions } from "@geekmidas/services";
|
|
3
|
+
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
4
4
|
//#region src/construct-interface.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* @typeParam TName - the construct's canonical id, PascalCase. Keeping it a
|
|
@@ -157,6 +157,11 @@ declare function isConsumable(value: unknown): value is Consumable;
|
|
|
157
157
|
* construct to stand for it.
|
|
158
158
|
*/
|
|
159
159
|
declare function serviceOf<TName extends string, TClient>(source: Consumable<TName, TClient> | Service<TName, TClient>): Service<TName, TClient>;
|
|
160
|
+
/**
|
|
161
|
+
* A surface's or a site's public address, read from its `<ID>_URL` — the
|
|
162
|
+
* client a `RestApi` or a `StaticSite` hands whatever `.dependsOn()` it.
|
|
163
|
+
*/
|
|
164
|
+
declare function publicUrl(options: ServiceRegisterOptions, key: string): string;
|
|
160
165
|
//#endregion
|
|
161
|
-
export { Infer as a, ServicesOf as c, idsOf as d, isConsumable as f, Declarable as i, databaseEdges as l,
|
|
162
|
-
//# sourceMappingURL=construct-interface-
|
|
166
|
+
export { Infer as a, ServicesOf as c, idsOf as d, isConsumable as f, servicesOf as h, Declarable as i, databaseEdges as l, serviceOf as m, Construct as n, NameOf as o, publicUrl as p, Consumable as r, NotAConstruct as s, Authenticator as t, edgeTo as u };
|
|
167
|
+
//# sourceMappingURL=construct-interface-CSA9VeWM.d.mts.map
|
package/dist/{construct-interface-B1AfqRl4.d.cts.map → construct-interface-CSA9VeWM.d.mts.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"construct-interface-
|
|
1
|
+
{"version":3,"file":"construct-interface-CSA9VeWM.d.mts","names":[],"sources":["../src/construct-interface.ts"],"mappings":";;;;;;;;;;;;;UA8BiB,UAAU,+BAA+B;;WAEhD,IAAI;;;;;;;;EASb,WAAW;;;;;;;;WASF,UAAU,mCAEhB,QAAQ,aAAa,QAAQ;;;;;;;;;;;UAYhB,WAAW;WAClB,IAAI;EACb,WAAW;;;;;;;;;;UAWK,cAAc,4BAA4B;EAC1D,OACC,SAAS,SACT,WAAW,wBACT,QAAQ;;;;;;;;;;;;;;iBAeI,OAAO,WAAW,aAAa;;KAWnC,MAAM,KACjB,UAAU,wBAAwB,WAAW;;KAGlC,OAAO,KAClB,UAAU,gBAAgB,kBAAkB;;;;;;;;;;;UAY5B,WAAW,+BAA+B;WACjD,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQ;EAC/C,WAAW;;;;;;;;;;KAWA,WAAW,mBAAmB,mBACxC,WAAW,IAAI,EAAE;;;;;;;;iBAUH,iBAAiB,mBAAmB,cACnD,YAAY,IACV,WAAW;;;;;;;;;;iBAiBE,MACf,qBAAqB,cACrB;;;;;;;;;;;;;;iBAkBe,cACf;EACC;EACA;EACA,SAAS;EACT,mBAAmB;GAEpB;EACI;EAAuB;;;cAgBf,sBAAsB;WACb;EAArB,YAAqB;;;;;;;;;iBAqBN,aAAa,iBAAiB,SAAS;;;;;;;;iBAmBvC,UAAU,sBAAsB,SAC/C,QAAQ,WAAW,OAAO,WAAW,QAAQ,OAAO,WAClD,QAAQ,OAAO;;;;;iBAYF,UACf,SAAS,wBACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Declaration, Dependency } from "@geekmidas/manifest";
|
|
2
|
-
import { Service } from "@geekmidas/services";
|
|
3
1
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
2
|
+
import { Service, ServiceRegisterOptions } from "@geekmidas/services";
|
|
3
|
+
import { Declaration, Dependency } from "@geekmidas/manifest";
|
|
4
4
|
//#region src/construct-interface.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* @typeParam TName - the construct's canonical id, PascalCase. Keeping it a
|
|
@@ -157,6 +157,11 @@ declare function isConsumable(value: unknown): value is Consumable;
|
|
|
157
157
|
* construct to stand for it.
|
|
158
158
|
*/
|
|
159
159
|
declare function serviceOf<TName extends string, TClient>(source: Consumable<TName, TClient> | Service<TName, TClient>): Service<TName, TClient>;
|
|
160
|
+
/**
|
|
161
|
+
* A surface's or a site's public address, read from its `<ID>_URL` — the
|
|
162
|
+
* client a `RestApi` or a `StaticSite` hands whatever `.dependsOn()` it.
|
|
163
|
+
*/
|
|
164
|
+
declare function publicUrl(options: ServiceRegisterOptions, key: string): string;
|
|
160
165
|
//#endregion
|
|
161
|
-
export { Infer as a, ServicesOf as c, idsOf as d, isConsumable as f, Declarable as i, databaseEdges as l,
|
|
162
|
-
//# sourceMappingURL=construct-interface-
|
|
166
|
+
export { Infer as a, ServicesOf as c, idsOf as d, isConsumable as f, servicesOf as h, Declarable as i, databaseEdges as l, serviceOf as m, Construct as n, NameOf as o, publicUrl as p, Consumable as r, NotAConstruct as s, Authenticator as t, edgeTo as u };
|
|
167
|
+
//# sourceMappingURL=construct-interface-DugP0E5q.d.cts.map
|
package/dist/{construct-interface-ZvYQbivO.d.mts.map → construct-interface-DugP0E5q.d.cts.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"construct-interface-
|
|
1
|
+
{"version":3,"file":"construct-interface-DugP0E5q.d.cts","names":[],"sources":["../src/construct-interface.ts"],"mappings":";;;;;;;;;;;;;UA8BiB,UAAU,+BAA+B;;WAEhD,IAAI;;;;;;;;EASb,WAAW;;;;;;;;WASF,UAAU,mCAEhB,QAAQ,aAAa,QAAQ;;;;;;;;;;;UAYhB,WAAW;WAClB,IAAI;EACb,WAAW;;;;;;;;;;UAWK,cAAc,4BAA4B;EAC1D,OACC,SAAS,SACT,WAAW,wBACT,QAAQ;;;;;;;;;;;;;;iBAeI,OAAO,WAAW,aAAa;;KAWnC,MAAM,KACjB,UAAU,wBAAwB,WAAW;;KAGlC,OAAO,KAClB,UAAU,gBAAgB,kBAAkB;;;;;;;;;;;UAY5B,WAAW,+BAA+B;WACjD,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQ;EAC/C,WAAW;;;;;;;;;;KAWA,WAAW,mBAAmB,mBACxC,WAAW,IAAI,EAAE;;;;;;;;iBAUH,iBAAiB,mBAAmB,cACnD,YAAY,IACV,WAAW;;;;;;;;;;iBAiBE,MACf,qBAAqB,cACrB;;;;;;;;;;;;;;iBAkBe,cACf;EACC;EACA;EACA,SAAS;EACT,mBAAmB;GAEpB;EACI;EAAuB;;;cAgBf,sBAAsB;WACb;EAArB,YAAqB;;;;;;;;;iBAqBN,aAAa,iBAAiB,SAAS;;;;;;;;iBAmBvC,UAAU,sBAAsB,SAC/C,QAAQ,WAAW,OAAO,WAAW,QAAQ,OAAO,WAClD,QAAQ,OAAO;;;;;iBAYF,UACf,SAAS,wBACT"}
|
|
@@ -102,12 +102,20 @@ function isConsumable(value) {
|
|
|
102
102
|
function serviceOf(source) {
|
|
103
103
|
return isConsumable(source) ? source.service : source;
|
|
104
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* A surface's or a site's public address, read from its `<ID>_URL` — the
|
|
107
|
+
* client a `RestApi` or a `StaticSite` hands whatever `.dependsOn()` it.
|
|
108
|
+
*/
|
|
109
|
+
function publicUrl(options, key) {
|
|
110
|
+
return options.envParser.create((get) => ({ url: get(key).string() })).parse().url;
|
|
111
|
+
}
|
|
105
112
|
//#endregion
|
|
106
113
|
exports.NotAConstruct = NotAConstruct;
|
|
107
114
|
exports.databaseEdges = databaseEdges;
|
|
108
115
|
exports.edgeTo = edgeTo;
|
|
109
116
|
exports.idsOf = idsOf;
|
|
110
117
|
exports.isConsumable = isConsumable;
|
|
118
|
+
exports.publicUrl = publicUrl;
|
|
111
119
|
exports.serviceOf = serviceOf;
|
|
112
120
|
exports.servicesOf = servicesOf;
|
|
113
121
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"construct-interface.cjs","names":[],"sources":["../src/construct-interface.ts"],"sourcesContent":["/**\n * The construct contract.\n *\n * A construct is three things at once — an infrastructure requirement at build\n * time, a runtime capability, and something other code can consume — which is\n * what forces exactly these three members.\n *\n * An **interface**, not a base class: `Endpoint`, `Cron`, `Queue`, and `Topic`\n * can satisfy it without inheritance surgery, a lifted `Service` can satisfy it\n * as a plain object, and `.dependsOn()` gets its enforcement structurally — a\n * `Service` (`{ serviceName, register }`) simply does not match\n * `{ id, declare, service }`, with no `instanceof` anywhere.\n *\n * Lives in its own module while the existing abstract `Construct` class is\n * still in use; it takes that name once the class is gone.\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Declaration, Dependency } from '@geekmidas/manifest';\nimport type { Service } from '@geekmidas/services';\n\n/**\n * @typeParam TName - the construct's canonical id, PascalCase. Keeping it a\n * literal is what lets the service key be `Uncapitalize<TName>` — a TypeScript\n * intrinsic, so no custom transform needs a runtime twin.\n * @typeParam TClient - what consuming this construct hands you. `never` means it\n * owns no address and cannot be consumed: a `Cron` is fired by a schedule and a\n * `Subscriber` is reached through its topic, so `.dependsOn()` on either is a\n * compile error rather than a stub that throws.\n */\nexport interface Construct<TName extends string = string, TClient = never> {\n\t/** Canonical, PascalCase, unique within the manifest. */\n\treadonly id: TName;\n\n\t/**\n\t * The build-time face: what this construct contributes to the manifest.\n\t *\n\t * Returns an array because some constructs contribute more than one node — a\n\t * queue declares the queue and its worker, a database declares its migrator\n\t * and seeder. Most return one.\n\t */\n\tdeclare(): Declaration[];\n\n\t/**\n\t * The consumable face — the address this construct owns, as a client.\n\t *\n\t * A field assigned once rather than a getter. `Construct.getEnvironment`\n\t * and `ServiceDiscovery` cache by service *object*, so a getter returning a\n\t * fresh literal on every access would never hit either cache.\n\t */\n\treadonly service: [TClient] extends [never]\n\t\t? never\n\t\t: Service<Uncapitalize<TName>, TClient>;\n}\n\n/**\n * The build-time face alone — an id and what it contributes to the manifest.\n *\n * Weaker than {@link Consumable} on purpose. An edge is not always an\n * injection: a site depending on an API needs that API's *address at build\n * time* and has no service record to put a client into, so requiring one would\n * make the weakest kind of edge impossible to express with the strongest\n * interface. Discovery asks this same question and nothing more.\n */\nexport interface Declarable<TName extends string = string> {\n\treadonly id: TName;\n\tdeclare(): Declaration[];\n}\n\n/**\n * A construct that authenticates requests — what `RestApi.auth()` takes.\n *\n * `verify` is the one thing every provider shares: given a request's headers,\n * whose request is it — the session, or `null` when there is none. Whether the\n * provider is a server mounted beside the API, deployed elsewhere, or an issuer\n * somebody else runs is its own business; a surface only ever asks this.\n */\nexport interface Authenticator<TSession = unknown> extends Declarable {\n\tverify(\n\t\theaders: Headers,\n\t\tenvParser: EnvironmentParser<{}>,\n\t): Promise<TSession | null>;\n}\n\n/**\n * The edge that points at a construct.\n *\n * A construct's *canonical* node is the one carrying its own id — the others are\n * things it owns rather than things it is, like the signing secret beside an\n * auth server — so the kind an edge records is read off that node instead of\n * being written down beside it. Hand-written kinds are the same fact stated\n * twice, and the copy is what goes stale when a construct changes what it\n * declares.\n *\n * @throws {NotAConstruct} when the value declares nothing under its own id.\n */\nexport function edgeTo(construct: Declarable): Dependency {\n\tconst canonical = construct\n\t\t.declare()\n\t\t.find((declaration) => declaration.id === construct.id);\n\n\tif (!canonical) throw new NotAConstruct(construct);\n\n\treturn { target: construct.id, kind: canonical.kind };\n}\n\n/** What consuming a construct hands you. */\nexport type Infer<C> =\n\tC extends Construct<string, infer TClient> ? TClient : never;\n\n/** A construct's canonical id. */\nexport type NameOf<C> =\n\tC extends Construct<infer TName, unknown> ? TName : never;\n\n/**\n * What `.dependsOn([…])` accepts: a construct that owns a client.\n *\n * Structural, and deliberately narrower than {@link Construct} — it is the\n * face a *consumer* needs, so the builders can accept a database, a bucket, a\n * mail sender, a queue, or a topic without importing any of them. A plain\n * `Service` is not one of these, which is the point: constructs-only confines\n * env sniffing to `.services()` and the explicit lift, so retiring that method\n * retires implicit inference with it.\n */\nexport interface Consumable<TName extends string = string, TClient = unknown> {\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, TClient>;\n\tdeclare(): Declaration[];\n}\n\n/**\n * The services a list of constructs dissolves into.\n *\n * A mapped tuple, so `[db, uploads]` types as `[Service<'orders', Kysely<DB>>,\n * Service<'uploads', StorageClient>]` and the handler's service record gains\n * both keys — the same machinery `.services()` already uses, which is why\n * `dependsOn` needs no type plumbing of its own.\n */\nexport type ServicesOf<T extends readonly Consumable[]> = {\n\t[K in keyof T]: T[K]['service'];\n};\n\n/**\n * The services of a list of constructs, at runtime.\n *\n * @throws {NotAConstruct} when handed something else. The type already refuses\n * it, but a JavaScript caller gets no such warning, and a `Service` slipping\n * through would fail later as an undefined key in the handler.\n */\nexport function servicesOf<const T extends readonly Consumable[]>(\n\tconstructs: T,\n): ServicesOf<T> {\n\treturn constructs.map((construct) => {\n\t\tif (!isConsumable(construct)) throw new NotAConstruct(construct);\n\n\t\treturn construct.service;\n\t}) as ServicesOf<T>;\n}\n\n/**\n * The other half of `servicesOf`: the same edge, as the manifest records it.\n *\n * `.dependsOn()` used to keep only the services, which is what a handler runs\n * with — and an id cannot be recovered from a service name reliably, so the\n * edges were gone by the time the build could read them. Both halves are taken\n * from one call now, and `existing` is folded in so repeated `.dependsOn()`\n * calls accumulate the way `.services()` already does.\n */\nexport function idsOf(\n\tconstructs: readonly Consumable[],\n\texisting: readonly string[] = [],\n): string[] {\n\treturn [...new Set([...existing, ...constructs.map(({ id }) => id)])];\n}\n\n/**\n * The edges after `.database(source)` names a builder's database.\n *\n * A database replaces the one before it — a worker's default, overridden by a\n * runnable that names its own — so the edge the previous one added goes with\n * it. Left behind, a Lambda built from a queue that moved to another database\n * would still be granted the worker's.\n *\n * Only an edge `.database()` added is removed, which is why it is returned as\n * `_databaseEdge` for the next call to read — and not even that one when\n * `.dependsOn()` has since named the same construct, since the handler still\n * reaches it through `services`.\n */\nexport function databaseEdges(\n\tcurrent: {\n\t\tconstructs: readonly string[];\n\t\tedge: string | undefined;\n\t\tservice: Service | undefined;\n\t\tservices: readonly Service[];\n\t},\n\tsource: unknown,\n): { _constructs: string[]; _databaseEdge: string | undefined } {\n\tconst stillDependedOn =\n\t\tcurrent.service !== undefined && current.services.includes(current.service);\n\tconst kept =\n\t\tcurrent.edge && !stillDependedOn\n\t\t\t? current.constructs.filter((id) => id !== current.edge)\n\t\t\t: [...current.constructs];\n\n\tif (!isConsumable(source) || kept.includes(source.id)) {\n\t\treturn { _constructs: kept, _databaseEdge: undefined };\n\t}\n\n\treturn { _constructs: [...kept, source.id], _databaseEdge: source.id };\n}\n\n/** Something that is not a construct was passed to `.dependsOn()`. */\nexport class NotAConstruct extends Error {\n\tconstructor(readonly value: unknown) {\n\t\tconst name =\n\t\t\ttypeof value === 'object' && value !== null && 'serviceName' in value\n\t\t\t\t? `the service '${String((value as { serviceName: unknown }).serviceName)}'`\n\t\t\t\t: `a ${typeof value}`;\n\n\t\tsuper(\n\t\t\t`.dependsOn() takes constructs, and was given ${name}. ` +\n\t\t\t\t`Pass it to .services([…]) instead.`,\n\t\t);\n\t\tthis.name = 'NotAConstruct';\n\t}\n}\n\n/**\n * Whether a value is a construct rather than a bare `Service`.\n *\n * Structural rather than `instanceof`: a construct from a second copy of\n * `@geekmidas/constructs` — a linked workspace, two versions in a lockfile — is\n * still a construct, and `instanceof` is exactly the check that says otherwise.\n */\nexport function isConsumable(value: unknown): value is Consumable {\n\tif (typeof value !== 'object' || value === null) return false;\n\n\tconst candidate = value as Partial<Consumable>;\n\n\treturn (\n\t\ttypeof candidate.id === 'string' &&\n\t\ttypeof candidate.declare === 'function' &&\n\t\ttypeof (candidate.service as Service | undefined)?.serviceName === 'string'\n\t);\n}\n\n/**\n * The service behind either face.\n *\n * `.database()` and the auditor slot take a construct now; they took a\n * `Service` before and still do, because not every hand-written service has a\n * construct to stand for it.\n */\nexport function serviceOf<TName extends string, TClient>(\n\tsource: Consumable<TName, TClient> | Service<TName, TClient>,\n): Service<TName, TClient> {\n\t// A construct's service key is `Uncapitalize<TName>` and the slot is typed\n\t// by `TName`; the two describe the same key, and only the cast says so.\n\treturn isConsumable(source)\n\t\t? (source.service as unknown as Service<TName, TClient>)\n\t\t: (source as Service<TName, TCl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;EAToB,KAAA,QAAA;EAUpB,KAAK,OAAO;CACb;AACD;;;;;;;;AASA,SAAgB,aAAa,OAAqC;CACjE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CAExD,MAAM,YAAY;CAElB,OACC,OAAO,UAAU,OAAO,YACxB,OAAO,UAAU,YAAY,cAC7B,OAAQ,UAAU,SAAiC,gBAAgB;AAErE;;;;;;;;AASA,SAAgB,UACf,QAC0B;CAG1B,OAAO,aAAa,MAAM,IACtB,OAAO,UACP;AACL"}
|
|
1
|
+
{"version":3,"file":"construct-interface.cjs","names":[],"sources":["../src/construct-interface.ts"],"sourcesContent":["/**\n * The construct contract.\n *\n * A construct is three things at once — an infrastructure requirement at build\n * time, a runtime capability, and something other code can consume — which is\n * what forces exactly these three members.\n *\n * An **interface**, not a base class: `Endpoint`, `Cron`, `Queue`, and `Topic`\n * can satisfy it without inheritance surgery, a lifted `Service` can satisfy it\n * as a plain object, and `.dependsOn()` gets its enforcement structurally — a\n * `Service` (`{ serviceName, register }`) simply does not match\n * `{ id, declare, service }`, with no `instanceof` anywhere.\n *\n * Lives in its own module while the existing abstract `Construct` class is\n * still in use; it takes that name once the class is gone.\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Declaration, Dependency } from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\n\n/**\n * @typeParam TName - the construct's canonical id, PascalCase. Keeping it a\n * literal is what lets the service key be `Uncapitalize<TName>` — a TypeScript\n * intrinsic, so no custom transform needs a runtime twin.\n * @typeParam TClient - what consuming this construct hands you. `never` means it\n * owns no address and cannot be consumed: a `Cron` is fired by a schedule and a\n * `Subscriber` is reached through its topic, so `.dependsOn()` on either is a\n * compile error rather than a stub that throws.\n */\nexport interface Construct<TName extends string = string, TClient = never> {\n\t/** Canonical, PascalCase, unique within the manifest. */\n\treadonly id: TName;\n\n\t/**\n\t * The build-time face: what this construct contributes to the manifest.\n\t *\n\t * Returns an array because some constructs contribute more than one node — a\n\t * queue declares the queue and its worker, a database declares its migrator\n\t * and seeder. Most return one.\n\t */\n\tdeclare(): Declaration[];\n\n\t/**\n\t * The consumable face — the address this construct owns, as a client.\n\t *\n\t * A field assigned once rather than a getter. `Construct.getEnvironment`\n\t * and `ServiceDiscovery` cache by service *object*, so a getter returning a\n\t * fresh literal on every access would never hit either cache.\n\t */\n\treadonly service: [TClient] extends [never]\n\t\t? never\n\t\t: Service<Uncapitalize<TName>, TClient>;\n}\n\n/**\n * The build-time face alone — an id and what it contributes to the manifest.\n *\n * Weaker than {@link Consumable} on purpose. An edge is not always an\n * injection: a site depending on an API needs that API's *address at build\n * time* and has no service record to put a client into, so requiring one would\n * make the weakest kind of edge impossible to express with the strongest\n * interface. Discovery asks this same question and nothing more.\n */\nexport interface Declarable<TName extends string = string> {\n\treadonly id: TName;\n\tdeclare(): Declaration[];\n}\n\n/**\n * A construct that authenticates requests — what `RestApi.auth()` takes.\n *\n * `verify` is the one thing every provider shares: given a request's headers,\n * whose request is it — the session, or `null` when there is none. Whether the\n * provider is a server mounted beside the API, deployed elsewhere, or an issuer\n * somebody else runs is its own business; a surface only ever asks this.\n */\nexport interface Authenticator<TSession = unknown> extends Declarable {\n\tverify(\n\t\theaders: Headers,\n\t\tenvParser: EnvironmentParser<{}>,\n\t): Promise<TSession | null>;\n}\n\n/**\n * The edge that points at a construct.\n *\n * A construct's *canonical* node is the one carrying its own id — the others are\n * things it owns rather than things it is, like the signing secret beside an\n * auth server — so the kind an edge records is read off that node instead of\n * being written down beside it. Hand-written kinds are the same fact stated\n * twice, and the copy is what goes stale when a construct changes what it\n * declares.\n *\n * @throws {NotAConstruct} when the value declares nothing under its own id.\n */\nexport function edgeTo(construct: Declarable): Dependency {\n\tconst canonical = construct\n\t\t.declare()\n\t\t.find((declaration) => declaration.id === construct.id);\n\n\tif (!canonical) throw new NotAConstruct(construct);\n\n\treturn { target: construct.id, kind: canonical.kind };\n}\n\n/** What consuming a construct hands you. */\nexport type Infer<C> =\n\tC extends Construct<string, infer TClient> ? TClient : never;\n\n/** A construct's canonical id. */\nexport type NameOf<C> =\n\tC extends Construct<infer TName, unknown> ? TName : never;\n\n/**\n * What `.dependsOn([…])` accepts: a construct that owns a client.\n *\n * Structural, and deliberately narrower than {@link Construct} — it is the\n * face a *consumer* needs, so the builders can accept a database, a bucket, a\n * mail sender, a queue, or a topic without importing any of them. A plain\n * `Service` is not one of these, which is the point: constructs-only confines\n * env sniffing to `.services()` and the explicit lift, so retiring that method\n * retires implicit inference with it.\n */\nexport interface Consumable<TName extends string = string, TClient = unknown> {\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, TClient>;\n\tdeclare(): Declaration[];\n}\n\n/**\n * The services a list of constructs dissolves into.\n *\n * A mapped tuple, so `[db, uploads]` types as `[Service<'orders', Kysely<DB>>,\n * Service<'uploads', StorageClient>]` and the handler's service record gains\n * both keys — the same machinery `.services()` already uses, which is why\n * `dependsOn` needs no type plumbing of its own.\n */\nexport type ServicesOf<T extends readonly Consumable[]> = {\n\t[K in keyof T]: T[K]['service'];\n};\n\n/**\n * The services of a list of constructs, at runtime.\n *\n * @throws {NotAConstruct} when handed something else. The type already refuses\n * it, but a JavaScript caller gets no such warning, and a `Service` slipping\n * through would fail later as an undefined key in the handler.\n */\nexport function servicesOf<const T extends readonly Consumable[]>(\n\tconstructs: T,\n): ServicesOf<T> {\n\treturn constructs.map((construct) => {\n\t\tif (!isConsumable(construct)) throw new NotAConstruct(construct);\n\n\t\treturn construct.service;\n\t}) as ServicesOf<T>;\n}\n\n/**\n * The other half of `servicesOf`: the same edge, as the manifest records it.\n *\n * `.dependsOn()` used to keep only the services, which is what a handler runs\n * with — and an id cannot be recovered from a service name reliably, so the\n * edges were gone by the time the build could read them. Both halves are taken\n * from one call now, and `existing` is folded in so repeated `.dependsOn()`\n * calls accumulate the way `.services()` already does.\n */\nexport function idsOf(\n\tconstructs: readonly Consumable[],\n\texisting: readonly string[] = [],\n): string[] {\n\treturn [...new Set([...existing, ...constructs.map(({ id }) => id)])];\n}\n\n/**\n * The edges after `.database(source)` names a builder's database.\n *\n * A database replaces the one before it — a worker's default, overridden by a\n * runnable that names its own — so the edge the previous one added goes with\n * it. Left behind, a Lambda built from a queue that moved to another database\n * would still be granted the worker's.\n *\n * Only an edge `.database()` added is removed, which is why it is returned as\n * `_databaseEdge` for the next call to read — and not even that one when\n * `.dependsOn()` has since named the same construct, since the handler still\n * reaches it through `services`.\n */\nexport function databaseEdges(\n\tcurrent: {\n\t\tconstructs: readonly string[];\n\t\tedge: string | undefined;\n\t\tservice: Service | undefined;\n\t\tservices: readonly Service[];\n\t},\n\tsource: unknown,\n): { _constructs: string[]; _databaseEdge: string | undefined } {\n\tconst stillDependedOn =\n\t\tcurrent.service !== undefined && current.services.includes(current.service);\n\tconst kept =\n\t\tcurrent.edge && !stillDependedOn\n\t\t\t? current.constructs.filter((id) => id !== current.edge)\n\t\t\t: [...current.constructs];\n\n\tif (!isConsumable(source) || kept.includes(source.id)) {\n\t\treturn { _constructs: kept, _databaseEdge: undefined };\n\t}\n\n\treturn { _constructs: [...kept, source.id], _databaseEdge: source.id };\n}\n\n/** Something that is not a construct was passed to `.dependsOn()`. */\nexport class NotAConstruct extends Error {\n\tconstructor(readonly value: unknown) {\n\t\tconst name =\n\t\t\ttypeof value === 'object' && value !== null && 'serviceName' in value\n\t\t\t\t? `the service '${String((value as { serviceName: unknown }).serviceName)}'`\n\t\t\t\t: `a ${typeof value}`;\n\n\t\tsuper(\n\t\t\t`.dependsOn() takes constructs, and was given ${name}. ` +\n\t\t\t\t`Pass it to .services([…]) instead.`,\n\t\t);\n\t\tthis.name = 'NotAConstruct';\n\t}\n}\n\n/**\n * Whether a value is a construct rather than a bare `Service`.\n *\n * Structural rather than `instanceof`: a construct from a second copy of\n * `@geekmidas/constructs` — a linked workspace, two versions in a lockfile — is\n * still a construct, and `instanceof` is exactly the check that says otherwise.\n */\nexport function isConsumable(value: unknown): value is Consumable {\n\tif (typeof value !== 'object' || value === null) return false;\n\n\tconst candidate = value as Partial<Consumable>;\n\n\treturn (\n\t\ttypeof candidate.id === 'string' &&\n\t\ttypeof candidate.declare === 'function' &&\n\t\ttypeof (candidate.service as Service | undefined)?.serviceName === 'string'\n\t);\n}\n\n/**\n * The service behind either face.\n *\n * `.database()` and the auditor slot take a construct now; they took a\n * `Service` before and still do, because not every hand-written service has a\n * construct to stand for it.\n */\nexport function serviceOf<TName extends string, TClient>(\n\tsource: Consumable<TName, TClient> | Service<TName, TClient>,\n): Service<TName, TClient> {\n\t// A construct's service key is `Uncapitalize<TName>` and the slot is typed\n\t// by `TName`; the two describe the same key, and only the cast says so.\n\treturn isConsumable(source)\n\t\t? (source.service as unknown as Service<TName, TClient>)\n\t\t: (source as Service<TName, TClient>);\n}\n\n/**\n * A surface's or a site's public address, read from its `<ID>_URL` — the\n * client a `RestApi` or a `StaticSite` hands whatever `.dependsOn()` it.\n */\nexport function publicUrl(\n\toptions: ServiceRegisterOptions,\n\tkey: string,\n): string {\n\treturn options.envParser.create((get) => ({ url: get(key).string() })).parse()\n\t\t.url;\n}\n"],"mappings":";;;;;;;;;;;;;;AAgGA,SAAgB,OAAO,WAAmC;CACzD,MAAM,YAAY,UAChB,QAAQ,CAAC,CACT,MAAM,gBAAgB,YAAY,OAAO,UAAU,EAAE;CAEvD,IAAI,CAAC,WAAW,MAAM,IAAI,cAAc,SAAS;CAEjD,OAAO;EAAE,QAAQ,UAAU;EAAI,MAAM,UAAU;CAAK;AACrD;;;;;;;;AA6CA,SAAgB,WACf,YACgB;CAChB,OAAO,WAAW,KAAK,cAAc;EACpC,IAAI,CAAC,aAAa,SAAS,GAAG,MAAM,IAAI,cAAc,SAAS;EAE/D,OAAO,UAAU;CAClB,CAAC;AACF;;;;;;;;;;AAWA,SAAgB,MACf,YACA,WAA8B,CAAC,GACpB;CACX,OAAO,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAG,UAAU,GAAG,WAAW,KAAK,EAAE,SAAS,EAA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Consumable, i as Declarable, l as databaseEdges, m as
|
|
2
|
-
export { Authenticator, Construct, Consumable, Declarable, Infer, NameOf, NotAConstruct, ServicesOf, databaseEdges, edgeTo, idsOf, isConsumable, serviceOf, servicesOf };
|
|
1
|
+
import { a as Infer, c as ServicesOf, d as idsOf, f as isConsumable, h as servicesOf, i as Declarable, l as databaseEdges, m as serviceOf, n as Construct, o as NameOf, p as publicUrl, r as Consumable, s as NotAConstruct, t as Authenticator, u as edgeTo } from "./construct-interface-DugP0E5q.cjs";
|
|
2
|
+
export { Authenticator, Construct, Consumable, Declarable, Infer, NameOf, NotAConstruct, ServicesOf, databaseEdges, edgeTo, idsOf, isConsumable, publicUrl, serviceOf, servicesOf };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as Infer, c as ServicesOf, d as idsOf, f as isConsumable, i as Declarable, l as databaseEdges, m as
|
|
2
|
-
export { Authenticator, Construct, Consumable, Declarable, Infer, NameOf, NotAConstruct, ServicesOf, databaseEdges, edgeTo, idsOf, isConsumable, serviceOf, servicesOf };
|
|
1
|
+
import { a as Infer, c as ServicesOf, d as idsOf, f as isConsumable, h as servicesOf, i as Declarable, l as databaseEdges, m as serviceOf, n as Construct, o as NameOf, p as publicUrl, r as Consumable, s as NotAConstruct, t as Authenticator, u as edgeTo } from "./construct-interface-CSA9VeWM.mjs";
|
|
2
|
+
export { Authenticator, Construct, Consumable, Declarable, Infer, NameOf, NotAConstruct, ServicesOf, databaseEdges, edgeTo, idsOf, isConsumable, publicUrl, serviceOf, servicesOf };
|
|
@@ -101,7 +101,14 @@ function isConsumable(value) {
|
|
|
101
101
|
function serviceOf(source) {
|
|
102
102
|
return isConsumable(source) ? source.service : source;
|
|
103
103
|
}
|
|
104
|
+
/**
|
|
105
|
+
* A surface's or a site's public address, read from its `<ID>_URL` — the
|
|
106
|
+
* client a `RestApi` or a `StaticSite` hands whatever `.dependsOn()` it.
|
|
107
|
+
*/
|
|
108
|
+
function publicUrl(options, key) {
|
|
109
|
+
return options.envParser.create((get) => ({ url: get(key).string() })).parse().url;
|
|
110
|
+
}
|
|
104
111
|
//#endregion
|
|
105
|
-
export { NotAConstruct, databaseEdges, edgeTo, idsOf, isConsumable, serviceOf, servicesOf };
|
|
112
|
+
export { NotAConstruct, databaseEdges, edgeTo, idsOf, isConsumable, publicUrl, serviceOf, servicesOf };
|
|
106
113
|
|
|
107
114
|
//# sourceMappingURL=construct-interface.mjs.map
|