@geekmidas/constructs 10.0.0-alpha.88 → 10.0.0-alpha.89
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/{Endpoint-ViSuXwMB.d.mts → Endpoint-Du-NwPX2.d.mts} +2 -2
- package/dist/{Endpoint-C4PZn_mD.d.cts.map → Endpoint-Du-NwPX2.d.mts.map} +1 -1
- package/dist/{Endpoint-C4PZn_mD.d.cts → Endpoint-aCvBMPoH.d.cts} +2 -2
- package/dist/{Endpoint-ViSuXwMB.d.mts.map → Endpoint-aCvBMPoH.d.cts.map} +1 -1
- package/dist/{EndpointFactory-CLmsBr1G.d.mts → EndpointFactory-DMYdJCOj.d.mts} +2 -2
- package/dist/{EndpointFactory-CLmsBr1G.d.mts.map → EndpointFactory-DMYdJCOj.d.mts.map} +1 -1
- package/dist/{EndpointFactory-CLnJ2GQ8.d.cts → EndpointFactory-I7s1co3Y.d.cts} +2 -2
- package/dist/{EndpointFactory-CLnJ2GQ8.d.cts.map → EndpointFactory-I7s1co3Y.d.cts.map} +1 -1
- package/dist/adaptors/aws.d.cts +1 -1
- package/dist/adaptors/aws.d.mts +1 -1
- package/dist/adaptors/hono.d.cts +1 -1
- package/dist/adaptors/hono.d.mts +1 -1
- package/dist/adaptors/testing.d.cts +1 -1
- package/dist/adaptors/testing.d.mts +1 -1
- package/dist/{auth-CwYlcogd.d.cts → auth-BMCJN30Y.d.cts} +2 -2
- package/dist/{auth-CYFghDZw.d.mts.map → auth-BMCJN30Y.d.cts.map} +1 -1
- package/dist/{auth-CYFghDZw.d.mts → auth-CcuceLYo.d.mts} +2 -2
- package/dist/{auth-CwYlcogd.d.cts.map → auth-CcuceLYo.d.mts.map} +1 -1
- 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.map +1 -1
- package/dist/endpoints/index.d.cts +2 -2
- package/dist/endpoints/index.d.mts +2 -2
- package/dist/rest-api.cjs.map +1 -1
- package/dist/rest-api.d.cts +3 -3
- package/dist/rest-api.d.mts +3 -3
- package/dist/rest-api.mjs.map +1 -1
- package/dist/site.cjs.map +1 -1
- package/dist/site.d.cts +1 -1
- package/dist/site.d.mts +1 -1
- package/dist/site.mjs.map +1 -1
- package/package.json +31 -31
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 `deploy.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\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 /^f[cd][0-9a-f]{2}:/.test(ip) || /^fe[89ab][0-9a-f]:/.test(ip);\n}\n"],"mappings":";;;;AA4KA,MAAM,oBAAoB;AAE1B,IAAa,aAAb,MAKA;CA8BmB;CA7BlB;;;;;;;;;;;;CAYA;CACA;;;;;CAMA;CAQA,YACC,IACA,QACC;EADgB,KAAA,SAAA;EAEjB,MAAM,YAAY,YAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,WAAW,OAAO,YAAY;EAInC,MAAM,WAAW,GAAG,UAAU;EAC9B,KAAK,OAAO;GACX;GACA,QAAQ,gBAAgB,QAAQ;GAChC,KAAK,WAAW,WAAW,KAAK;GAChC,gBAAgB,WAAW,WAAW,gBAAgB;GACtD,cAAc,WAAW,WAAW,cAAc;EACnD;EAGA,KAAK,UAAU;GACd,aAAa,WAAW,SAAS;GACjC,WAAW,YAAY,KAAK,OAAO,QAAQ,SAAS;EACrD;CACD;;;;;;;;;;;;;;;CAgBA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK,KAAK;GACd,UAAU,CAAC,KAAK,KAAK,MAAM;EAC5B,GAC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,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 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\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 /^f[cd][0-9a-f]{2}:/.test(ip) || /^fe[89ab][0-9a-f]:/.test(ip);\n}\n"],"mappings":";;;;AA4KA,MAAM,oBAAoB;AAE1B,IAAa,aAAb,MAKA;CA8BmB;CA7BlB;;;;;;;;;;;;CAYA;CACA;;;;;CAMA;CAQA,YACC,IACA,QACC;EADgB,KAAA,SAAA;EAEjB,MAAM,YAAY,YAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,WAAW,OAAO,YAAY;EAInC,MAAM,WAAW,GAAG,UAAU;EAC9B,KAAK,OAAO;GACX;GACA,QAAQ,gBAAgB,QAAQ;GAChC,KAAK,WAAW,WAAW,KAAK;GAChC,gBAAgB,WAAW,WAAW,gBAAgB;GACtD,cAAc,WAAW,WAAW,cAAc;EACnD;EAGA,KAAK,UAAU;GACd,aAAa,WAAW,SAAS;GACjC,WAAW,YAAY,KAAK,OAAO,QAAQ,SAAS;EACrD;CACD;;;;;;;;;;;;;;;CAgBA,UAAy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C/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,6 +1,6 @@
|
|
|
1
1
|
import { s as publishConstructEvents } from "../Construct-BQALFCh2.cjs";
|
|
2
|
-
import { A as getSecurityScheme, C as Authorizer, D as OAuthFlows, E as OAuthFlow, O as SecurityScheme, S as MappedAudit, T as BuiltInSecuritySchemeId, _ as RlsBypass, a as EndpointContext, b as RlsContextExtractor, c as EndpointSchemas, d as ResponseBuilder, g as RLS_BYPASS, h as SessionAuth, i as Endpoint, j as isBuiltInSecurityScheme, k as createAuthorizer, l as EndpointSurface, m as NoAuthenticator, n as ConvertRouteParams, o as EndpointHandler, r as CookieFn, s as EndpointOutput, u as HeaderFn, v as RlsConfig, w as BUILT_IN_SECURITY_SCHEMES, x as ActorExtractor, y as RlsContext } from "../Endpoint-
|
|
3
|
-
import { n as EndpointBuilder, t as EndpointFactory } from "../EndpointFactory-
|
|
2
|
+
import { A as getSecurityScheme, C as Authorizer, D as OAuthFlows, E as OAuthFlow, O as SecurityScheme, S as MappedAudit, T as BuiltInSecuritySchemeId, _ as RlsBypass, a as EndpointContext, b as RlsContextExtractor, c as EndpointSchemas, d as ResponseBuilder, g as RLS_BYPASS, h as SessionAuth, i as Endpoint, j as isBuiltInSecurityScheme, k as createAuthorizer, l as EndpointSurface, m as NoAuthenticator, n as ConvertRouteParams, o as EndpointHandler, r as CookieFn, s as EndpointOutput, u as HeaderFn, v as RlsConfig, w as BUILT_IN_SECURITY_SCHEMES, x as ActorExtractor, y as RlsContext } from "../Endpoint-aCvBMPoH.cjs";
|
|
3
|
+
import { n as EndpointBuilder, t as EndpointFactory } from "../EndpointFactory-I7s1co3Y.cjs";
|
|
4
4
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
5
5
|
import { Context } from "hono";
|
|
6
6
|
//#region src/endpoints/lazyAccessors.d.ts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { s as publishConstructEvents } from "../Construct-QXnl3VqT.mjs";
|
|
2
|
-
import { A as getSecurityScheme, C as Authorizer, D as OAuthFlows, E as OAuthFlow, O as SecurityScheme, S as MappedAudit, T as BuiltInSecuritySchemeId, _ as RlsBypass, a as EndpointContext, b as RlsContextExtractor, c as EndpointSchemas, d as ResponseBuilder, g as RLS_BYPASS, h as SessionAuth, i as Endpoint, j as isBuiltInSecurityScheme, k as createAuthorizer, l as EndpointSurface, m as NoAuthenticator, n as ConvertRouteParams, o as EndpointHandler, r as CookieFn, s as EndpointOutput, u as HeaderFn, v as RlsConfig, w as BUILT_IN_SECURITY_SCHEMES, x as ActorExtractor, y as RlsContext } from "../Endpoint-
|
|
3
|
-
import { n as EndpointBuilder, t as EndpointFactory } from "../EndpointFactory-
|
|
2
|
+
import { A as getSecurityScheme, C as Authorizer, D as OAuthFlows, E as OAuthFlow, O as SecurityScheme, S as MappedAudit, T as BuiltInSecuritySchemeId, _ as RlsBypass, a as EndpointContext, b as RlsContextExtractor, c as EndpointSchemas, d as ResponseBuilder, g as RLS_BYPASS, h as SessionAuth, i as Endpoint, j as isBuiltInSecurityScheme, k as createAuthorizer, l as EndpointSurface, m as NoAuthenticator, n as ConvertRouteParams, o as EndpointHandler, r as CookieFn, s as EndpointOutput, u as HeaderFn, v as RlsConfig, w as BUILT_IN_SECURITY_SCHEMES, x as ActorExtractor, y as RlsContext } from "../Endpoint-Du-NwPX2.mjs";
|
|
3
|
+
import { n as EndpointBuilder, t as EndpointFactory } from "../EndpointFactory-DMYdJCOj.mjs";
|
|
4
4
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
5
5
|
import { Context } from "hono";
|
|
6
6
|
//#region src/endpoints/lazyAccessors.d.ts
|
package/dist/rest-api.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rest-api.cjs","names":["canonicalId","provideKey","DEFAULT_LOGGER","envParserFor","EndpointFactory","getSecurityScheme","edgeTo"],"sources":["../src/rest-api.ts"],"sourcesContent":["/**\n * `RestApi` — the application's own HTTP surface, declared.\n *\n * Everything an app serves already existed; what did not exist was a *node* for\n * it. Without one, three things that are properties of the graph had to be\n * written down somewhere else: which origins the API accepts, which origins the\n * auth server trusts, and which URL a frontend is built against. All three were\n * being derived by walking the workspace config for ports — a second mechanism,\n * running beside the graph and answering the same question worse, since it can\n * only ever describe what this repo happens to run.\n *\n * With the surface declared, all three become one edge read backwards: a\n * consumer depends on the API, and *that* is the CORS entry, the trusted origin,\n * and the build-time URL. Nothing enumerates its own callers.\n *\n * ```ts\n * export const api = new RestApi('Api', {\n * authorizers: ['session'],\n * defaultAuthorizer: 'session',\n * });\n * ```\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n\tprovideKey,\n} from '@geekmidas/manifest';\nimport type { Telescope } from '@geekmidas/telescope';\nimport {\n\ttype Authenticator,\n\ttype Declarable,\n\tedgeTo,\n} from './construct-interface';\n\nexport type { Authenticator } from './construct-interface';\n\nimport {\n\ttype BuiltInSecuritySchemeId,\n\tgetSecurityScheme,\n} from './endpoints/Authorizer';\nimport { EndpointFactory } from './endpoints/EndpointFactory';\nimport { envParserFor } from './endpoints/surfaceEnv';\nimport type { Telemetry } from './telemetry';\n\n/** The factory a surface builds its endpoints from. */\ntype Endpoints = EndpointFactory<[], '', Logger>;\n\nexport interface RestApiConfig<\n\t// `readonly []` rather than `readonly string[]`: a surface that declares no\n\t// authorizers of its own should narrow `defaultAuthorizer` to the built-ins\n\t// and `'none'`, not widen it back to any string.\n\tTAuthorizers extends readonly string[] = readonly [],\n> {\n\t/**\n\t * The app that serves this surface, relative to the workspace root —\n\t * `'apps/api'`, or `'.'` in a single-app project.\n\t *\n\t * Required. It was inferred from the id (`apps/<kebab-id>`, or the root\n\t * when no such directory existed), which meant a surface's home was\n\t * whatever happened to be on disk. It is where the app's `package.json`\n\t * and base `tsconfig.json` are, and which build serves this surface. It\n\t * does not change discovery: constructs still load from the workspace's\n\t * `constructs` glob.\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 `deploy.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 * CORS tunables. The *origins* are never here — they are read off the\n\t * constructs that declared an edge to this surface, which is the whole point\n\t * of declaring one. These are the parts a graph cannot answer.\n\t */\n\tcors?: {\n\t\tmaxAge?: number;\n\t\tcredentials?: boolean;\n\t\tallowHeaders?: readonly string[];\n\t\texposeHeaders?: readonly string[];\n\t};\n\t/**\n\t * The authorizer names this surface exposes. Names only — what verifies a\n\t * request legitimately differs between local and deployed, so the mechanism\n\t * belongs to the target and never to portable code.\n\t */\n\tauthorizers?: TAuthorizers;\n\t/**\n\t * The authorizer applied to an endpoint that names none.\n\t *\n\t * Required, and `'none'` is a valid answer that has to be typed out. The\n\t * alternative is an API that ships open because a field was left off, which\n\t * is the one default worth refusing to have.\n\t *\n\t * It was called `default`, which said what it was to the type and nothing\n\t * to the reader: next to `authorizers: ['iam']`, a bare `default: 'none'`\n\t * could be defaulting the runtime or the target. The manifest has always\n\t * called it `defaultAuthorizer` and the factory `defaultAuthorizerName`;\n\t * this is the same fact under the same name.\n\t *\n\t * Typed from `authorizers`, so it can only name one this surface exposes —\n\t * plus a built-in scheme, and `'none'`. It was a bare `string`, which let\n\t * `defaultAuthorizer: 'jwtt'` compile and every endpoint on the surface\n\t * default to an authorizer that does not exist.\n\t */\n\tdefaultAuthorizer: TAuthorizers[number] | BuiltInSecuritySchemeId | 'none';\n\t/**\n\t * The logger every endpoint on this surface runs with.\n\t *\n\t * The actual logger, not a path to one. It used to be named in config as\n\t * `logger: './config/logger'`, because the build wrote an import into each\n\t * generated handler and a generator can print a specifier but not an object.\n\t * Endpoints built from the surface carry it, so there is nothing to print\n\t * and nothing to keep in step with a moved file.\n\t */\n\tlogger?: Logger;\n\t/**\n\t * The environment parser every endpoint on this surface runs with.\n\t *\n\t * Same reason as `logger`, and the same field it replaces —\n\t * `envParser: './config/env#envParser'`, a module path with an export name\n\t * appended, parsed by us, checked by nothing.\n\t */\n\tenvParser?: EnvironmentParser<{}>;\n\t/**\n\t * The Telescope instance this surface's entry mounts.\n\t *\n\t * The actual instance, for the reason `logger` is: it used to be named as\n\t * `telescope: './config/telescope#telescope'`, a module path the build\n\t * printed an import for. The entry already imports the surface.\n\t */\n\ttelescope?: Telescope;\n\t/**\n\t * What this surface's process emits — the `Telemetry` construct, passed\n\t * like the logger: a fact about the process, not a grant to a route.\n\t *\n\t * An edge to the node, so the deploy hands this process the `OTEL_*` keys\n\t * its stage resolves, and the build fails without the OpenTelemetry\n\t * packages. Where the telemetry goes is never here: it is the deploy's,\n\t * per stage.\n\t */\n\ttelemetry?: Telemetry;\n}\n\n/**\n * What is *not* here, and why.\n *\n * `dependsOn`, `database`, `auditor` and `.event(topic, …)` all inject a capability\n * into a handler. Putting one on the surface hands it to every route the\n * surface serves — a health check gets the database because a report needed it\n * — which is the thing least privilege forbids and the reason `.calls()` is not\n * spelled `dependsOn`. They belong to the endpoint, or to a branch —\n * `api.database(db)` — for a group of endpoints that genuinely share them. A\n * branch is a new factory; the surface config stays free of grants.\n *\n * `auth` is not here either: `.auth(construct)` already declares it, and a\n * second way to say the same thing is the duplication this whole model removes.\n *\n * What is left is what the *process* is rather than what a route may reach.\n */\n\nexport class RestApi<\n\tTName extends string = string,\n\tconst TAuthorizers extends readonly string[] = readonly [],\n> implements Declarable<TName>\n{\n\treadonly id: TName;\n\n\t/**\n\t * Declared once and read by both `declare()` and anything that consumes this\n\t * surface, so what the target publishes and what a consumer reads cannot\n\t * drift.\n\t */\n\treadonly keys: {\n\t\turl: string;\n\t\ttrustedOrigins: string;\n\t\tcookieDomain: string;\n\t};\n\n\t/**\n\t * The logger every endpoint on this surface runs with.\n\t *\n\t * Always defined — the surface's own if it was given one, the console\n\t * logger otherwise — so nothing downstream has to decide what to do about a\n\t * missing one. The generated entry reads it from here.\n\t */\n\treadonly logger: Logger;\n\n\t/**\n\t * The environment parser every endpoint on this surface runs with.\n\t *\n\t * Always defined, and normally the default: `process.env` merged with the\n\t * credentials `gkm dev`/`gkm exec` injected. That is what every\n\t * application's own `config/env.ts` was — boilerplate identical in every\n\t * project, and mandatory, which is a poor combination.\n\t */\n\treadonly envParser: EnvironmentParser<{}>;\n\n\t/** The Telescope instance, when this surface was given one. */\n\treadonly telescope?: Telescope;\n\n\t/** What this surface's process emits, when it was given a `Telemetry`. */\n\treadonly telemetry?: Telemetry;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: RestApiConfig<TAuthorizers>,\n\t\t/** Internal: how `.calls()` carries edges into the copy it returns. */\n\t\tprivate readonly dependencies: readonly Dependency[] = [],\n\t\t/** Internal: how `.auth()` carries the authenticator into its copy. */\n\t\tprivate readonly authenticator?: Authenticator,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\n\t\tthis.keys = {\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\tthis.logger = config.logger ?? DEFAULT_LOGGER;\n\t\tthis.telescope = config.telescope;\n\t\tthis.telemetry = config.telemetry;\n\t\tthis.envParser = envParserFor(\n\t\t\tconfig.envParser\n\t\t\t\t? { id: canonical, envParser: config.envParser }\n\t\t\t\t: undefined,\n\t\t);\n\n\t\tthis.#endpoints = new EndpointFactory({\n\t\t\tdefaultLogger: this.logger,\n\t\t\t...(config.authorizers\n\t\t\t\t? {\n\t\t\t\t\t\t// With the scheme a built-in name stands for, as the factory's own\n\t\t\t\t\t\t// `.authorizers()` resolves it. Bare names reached the OpenAPI\n\t\t\t\t\t\t// document with no scheme, so a guarded endpoint read as public.\n\t\t\t\t\t\tavailableAuthorizers: config.authorizers.map((name) => {\n\t\t\t\t\t\t\tconst securityScheme = getSecurityScheme(name);\n\t\t\t\t\t\t\treturn securityScheme ? { name, securityScheme } : { name };\n\t\t\t\t\t\t}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t// `'none'` reaches the factory as no default at all, which is what\n\t\t\t// public means to an endpoint that names no authorizer.\n\t\t\t...(config.defaultAuthorizer && config.defaultAuthorizer !== 'none'\n\t\t\t\t? { defaultAuthorizerName: config.defaultAuthorizer }\n\t\t\t\t: {}),\n\t\t\tsurface: {\n\t\t\t\tid: this.id,\n\t\t\t\tenvParser: this.envParser,\n\t\t\t\t...(authenticator ? { auth: authenticator } : {}),\n\t\t\t},\n\t\t});\n\n\t\tconst endpoints = this.#endpoints;\n\t\tthis.get = endpoints.get.bind(endpoints);\n\t\tthis.post = endpoints.post.bind(endpoints);\n\t\tthis.put = endpoints.put.bind(endpoints);\n\t\tthis.patch = endpoints.patch.bind(endpoints);\n\t\tthis.delete = endpoints.delete.bind(endpoints);\n\t\tthis.options = endpoints.options.bind(endpoints);\n\t\tthis.database = endpoints.database.bind(endpoints);\n\t\tthis.session = endpoints.session.bind(endpoints);\n\t\tthis.auditor = endpoints.auditor.bind(endpoints);\n\t\tthis.actor = endpoints.actor.bind(endpoints);\n\t\tthis.authorizer = endpoints.authorizer.bind(endpoints);\n\t\tthis.authorize = endpoints.authorize.bind(endpoints);\n\t\tthis.rls = endpoints.rls.bind(endpoints);\n\t\tthis.route = endpoints.route.bind(endpoints);\n\t}\n\n\t/**\n\t * This surface's endpoint factory, which every method below starts from.\n\t *\n\t * Private: a surface *is* where endpoints are built, so there is no second\n\t * object to reach through first. `api.database(db)` said the same\n\t * thing as `api.database(db)` with one more word to learn.\n\t */\n\treadonly #endpoints: Endpoints;\n\n\t/** `api.get('/users')` — one route on this surface. */\n\treadonly get: Endpoints['get'];\n\treadonly post: Endpoints['post'];\n\treadonly put: Endpoints['put'];\n\treadonly patch: Endpoints['patch'];\n\treadonly delete: Endpoints['delete'];\n\treadonly options: Endpoints['options'];\n\n\t/**\n\t * A branch for a *group* of endpoints that shares what a single route would\n\t * otherwise repeat — a database, an auditor, a publisher, a session:\n\t *\n\t * ```ts\n\t * export const router = api.database(database);\n\t * export const createUser = router.post('/users').handle(({ db }) => …);\n\t * ```\n\t *\n\t * Each returns a new factory and leaves the surface as it was. That is the\n\t * whole difference from putting the same thing in the surface's config: a\n\t * group opts in, where the surface would grant it to every route it serves —\n\t * a health check handed the database because a profile endpoint needed it.\n\t *\n\t * `dependsOn` is deliberately not here. It is per endpoint, and on the\n\t * surface it would read as the API depending on something, which is what\n\t * `.calls()` and `.auth()` say instead.\n\t */\n\treadonly database: Endpoints['database'];\n\treadonly session: Endpoints['session'];\n\treadonly auditor: Endpoints['auditor'];\n\treadonly actor: Endpoints['actor'];\n\treadonly authorizer: Endpoints['authorizer'];\n\treadonly authorize: Endpoints['authorize'];\n\treadonly rls: Endpoints['rls'];\n\treadonly route: Endpoints['route'];\n\n\t/**\n\t * What authenticates this surface.\n\t *\n\t * An edge like `.calls()` — the auth server learns this origin, and the two\n\t * share a cookie domain — but a named one, because *who authenticates me* is\n\t * a different fact from *who I happen to call*, and only one of them decides\n\t * what a request is allowed to be. A surface with two of the first is a\n\t * mistake; two of the second is Tuesday.\n\t *\n\t * It declares the id, and keeps the construct: a session callback reads from\n\t * it as `auth` — `session(async ({ auth }) => auth.getSession())` — which\n\t * calls the construct's `verify(headers)`. That is the one thing every\n\t * provider shares, whether the server is mounted in this process, deployed\n\t * beside it, or an OIDC issuer somebody else runs.\n\t */\n\tauth(construct: Authenticator): RestApi<TName, TAuthorizers> {\n\t\treturn new RestApi<TName, TAuthorizers>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, edgeTo(construct)],\n\t\t\tconstruct,\n\t\t);\n\t}\n\n\t/**\n\t * Other surfaces this one calls.\n\t *\n\t * **Not `.dependsOn()`, and the difference matters.** An endpoint's\n\t * `.dependsOn()` injects a client into that handler and grants it exactly\n\t * what it named. This grants nothing and injects nothing: it records that\n\t * this API calls another surface, which is what puts this API's origin on\n\t * that surface's trusted-origin list.\n\t *\n\t * Spelling it `dependsOn` would invite the thing least privilege forbids —\n\t * every route on the surface receiving whatever the surface named.\n\t *\n\t * Immutable, like every other builder here.\n\t */\n\tcalls(constructs: readonly Declarable[]): RestApi<TName, TAuthorizers> {\n\t\treturn new RestApi<TName, TAuthorizers>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, ...constructs.map(edgeTo)],\n\t\t\tthis.authenticator,\n\t\t);\n\t}\n\n\t/**\n\t * One surface node, with its endpoints left to the build.\n\t *\n\t * The three provided keys are one fact about this surface and two about its\n\t * callers. Declaring the caller-derived pair here rather than having the\n\t * target invent them is what makes the contract checkable: a target that\n\t * resolves no origins is caught against this list instead of being noticed\n\t * when a browser is refused in production.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\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.telescope ? { telescope: true } : {}),\n\t\t\t\t...(this.config.cors ? { cors: this.config.cors } : {}),\n\t\t\t\t...(this.authenticator ? { auth: this.authenticator.id } : {}),\n\t\t\t\t// Filled by the build, which already generates one handler per\n\t\t\t\t// endpoint and knows the path it wrote it to. A surface that\n\t\t\t\t// enumerates its own routes statically — an auth server's single\n\t\t\t\t// wildcard — puts them here instead.\n\t\t\t\tendpoints: [],\n\t\t\t\t...(this.dependencies.length ? { calls: this.dependencies } : {}),\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\t...(this.config.authorizers?.length\n\t\t\t\t\t? { authorizers: this.config.authorizers }\n\t\t\t\t\t: {}),\n\t\t\t\tdefaultAuthorizer: this.config.defaultAuthorizer,\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},\n\t\t];\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwKA,IAAa,UAAb,MAAa,QAIb;CAyCmB;CAEA;CAEA;CA5ClB;;;;;;CAOA;;;;;;;;CAaA;;;;;;;;;CAUA;;CAGA;;CAGA;CAEA,YACC,IACA,QAEA,eAAuD,CAAC,GAExD,eACC;EALgB,KAAA,SAAA;EAEA,KAAA,eAAA;EAEA,KAAA,gBAAA;EAEjB,MAAM,aAAA,GAAYA,oBAAAA,YAAAA,CAAY,EAAY;EAE1C,KAAK,KAAK;EAEV,KAAK,OAAO;GACX,MAAA,GAAKC,oBAAAA,WAAAA,CAAW,WAAW,KAAK;GAChC,iBAAA,GAAgBA,oBAAAA,WAAAA,CAAW,WAAW,gBAAgB;GACtD,eAAA,GAAcA,oBAAAA,WAAAA,CAAW,WAAW,cAAc;EACnD;EAEA,KAAK,SAAS,OAAO,UAAUC,0BAAAA;EAC/B,KAAK,YAAY,OAAO;EACxB,KAAK,YAAY,OAAO;EACxB,KAAK,Y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;;;;;;;;;;CAoBA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;;;;;;;;;;;;;;;;CAiBA,KAAK,WAAwD;EAC5D,OAAO,IAAI,QACV,KAAK,IACL,KAAK,QACL,CAAC,GAAG,KAAK,cAAcC,4BAAAA,OAAO,SAAS,CAAC,GACxC,SACD;CACD;;;;;;;;;;;;;;;CAgBA,MAAM,YAAiE;EACtE,OAAO,IAAI,QACV,KAAK,IACL,KAAK,QACL,CAAC,GAAG,KAAK,cAAc,GAAG,WAAW,IAAIA,4BAAAA,MAAM,CAAC,GAChD,KAAK,aACN;CACD;;;;;;;;;;CAWA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,MAAM,KAAK,OAAO;GAClB,GAAI,KAAK,OAAO,YAAY,EAAE,WAAW,KAAK,OAAO,UAAU,IAAI,CAAC;GACpE,GAAI,KAAK,OAAO,YAAY,EAAE,WAAW,KAAK,IAAI,CAAC;GACnD,GAAI,KAAK,OAAO,OAAO,EAAE,MAAM,KAAK,OAAO,KAAK,IAAI,CAAC;GACrD,GAAI,KAAK,gBAAgB,EAAE,MAAM,KAAK,cAAc,GAAG,IAAI,CAAC;GAK5D,WAAW,CAAC;GACZ,GAAI,KAAK,aAAa,SAAS,EAAE,OAAO,KAAK,aAAa,IAAI,CAAC;GAC/D,GAAI,KAAK,OAAO,YACb,EAAE,WAAW,KAAK,OAAO,UAAU,GAAG,IACtC,CAAC;GACJ,GAAI,KAAK,OAAO,aAAa,SAC1B,EAAE,aAAa,KAAK,OAAO,YAAY,IACvC,CAAC;GACJ,mBAAmB,KAAK,OAAO;GAC/B,UAAU;IACT,KAAK,KAAK;IACV,KAAK,KAAK;IACV,KAAK,KAAK;GACX;EACD,CACD;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"rest-api.cjs","names":["canonicalId","provideKey","DEFAULT_LOGGER","envParserFor","EndpointFactory","getSecurityScheme","edgeTo"],"sources":["../src/rest-api.ts"],"sourcesContent":["/**\n * `RestApi` — the application's own HTTP surface, declared.\n *\n * Everything an app serves already existed; what did not exist was a *node* for\n * it. Without one, three things that are properties of the graph had to be\n * written down somewhere else: which origins the API accepts, which origins the\n * auth server trusts, and which URL a frontend is built against. All three were\n * being derived by walking the workspace config for ports — a second mechanism,\n * running beside the graph and answering the same question worse, since it can\n * only ever describe what this repo happens to run.\n *\n * With the surface declared, all three become one edge read backwards: a\n * consumer depends on the API, and *that* is the CORS entry, the trusted origin,\n * and the build-time URL. Nothing enumerates its own callers.\n *\n * ```ts\n * export const api = new RestApi('Api', {\n * authorizers: ['session'],\n * defaultAuthorizer: 'session',\n * });\n * ```\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n\tprovideKey,\n} from '@geekmidas/manifest';\nimport type { Telescope } from '@geekmidas/telescope';\nimport {\n\ttype Authenticator,\n\ttype Declarable,\n\tedgeTo,\n} from './construct-interface';\n\nexport type { Authenticator } from './construct-interface';\n\nimport {\n\ttype BuiltInSecuritySchemeId,\n\tgetSecurityScheme,\n} from './endpoints/Authorizer';\nimport { EndpointFactory } from './endpoints/EndpointFactory';\nimport { envParserFor } from './endpoints/surfaceEnv';\nimport type { Telemetry } from './telemetry';\n\n/** The factory a surface builds its endpoints from. */\ntype Endpoints = EndpointFactory<[], '', Logger>;\n\nexport interface RestApiConfig<\n\t// `readonly []` rather than `readonly string[]`: a surface that declares no\n\t// authorizers of its own should narrow `defaultAuthorizer` to the built-ins\n\t// and `'none'`, not widen it back to any string.\n\tTAuthorizers extends readonly string[] = readonly [],\n> {\n\t/**\n\t * The app that serves this surface, relative to the workspace root —\n\t * `'apps/api'`, or `'.'` in a single-app project.\n\t *\n\t * Required. It was inferred from the id (`apps/<kebab-id>`, or the root\n\t * when no such directory existed), which meant a surface's home was\n\t * whatever happened to be on disk. It is where the app's `package.json`\n\t * and base `tsconfig.json` are, and which build serves this surface. It\n\t * does not change discovery: constructs still load from the workspace's\n\t * `constructs` glob.\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 * CORS tunables. The *origins* are never here — they are read off the\n\t * constructs that declared an edge to this surface, which is the whole point\n\t * of declaring one. These are the parts a graph cannot answer.\n\t */\n\tcors?: {\n\t\tmaxAge?: number;\n\t\tcredentials?: boolean;\n\t\tallowHeaders?: readonly string[];\n\t\texposeHeaders?: readonly string[];\n\t};\n\t/**\n\t * The authorizer names this surface exposes. Names only — what verifies a\n\t * request legitimately differs between local and deployed, so the mechanism\n\t * belongs to the target and never to portable code.\n\t */\n\tauthorizers?: TAuthorizers;\n\t/**\n\t * The authorizer applied to an endpoint that names none.\n\t *\n\t * Required, and `'none'` is a valid answer that has to be typed out. The\n\t * alternative is an API that ships open because a field was left off, which\n\t * is the one default worth refusing to have.\n\t *\n\t * It was called `default`, which said what it was to the type and nothing\n\t * to the reader: next to `authorizers: ['iam']`, a bare `default: 'none'`\n\t * could be defaulting the runtime or the target. The manifest has always\n\t * called it `defaultAuthorizer` and the factory `defaultAuthorizerName`;\n\t * this is the same fact under the same name.\n\t *\n\t * Typed from `authorizers`, so it can only name one this surface exposes —\n\t * plus a built-in scheme, and `'none'`. It was a bare `string`, which let\n\t * `defaultAuthorizer: 'jwtt'` compile and every endpoint on the surface\n\t * default to an authorizer that does not exist.\n\t */\n\tdefaultAuthorizer: TAuthorizers[number] | BuiltInSecuritySchemeId | 'none';\n\t/**\n\t * The logger every endpoint on this surface runs with.\n\t *\n\t * The actual logger, not a path to one. It used to be named in config as\n\t * `logger: './config/logger'`, because the build wrote an import into each\n\t * generated handler and a generator can print a specifier but not an object.\n\t * Endpoints built from the surface carry it, so there is nothing to print\n\t * and nothing to keep in step with a moved file.\n\t */\n\tlogger?: Logger;\n\t/**\n\t * The environment parser every endpoint on this surface runs with.\n\t *\n\t * Same reason as `logger`, and the same field it replaces —\n\t * `envParser: './config/env#envParser'`, a module path with an export name\n\t * appended, parsed by us, checked by nothing.\n\t */\n\tenvParser?: EnvironmentParser<{}>;\n\t/**\n\t * The Telescope instance this surface's entry mounts.\n\t *\n\t * The actual instance, for the reason `logger` is: it used to be named as\n\t * `telescope: './config/telescope#telescope'`, a module path the build\n\t * printed an import for. The entry already imports the surface.\n\t */\n\ttelescope?: Telescope;\n\t/**\n\t * What this surface's process emits — the `Telemetry` construct, passed\n\t * like the logger: a fact about the process, not a grant to a route.\n\t *\n\t * An edge to the node, so the deploy hands this process the `OTEL_*` keys\n\t * its stage resolves, and the build fails without the OpenTelemetry\n\t * packages. Where the telemetry goes is never here: it is the deploy's,\n\t * per stage.\n\t */\n\ttelemetry?: Telemetry;\n}\n\n/**\n * What is *not* here, and why.\n *\n * `dependsOn`, `database`, `auditor` and `.event(topic, …)` all inject a capability\n * into a handler. Putting one on the surface hands it to every route the\n * surface serves — a health check gets the database because a report needed it\n * — which is the thing least privilege forbids and the reason `.calls()` is not\n * spelled `dependsOn`. They belong to the endpoint, or to a branch —\n * `api.database(db)` — for a group of endpoints that genuinely share them. A\n * branch is a new factory; the surface config stays free of grants.\n *\n * `auth` is not here either: `.auth(construct)` already declares it, and a\n * second way to say the same thing is the duplication this whole model removes.\n *\n * What is left is what the *process* is rather than what a route may reach.\n */\n\nexport class RestApi<\n\tTName extends string = string,\n\tconst TAuthorizers extends readonly string[] = readonly [],\n> implements Declarable<TName>\n{\n\treadonly id: TName;\n\n\t/**\n\t * Declared once and read by both `declare()` and anything that consumes this\n\t * surface, so what the target publishes and what a consumer reads cannot\n\t * drift.\n\t */\n\treadonly keys: {\n\t\turl: string;\n\t\ttrustedOrigins: string;\n\t\tcookieDomain: string;\n\t};\n\n\t/**\n\t * The logger every endpoint on this surface runs with.\n\t *\n\t * Always defined — the surface's own if it was given one, the console\n\t * logger otherwise — so nothing downstream has to decide what to do about a\n\t * missing one. The generated entry reads it from here.\n\t */\n\treadonly logger: Logger;\n\n\t/**\n\t * The environment parser every endpoint on this surface runs with.\n\t *\n\t * Always defined, and normally the default: `process.env` merged with the\n\t * credentials `gkm dev`/`gkm exec` injected. That is what every\n\t * application's own `config/env.ts` was — boilerplate identical in every\n\t * project, and mandatory, which is a poor combination.\n\t */\n\treadonly envParser: EnvironmentParser<{}>;\n\n\t/** The Telescope instance, when this surface was given one. */\n\treadonly telescope?: Telescope;\n\n\t/** What this surface's process emits, when it was given a `Telemetry`. */\n\treadonly telemetry?: Telemetry;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: RestApiConfig<TAuthorizers>,\n\t\t/** Internal: how `.calls()` carries edges into the copy it returns. */\n\t\tprivate readonly dependencies: readonly Dependency[] = [],\n\t\t/** Internal: how `.auth()` carries the authenticator into its copy. */\n\t\tprivate readonly authenticator?: Authenticator,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\n\t\tthis.keys = {\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\tthis.logger = config.logger ?? DEFAULT_LOGGER;\n\t\tthis.telescope = config.telescope;\n\t\tthis.telemetry = config.telemetry;\n\t\tthis.envParser = envParserFor(\n\t\t\tconfig.envParser\n\t\t\t\t? { id: canonical, envParser: config.envParser }\n\t\t\t\t: undefined,\n\t\t);\n\n\t\tthis.#endpoints = new EndpointFactory({\n\t\t\tdefaultLogger: this.logger,\n\t\t\t...(config.authorizers\n\t\t\t\t? {\n\t\t\t\t\t\t// With the scheme a built-in name stands for, as the factory's own\n\t\t\t\t\t\t// `.authorizers()` resolves it. Bare names reached the OpenAPI\n\t\t\t\t\t\t// document with no scheme, so a guarded endpoint read as public.\n\t\t\t\t\t\tavailableAuthorizers: config.authorizers.map((name) => {\n\t\t\t\t\t\t\tconst securityScheme = getSecurityScheme(name);\n\t\t\t\t\t\t\treturn securityScheme ? { name, securityScheme } : { name };\n\t\t\t\t\t\t}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t// `'none'` reaches the factory as no default at all, which is what\n\t\t\t// public means to an endpoint that names no authorizer.\n\t\t\t...(config.defaultAuthorizer && config.defaultAuthorizer !== 'none'\n\t\t\t\t? { defaultAuthorizerName: config.defaultAuthorizer }\n\t\t\t\t: {}),\n\t\t\tsurface: {\n\t\t\t\tid: this.id,\n\t\t\t\tenvParser: this.envParser,\n\t\t\t\t...(authenticator ? { auth: authenticator } : {}),\n\t\t\t},\n\t\t});\n\n\t\tconst endpoints = this.#endpoints;\n\t\tthis.get = endpoints.get.bind(endpoints);\n\t\tthis.post = endpoints.post.bind(endpoints);\n\t\tthis.put = endpoints.put.bind(endpoints);\n\t\tthis.patch = endpoints.patch.bind(endpoints);\n\t\tthis.delete = endpoints.delete.bind(endpoints);\n\t\tthis.options = endpoints.options.bind(endpoints);\n\t\tthis.database = endpoints.database.bind(endpoints);\n\t\tthis.session = endpoints.session.bind(endpoints);\n\t\tthis.auditor = endpoints.auditor.bind(endpoints);\n\t\tthis.actor = endpoints.actor.bind(endpoints);\n\t\tthis.authorizer = endpoints.authorizer.bind(endpoints);\n\t\tthis.authorize = endpoints.authorize.bind(endpoints);\n\t\tthis.rls = endpoints.rls.bind(endpoints);\n\t\tthis.route = endpoints.route.bind(endpoints);\n\t}\n\n\t/**\n\t * This surface's endpoint factory, which every method below starts from.\n\t *\n\t * Private: a surface *is* where endpoints are built, so there is no second\n\t * object to reach through first. `api.database(db)` said the same\n\t * thing as `api.database(db)` with one more word to learn.\n\t */\n\treadonly #endpoints: Endpoints;\n\n\t/** `api.get('/users')` — one route on this surface. */\n\treadonly get: Endpoints['get'];\n\treadonly post: Endpoints['post'];\n\treadonly put: Endpoints['put'];\n\treadonly patch: Endpoints['patch'];\n\treadonly delete: Endpoints['delete'];\n\treadonly options: Endpoints['options'];\n\n\t/**\n\t * A branch for a *group* of endpoints that shares what a single route would\n\t * otherwise repeat — a database, an auditor, a publisher, a session:\n\t *\n\t * ```ts\n\t * export const router = api.database(database);\n\t * export const createUser = router.post('/users').handle(({ db }) => …);\n\t * ```\n\t *\n\t * Each returns a new factory and leaves the surface as it was. That is the\n\t * whole difference from putting the same thing in the surface's config: a\n\t * group opts in, where the surface would grant it to every route it serves —\n\t * a health check handed the database because a profile endpoint needed it.\n\t *\n\t * `dependsOn` is deliberately not here. It is per endpoint, and on the\n\t * surface it would read as the API depending on something, which is what\n\t * `.calls()` and `.auth()` say instead.\n\t */\n\treadonly database: Endpoints['database'];\n\treadonly session: Endpoints['session'];\n\treadonly auditor: Endpoints['auditor'];\n\treadonly actor: Endpoints['actor'];\n\treadonly authorizer: Endpoints['authorizer'];\n\treadonly authorize: Endpoints['authorize'];\n\treadonly rls: Endpoints['rls'];\n\treadonly route: Endpoints['route'];\n\n\t/**\n\t * What authenticates this surface.\n\t *\n\t * An edge like `.calls()` — the auth server learns this origin, and the two\n\t * share a cookie domain — but a named one, because *who authenticates me* is\n\t * a different fact from *who I happen to call*, and only one of them decides\n\t * what a request is allowed to be. A surface with two of the first is a\n\t * mistake; two of the second is Tuesday.\n\t *\n\t * It declares the id, and keeps the construct: a session callback reads from\n\t * it as `auth` — `session(async ({ auth }) => auth.getSession())` — which\n\t * calls the construct's `verify(headers)`. That is the one thing every\n\t * provider shares, whether the server is mounted in this process, deployed\n\t * beside it, or an OIDC issuer somebody else runs.\n\t */\n\tauth(construct: Authenticator): RestApi<TName, TAuthorizers> {\n\t\treturn new RestApi<TName, TAuthorizers>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, edgeTo(construct)],\n\t\t\tconstruct,\n\t\t);\n\t}\n\n\t/**\n\t * Other surfaces this one calls.\n\t *\n\t * **Not `.dependsOn()`, and the difference matters.** An endpoint's\n\t * `.dependsOn()` injects a client into that handler and grants it exactly\n\t * what it named. This grants nothing and injects nothing: it records that\n\t * this API calls another surface, which is what puts this API's origin on\n\t * that surface's trusted-origin list.\n\t *\n\t * Spelling it `dependsOn` would invite the thing least privilege forbids —\n\t * every route on the surface receiving whatever the surface named.\n\t *\n\t * Immutable, like every other builder here.\n\t */\n\tcalls(constructs: readonly Declarable[]): RestApi<TName, TAuthorizers> {\n\t\treturn new RestApi<TName, TAuthorizers>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, ...constructs.map(edgeTo)],\n\t\t\tthis.authenticator,\n\t\t);\n\t}\n\n\t/**\n\t * One surface node, with its endpoints left to the build.\n\t *\n\t * The three provided keys are one fact about this surface and two about its\n\t * callers. Declaring the caller-derived pair here rather than having the\n\t * target invent them is what makes the contract checkable: a target that\n\t * resolves no origins is caught against this list instead of being noticed\n\t * when a browser is refused in production.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\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.telescope ? { telescope: true } : {}),\n\t\t\t\t...(this.config.cors ? { cors: this.config.cors } : {}),\n\t\t\t\t...(this.authenticator ? { auth: this.authenticator.id } : {}),\n\t\t\t\t// Filled by the build, which already generates one handler per\n\t\t\t\t// endpoint and knows the path it wrote it to. A surface that\n\t\t\t\t// enumerates its own routes statically — an auth server's single\n\t\t\t\t// wildcard — puts them here instead.\n\t\t\t\tendpoints: [],\n\t\t\t\t...(this.dependencies.length ? { calls: this.dependencies } : {}),\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\t...(this.config.authorizers?.length\n\t\t\t\t\t? { authorizers: this.config.authorizers }\n\t\t\t\t\t: {}),\n\t\t\t\tdefaultAuthorizer: this.config.defaultAuthorizer,\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},\n\t\t];\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwKA,IAAa,UAAb,MAAa,QAIb;CAyCmB;CAEA;CAEA;CA5ClB;;;;;;CAOA;;;;;;;;CAaA;;;;;;;;;CAUA;;CAGA;;CAGA;CAEA,YACC,IACA,QAEA,eAAuD,CAAC,GAExD,eACC;EALgB,KAAA,SAAA;EAEA,KAAA,eAAA;EAEA,KAAA,gBAAA;EAEjB,MAAM,aAAA,GAAYA,oBAAAA,YAAAA,CAAY,EAAY;EAE1C,KAAK,KAAK;EAEV,KAAK,OAAO;GACX,MAAA,GAAKC,oBAAAA,WAAAA,CAAW,WAAW,KAAK;GAChC,iBAAA,GAAgBA,oBAAAA,WAAAA,CAAW,WAAW,gBAAgB;GACtD,eAAA,GAAcA,oBAAAA,WAAAA,CAAW,WAAW,cAAc;EACnD;EAEA,KAAK,SAAS,OAAO,UAAUC,0BAAAA;EAC/B,KAAK,YAAY,OAAO;EACxB,KAAK,YAAY,OAAO;EACxB,KAAK,YAAYC,mBAAAA,aAChB,OAAO,YACJ;GAAE,IAAI;GAAW,WAAW,OAAO;EAAU,IAC7C,KAAA,CACJ;EAEA,KAAK,aAAa,IAAIC,wBAAAA,gBAAgB;GACrC,eAAe,KAAK;GACpB,GAAI,OAAO,cACR,EAIA,sBAAsB,OAAO,YAAY,KAAK,SAAS;IACtD,MAAM,iBAAiBC,wBAAAA,kBAAkB,IAAI;IAC7C,OAAO,iBAAiB;KAAE;KAAM;IAAe,IAAI,EAAE,KAAK;GAC3D,CAAC,EACF,IACC,CAAC;GAGJ,GAAI,OAAO,qBAAqB,OAAO,sBAAsB,SAC1D,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AAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,MAAM,KAAK,OAAO;GAClB,GAAI,KAAK,OAAO,YAAY,EAAE,WAAW,KAAK,OAAO,UAAU,IAAI,CAAC;GACpE,GAAI,KAAK,OAAO,YAAY,EAAE,WAAW,KAAK,IAAI,CAAC;GACnD,GAAI,KAAK,OAAO,OAAO,EAAE,MAAM,KAAK,OAAO,KAAK,IAAI,CAAC;GACrD,GAAI,KAAK,gBAAgB,EAAE,MAAM,KAAK,cAAc,GAAG,IAAI,CAAC;GAK5D,WAAW,CAAC;GACZ,GAAI,KAAK,aAAa,SAAS,EAAE,OAAO,KAAK,aAAa,IAAI,CAAC;GAC/D,GAAI,KAAK,OAAO,YACb,EAAE,WAAW,KAAK,OAAO,UAAU,GAAG,IACtC,CAAC;GACJ,GAAI,KAAK,OAAO,aAAa,SAC1B,EAAE,aAAa,KAAK,OAAO,YAAY,IACvC,CAAC;GACJ,mBAAmB,KAAK,OAAO;GAC/B,UAAU;IACT,KAAK,KAAK;IACV,KAAK,KAAK;IACV,KAAK,KAAK;GACX;EACD,CACD;CACD;AACD"}
|
package/dist/rest-api.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { i as Declarable, t as Authenticator } from "./construct-interface-B1AfqRl4.cjs";
|
|
2
2
|
import { n as Telemetry } from "./telemetry-B48RLjyk.cjs";
|
|
3
|
-
import { T as BuiltInSecuritySchemeId } from "./Endpoint-
|
|
4
|
-
import { t as EndpointFactory } from "./EndpointFactory-
|
|
3
|
+
import { T as BuiltInSecuritySchemeId } from "./Endpoint-aCvBMPoH.cjs";
|
|
4
|
+
import { t as EndpointFactory } from "./EndpointFactory-I7s1co3Y.cjs";
|
|
5
5
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
6
6
|
import { Logger } from "@geekmidas/logger";
|
|
7
7
|
import { ConstructName, Declaration, Dependency } from "@geekmidas/manifest";
|
|
@@ -24,7 +24,7 @@ export interface RestApiConfig<TAuthorizers extends readonly string[] = readonly
|
|
|
24
24
|
path: string;
|
|
25
25
|
/**
|
|
26
26
|
* The label it answers on under a stage's domain — `api` for
|
|
27
|
-
* `api.myapp.com`, from `
|
|
27
|
+
* `api.myapp.com`, from `domains` — and under the project locally,
|
|
28
28
|
* `api.myapp.localhost`. Absent, its id kebab-cased.
|
|
29
29
|
*/
|
|
30
30
|
subdomain?: string;
|
package/dist/rest-api.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { i as Declarable, t as Authenticator } from "./construct-interface-DluK3_da.mjs";
|
|
2
2
|
import { n as Telemetry } from "./telemetry-DRtT1_0A.mjs";
|
|
3
|
-
import { T as BuiltInSecuritySchemeId } from "./Endpoint-
|
|
4
|
-
import { t as EndpointFactory } from "./EndpointFactory-
|
|
3
|
+
import { T as BuiltInSecuritySchemeId } from "./Endpoint-Du-NwPX2.mjs";
|
|
4
|
+
import { t as EndpointFactory } from "./EndpointFactory-DMYdJCOj.mjs";
|
|
5
5
|
import { ConstructName, Declaration, Dependency } from "@geekmidas/manifest";
|
|
6
6
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
7
7
|
import { Logger } from "@geekmidas/logger";
|
|
@@ -24,7 +24,7 @@ export interface RestApiConfig<TAuthorizers extends readonly string[] = readonly
|
|
|
24
24
|
path: string;
|
|
25
25
|
/**
|
|
26
26
|
* The label it answers on under a stage's domain — `api` for
|
|
27
|
-
* `api.myapp.com`, from `
|
|
27
|
+
* `api.myapp.com`, from `domains` — and under the project locally,
|
|
28
28
|
* `api.myapp.localhost`. Absent, its id kebab-cased.
|
|
29
29
|
*/
|
|
30
30
|
subdomain?: string;
|
package/dist/rest-api.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rest-api.mjs","names":[],"sources":["../src/rest-api.ts"],"sourcesContent":["/**\n * `RestApi` — the application's own HTTP surface, declared.\n *\n * Everything an app serves already existed; what did not exist was a *node* for\n * it. Without one, three things that are properties of the graph had to be\n * written down somewhere else: which origins the API accepts, which origins the\n * auth server trusts, and which URL a frontend is built against. All three were\n * being derived by walking the workspace config for ports — a second mechanism,\n * running beside the graph and answering the same question worse, since it can\n * only ever describe what this repo happens to run.\n *\n * With the surface declared, all three become one edge read backwards: a\n * consumer depends on the API, and *that* is the CORS entry, the trusted origin,\n * and the build-time URL. Nothing enumerates its own callers.\n *\n * ```ts\n * export const api = new RestApi('Api', {\n * authorizers: ['session'],\n * defaultAuthorizer: 'session',\n * });\n * ```\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n\tprovideKey,\n} from '@geekmidas/manifest';\nimport type { Telescope } from '@geekmidas/telescope';\nimport {\n\ttype Authenticator,\n\ttype Declarable,\n\tedgeTo,\n} from './construct-interface';\n\nexport type { Authenticator } from './construct-interface';\n\nimport {\n\ttype BuiltInSecuritySchemeId,\n\tgetSecurityScheme,\n} from './endpoints/Authorizer';\nimport { EndpointFactory } from './endpoints/EndpointFactory';\nimport { envParserFor } from './endpoints/surfaceEnv';\nimport type { Telemetry } from './telemetry';\n\n/** The factory a surface builds its endpoints from. */\ntype Endpoints = EndpointFactory<[], '', Logger>;\n\nexport interface RestApiConfig<\n\t// `readonly []` rather than `readonly string[]`: a surface that declares no\n\t// authorizers of its own should narrow `defaultAuthorizer` to the built-ins\n\t// and `'none'`, not widen it back to any string.\n\tTAuthorizers extends readonly string[] = readonly [],\n> {\n\t/**\n\t * The app that serves this surface, relative to the workspace root —\n\t * `'apps/api'`, or `'.'` in a single-app project.\n\t *\n\t * Required. It was inferred from the id (`apps/<kebab-id>`, or the root\n\t * when no such directory existed), which meant a surface's home was\n\t * whatever happened to be on disk. It is where the app's `package.json`\n\t * and base `tsconfig.json` are, and which build serves this surface. It\n\t * does not change discovery: constructs still load from the workspace's\n\t * `constructs` glob.\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 `deploy.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 * CORS tunables. The *origins* are never here — they are read off the\n\t * constructs that declared an edge to this surface, which is the whole point\n\t * of declaring one. These are the parts a graph cannot answer.\n\t */\n\tcors?: {\n\t\tmaxAge?: number;\n\t\tcredentials?: boolean;\n\t\tallowHeaders?: readonly string[];\n\t\texposeHeaders?: readonly string[];\n\t};\n\t/**\n\t * The authorizer names this surface exposes. Names only — what verifies a\n\t * request legitimately differs between local and deployed, so the mechanism\n\t * belongs to the target and never to portable code.\n\t */\n\tauthorizers?: TAuthorizers;\n\t/**\n\t * The authorizer applied to an endpoint that names none.\n\t *\n\t * Required, and `'none'` is a valid answer that has to be typed out. The\n\t * alternative is an API that ships open because a field was left off, which\n\t * is the one default worth refusing to have.\n\t *\n\t * It was called `default`, which said what it was to the type and nothing\n\t * to the reader: next to `authorizers: ['iam']`, a bare `default: 'none'`\n\t * could be defaulting the runtime or the target. The manifest has always\n\t * called it `defaultAuthorizer` and the factory `defaultAuthorizerName`;\n\t * this is the same fact under the same name.\n\t *\n\t * Typed from `authorizers`, so it can only name one this surface exposes —\n\t * plus a built-in scheme, and `'none'`. It was a bare `string`, which let\n\t * `defaultAuthorizer: 'jwtt'` compile and every endpoint on the surface\n\t * default to an authorizer that does not exist.\n\t */\n\tdefaultAuthorizer: TAuthorizers[number] | BuiltInSecuritySchemeId | 'none';\n\t/**\n\t * The logger every endpoint on this surface runs with.\n\t *\n\t * The actual logger, not a path to one. It used to be named in config as\n\t * `logger: './config/logger'`, because the build wrote an import into each\n\t * generated handler and a generator can print a specifier but not an object.\n\t * Endpoints built from the surface carry it, so there is nothing to print\n\t * and nothing to keep in step with a moved file.\n\t */\n\tlogger?: Logger;\n\t/**\n\t * The environment parser every endpoint on this surface runs with.\n\t *\n\t * Same reason as `logger`, and the same field it replaces —\n\t * `envParser: './config/env#envParser'`, a module path with an export name\n\t * appended, parsed by us, checked by nothing.\n\t */\n\tenvParser?: EnvironmentParser<{}>;\n\t/**\n\t * The Telescope instance this surface's entry mounts.\n\t *\n\t * The actual instance, for the reason `logger` is: it used to be named as\n\t * `telescope: './config/telescope#telescope'`, a module path the build\n\t * printed an import for. The entry already imports the surface.\n\t */\n\ttelescope?: Telescope;\n\t/**\n\t * What this surface's process emits — the `Telemetry` construct, passed\n\t * like the logger: a fact about the process, not a grant to a route.\n\t *\n\t * An edge to the node, so the deploy hands this process the `OTEL_*` keys\n\t * its stage resolves, and the build fails without the OpenTelemetry\n\t * packages. Where the telemetry goes is never here: it is the deploy's,\n\t * per stage.\n\t */\n\ttelemetry?: Telemetry;\n}\n\n/**\n * What is *not* here, and why.\n *\n * `dependsOn`, `database`, `auditor` and `.event(topic, …)` all inject a capability\n * into a handler. Putting one on the surface hands it to every route the\n * surface serves — a health check gets the database because a report needed it\n * — which is the thing least privilege forbids and the reason `.calls()` is not\n * spelled `dependsOn`. They belong to the endpoint, or to a branch —\n * `api.database(db)` — for a group of endpoints that genuinely share them. A\n * branch is a new factory; the surface config stays free of grants.\n *\n * `auth` is not here either: `.auth(construct)` already declares it, and a\n * second way to say the same thing is the duplication this whole model removes.\n *\n * What is left is what the *process* is rather than what a route may reach.\n */\n\nexport class RestApi<\n\tTName extends string = string,\n\tconst TAuthorizers extends readonly string[] = readonly [],\n> implements Declarable<TName>\n{\n\treadonly id: TName;\n\n\t/**\n\t * Declared once and read by both `declare()` and anything that consumes this\n\t * surface, so what the target publishes and what a consumer reads cannot\n\t * drift.\n\t */\n\treadonly keys: {\n\t\turl: string;\n\t\ttrustedOrigins: string;\n\t\tcookieDomain: string;\n\t};\n\n\t/**\n\t * The logger every endpoint on this surface runs with.\n\t *\n\t * Always defined — the surface's own if it was given one, the console\n\t * logger otherwise — so nothing downstream has to decide what to do about a\n\t * missing one. The generated entry reads it from here.\n\t */\n\treadonly logger: Logger;\n\n\t/**\n\t * The environment parser every endpoint on this surface runs with.\n\t *\n\t * Always defined, and normally the default: `process.env` merged with the\n\t * credentials `gkm dev`/`gkm exec` injected. That is what every\n\t * application's own `config/env.ts` was — boilerplate identical in every\n\t * project, and mandatory, which is a poor combination.\n\t */\n\treadonly envParser: EnvironmentParser<{}>;\n\n\t/** The Telescope instance, when this surface was given one. */\n\treadonly telescope?: Telescope;\n\n\t/** What this surface's process emits, when it was given a `Telemetry`. */\n\treadonly telemetry?: Telemetry;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: RestApiConfig<TAuthorizers>,\n\t\t/** Internal: how `.calls()` carries edges into the copy it returns. */\n\t\tprivate readonly dependencies: readonly Dependency[] = [],\n\t\t/** Internal: how `.auth()` carries the authenticator into its copy. */\n\t\tprivate readonly authenticator?: Authenticator,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\n\t\tthis.keys = {\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\tthis.logger = config.logger ?? DEFAULT_LOGGER;\n\t\tthis.telescope = config.telescope;\n\t\tthis.telemetry = config.telemetry;\n\t\tthis.envParser = envParserFor(\n\t\t\tconfig.envParser\n\t\t\t\t? { id: canonical, envParser: config.envParser }\n\t\t\t\t: undefined,\n\t\t);\n\n\t\tthis.#endpoints = new EndpointFactory({\n\t\t\tdefaultLogger: this.logger,\n\t\t\t...(config.authorizers\n\t\t\t\t? {\n\t\t\t\t\t\t// With the scheme a built-in name stands for, as the factory's own\n\t\t\t\t\t\t// `.authorizers()` resolves it. Bare names reached the OpenAPI\n\t\t\t\t\t\t// document with no scheme, so a guarded endpoint read as public.\n\t\t\t\t\t\tavailableAuthorizers: config.authorizers.map((name) => {\n\t\t\t\t\t\t\tconst securityScheme = getSecurityScheme(name);\n\t\t\t\t\t\t\treturn securityScheme ? { name, securityScheme } : { name };\n\t\t\t\t\t\t}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t// `'none'` reaches the factory as no default at all, which is what\n\t\t\t// public means to an endpoint that names no authorizer.\n\t\t\t...(config.defaultAuthorizer && config.defaultAuthorizer !== 'none'\n\t\t\t\t? { defaultAuthorizerName: config.defaultAuthorizer }\n\t\t\t\t: {}),\n\t\t\tsurface: {\n\t\t\t\tid: this.id,\n\t\t\t\tenvParser: this.envParser,\n\t\t\t\t...(authenticator ? { auth: authenticator } : {}),\n\t\t\t},\n\t\t});\n\n\t\tconst endpoints = this.#endpoints;\n\t\tthis.get = endpoints.get.bind(endpoints);\n\t\tthis.post = endpoints.post.bind(endpoints);\n\t\tthis.put = endpoints.put.bind(endpoints);\n\t\tthis.patch = endpoints.patch.bind(endpoints);\n\t\tthis.delete = endpoints.delete.bind(endpoints);\n\t\tthis.options = endpoints.options.bind(endpoints);\n\t\tthis.database = endpoints.database.bind(endpoints);\n\t\tthis.session = endpoints.session.bind(endpoints);\n\t\tthis.auditor = endpoints.auditor.bind(endpoints);\n\t\tthis.actor = endpoints.actor.bind(endpoints);\n\t\tthis.authorizer = endpoints.authorizer.bind(endpoints);\n\t\tthis.authorize = endpoints.authorize.bind(endpoints);\n\t\tthis.rls = endpoints.rls.bind(endpoints);\n\t\tthis.route = endpoints.route.bind(endpoints);\n\t}\n\n\t/**\n\t * This surface's endpoint factory, which every method below starts from.\n\t *\n\t * Private: a surface *is* where endpoints are built, so there is no second\n\t * object to reach through first. `api.database(db)` said the same\n\t * thing as `api.database(db)` with one more word to learn.\n\t */\n\treadonly #endpoints: Endpoints;\n\n\t/** `api.get('/users')` — one route on this surface. */\n\treadonly get: Endpoints['get'];\n\treadonly post: Endpoints['post'];\n\treadonly put: Endpoints['put'];\n\treadonly patch: Endpoints['patch'];\n\treadonly delete: Endpoints['delete'];\n\treadonly options: Endpoints['options'];\n\n\t/**\n\t * A branch for a *group* of endpoints that shares what a single route would\n\t * otherwise repeat — a database, an auditor, a publisher, a session:\n\t *\n\t * ```ts\n\t * export const router = api.database(database);\n\t * export const createUser = router.post('/users').handle(({ db }) => …);\n\t * ```\n\t *\n\t * Each returns a new factory and leaves the surface as it was. That is the\n\t * whole difference from putting the same thing in the surface's config: a\n\t * group opts in, where the surface would grant it to every route it serves —\n\t * a health check handed the database because a profile endpoint needed it.\n\t *\n\t * `dependsOn` is deliberately not here. It is per endpoint, and on the\n\t * surface it would read as the API depending on something, which is what\n\t * `.calls()` and `.auth()` say instead.\n\t */\n\treadonly database: Endpoints['database'];\n\treadonly session: Endpoints['session'];\n\treadonly auditor: Endpoints['auditor'];\n\treadonly actor: Endpoints['actor'];\n\treadonly authorizer: Endpoints['authorizer'];\n\treadonly authorize: Endpoints['authorize'];\n\treadonly rls: Endpoints['rls'];\n\treadonly route: Endpoints['route'];\n\n\t/**\n\t * What authenticates this surface.\n\t *\n\t * An edge like `.calls()` — the auth server learns this origin, and the two\n\t * share a cookie domain — but a named one, because *who authenticates me* is\n\t * a different fact from *who I happen to call*, and only one of them decides\n\t * what a request is allowed to be. A surface with two of the first is a\n\t * mistake; two of the second is Tuesday.\n\t *\n\t * It declares the id, and keeps the construct: a session callback reads from\n\t * it as `auth` — `session(async ({ auth }) => auth.getSession())` — which\n\t * calls the construct's `verify(headers)`. That is the one thing every\n\t * provider shares, whether the server is mounted in this process, deployed\n\t * beside it, or an OIDC issuer somebody else runs.\n\t */\n\tauth(construct: Authenticator): RestApi<TName, TAuthorizers> {\n\t\treturn new RestApi<TName, TAuthorizers>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, edgeTo(construct)],\n\t\t\tconstruct,\n\t\t);\n\t}\n\n\t/**\n\t * Other surfaces this one calls.\n\t *\n\t * **Not `.dependsOn()`, and the difference matters.** An endpoint's\n\t * `.dependsOn()` injects a client into that handler and grants it exactly\n\t * what it named. This grants nothing and injects nothing: it records that\n\t * this API calls another surface, which is what puts this API's origin on\n\t * that surface's trusted-origin list.\n\t *\n\t * Spelling it `dependsOn` would invite the thing least privilege forbids —\n\t * every route on the surface receiving whatever the surface named.\n\t *\n\t * Immutable, like every other builder here.\n\t */\n\tcalls(constructs: readonly Declarable[]): RestApi<TName, TAuthorizers> {\n\t\treturn new RestApi<TName, TAuthorizers>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, ...constructs.map(edgeTo)],\n\t\t\tthis.authenticator,\n\t\t);\n\t}\n\n\t/**\n\t * One surface node, with its endpoints left to the build.\n\t *\n\t * The three provided keys are one fact about this surface and two about its\n\t * callers. Declaring the caller-derived pair here rather than having the\n\t * target invent them is what makes the contract checkable: a target that\n\t * resolves no origins is caught against this list instead of being noticed\n\t * when a browser is refused in production.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\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.telescope ? { telescope: true } : {}),\n\t\t\t\t...(this.config.cors ? { cors: this.config.cors } : {}),\n\t\t\t\t...(this.authenticator ? { auth: this.authenticator.id } : {}),\n\t\t\t\t// Filled by the build, which already generates one handler per\n\t\t\t\t// endpoint and knows the path it wrote it to. A surface that\n\t\t\t\t// enumerates its own routes statically — an auth server's single\n\t\t\t\t// wildcard — puts them here instead.\n\t\t\t\tendpoints: [],\n\t\t\t\t...(this.dependencies.length ? { calls: this.dependencies } : {}),\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\t...(this.config.authorizers?.length\n\t\t\t\t\t? { authorizers: this.config.authorizers }\n\t\t\t\t\t: {}),\n\t\t\t\tdefaultAuthorizer: this.config.def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KAAK,OAAO,OAAO,EAAE,MAAM,KAAK,OAAO,KAAK,IAAI,CAAC;GACrD,GAAI,KAAK,gBAAgB,EAAE,MAAM,KAAK,cAAc,GAAG,IAAI,CAAC;GAK5D,WAAW,CAAC;GACZ,GAAI,KAAK,aAAa,SAAS,EAAE,OAAO,KAAK,aAAa,IAAI,CAAC;GAC/D,GAAI,KAAK,OAAO,YACb,EAAE,WAAW,KAAK,OAAO,UAAU,GAAG,IACtC,CAAC;GACJ,GAAI,KAAK,OAAO,aAAa,SAC1B,EAAE,aAAa,KAAK,OAAO,YAAY,IACvC,CAAC;GACJ,mBAAmB,KAAK,OAAO;GAC/B,UAAU;IACT,KAAK,KAAK;IACV,KAAK,KAAK;IACV,KAAK,KAAK;GACX;EACD,CACD;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"rest-api.mjs","names":[],"sources":["../src/rest-api.ts"],"sourcesContent":["/**\n * `RestApi` — the application's own HTTP surface, declared.\n *\n * Everything an app serves already existed; what did not exist was a *node* for\n * it. Without one, three things that are properties of the graph had to be\n * written down somewhere else: which origins the API accepts, which origins the\n * auth server trusts, and which URL a frontend is built against. All three were\n * being derived by walking the workspace config for ports — a second mechanism,\n * running beside the graph and answering the same question worse, since it can\n * only ever describe what this repo happens to run.\n *\n * With the surface declared, all three become one edge read backwards: a\n * consumer depends on the API, and *that* is the CORS entry, the trusted origin,\n * and the build-time URL. Nothing enumerates its own callers.\n *\n * ```ts\n * export const api = new RestApi('Api', {\n * authorizers: ['session'],\n * defaultAuthorizer: 'session',\n * });\n * ```\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n\tprovideKey,\n} from '@geekmidas/manifest';\nimport type { Telescope } from '@geekmidas/telescope';\nimport {\n\ttype Authenticator,\n\ttype Declarable,\n\tedgeTo,\n} from './construct-interface';\n\nexport type { Authenticator } from './construct-interface';\n\nimport {\n\ttype BuiltInSecuritySchemeId,\n\tgetSecurityScheme,\n} from './endpoints/Authorizer';\nimport { EndpointFactory } from './endpoints/EndpointFactory';\nimport { envParserFor } from './endpoints/surfaceEnv';\nimport type { Telemetry } from './telemetry';\n\n/** The factory a surface builds its endpoints from. */\ntype Endpoints = EndpointFactory<[], '', Logger>;\n\nexport interface RestApiConfig<\n\t// `readonly []` rather than `readonly string[]`: a surface that declares no\n\t// authorizers of its own should narrow `defaultAuthorizer` to the built-ins\n\t// and `'none'`, not widen it back to any string.\n\tTAuthorizers extends readonly string[] = readonly [],\n> {\n\t/**\n\t * The app that serves this surface, relative to the workspace root —\n\t * `'apps/api'`, or `'.'` in a single-app project.\n\t *\n\t * Required. It was inferred from the id (`apps/<kebab-id>`, or the root\n\t * when no such directory existed), which meant a surface's home was\n\t * whatever happened to be on disk. It is where the app's `package.json`\n\t * and base `tsconfig.json` are, and which build serves this surface. It\n\t * does not change discovery: constructs still load from the workspace's\n\t * `constructs` glob.\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 * CORS tunables. The *origins* are never here — they are read off the\n\t * constructs that declared an edge to this surface, which is the whole point\n\t * of declaring one. These are the parts a graph cannot answer.\n\t */\n\tcors?: {\n\t\tmaxAge?: number;\n\t\tcredentials?: boolean;\n\t\tallowHeaders?: readonly string[];\n\t\texposeHeaders?: readonly string[];\n\t};\n\t/**\n\t * The authorizer names this surface exposes. Names only — what verifies a\n\t * request legitimately differs between local and deployed, so the mechanism\n\t * belongs to the target and never to portable code.\n\t */\n\tauthorizers?: TAuthorizers;\n\t/**\n\t * The authorizer applied to an endpoint that names none.\n\t *\n\t * Required, and `'none'` is a valid answer that has to be typed out. The\n\t * alternative is an API that ships open because a field was left off, which\n\t * is the one default worth refusing to have.\n\t *\n\t * It was called `default`, which said what it was to the type and nothing\n\t * to the reader: next to `authorizers: ['iam']`, a bare `default: 'none'`\n\t * could be defaulting the runtime or the target. The manifest has always\n\t * called it `defaultAuthorizer` and the factory `defaultAuthorizerName`;\n\t * this is the same fact under the same name.\n\t *\n\t * Typed from `authorizers`, so it can only name one this surface exposes —\n\t * plus a built-in scheme, and `'none'`. It was a bare `string`, which let\n\t * `defaultAuthorizer: 'jwtt'` compile and every endpoint on the surface\n\t * default to an authorizer that does not exist.\n\t */\n\tdefaultAuthorizer: TAuthorizers[number] | BuiltInSecuritySchemeId | 'none';\n\t/**\n\t * The logger every endpoint on this surface runs with.\n\t *\n\t * The actual logger, not a path to one. It used to be named in config as\n\t * `logger: './config/logger'`, because the build wrote an import into each\n\t * generated handler and a generator can print a specifier but not an object.\n\t * Endpoints built from the surface carry it, so there is nothing to print\n\t * and nothing to keep in step with a moved file.\n\t */\n\tlogger?: Logger;\n\t/**\n\t * The environment parser every endpoint on this surface runs with.\n\t *\n\t * Same reason as `logger`, and the same field it replaces —\n\t * `envParser: './config/env#envParser'`, a module path with an export name\n\t * appended, parsed by us, checked by nothing.\n\t */\n\tenvParser?: EnvironmentParser<{}>;\n\t/**\n\t * The Telescope instance this surface's entry mounts.\n\t *\n\t * The actual instance, for the reason `logger` is: it used to be named as\n\t * `telescope: './config/telescope#telescope'`, a module path the build\n\t * printed an import for. The entry already imports the surface.\n\t */\n\ttelescope?: Telescope;\n\t/**\n\t * What this surface's process emits — the `Telemetry` construct, passed\n\t * like the logger: a fact about the process, not a grant to a route.\n\t *\n\t * An edge to the node, so the deploy hands this process the `OTEL_*` keys\n\t * its stage resolves, and the build fails without the OpenTelemetry\n\t * packages. Where the telemetry goes is never here: it is the deploy's,\n\t * per stage.\n\t */\n\ttelemetry?: Telemetry;\n}\n\n/**\n * What is *not* here, and why.\n *\n * `dependsOn`, `database`, `auditor` and `.event(topic, …)` all inject a capability\n * into a handler. Putting one on the surface hands it to every route the\n * surface serves — a health check gets the database because a report needed it\n * — which is the thing least privilege forbids and the reason `.calls()` is not\n * spelled `dependsOn`. They belong to the endpoint, or to a branch —\n * `api.database(db)` — for a group of endpoints that genuinely share them. A\n * branch is a new factory; the surface config stays free of grants.\n *\n * `auth` is not here either: `.auth(construct)` already declares it, and a\n * second way to say the same thing is the duplication this whole model removes.\n *\n * What is left is what the *process* is rather than what a route may reach.\n */\n\nexport class RestApi<\n\tTName extends string = string,\n\tconst TAuthorizers extends readonly string[] = readonly [],\n> implements Declarable<TName>\n{\n\treadonly id: TName;\n\n\t/**\n\t * Declared once and read by both `declare()` and anything that consumes this\n\t * surface, so what the target publishes and what a consumer reads cannot\n\t * drift.\n\t */\n\treadonly keys: {\n\t\turl: string;\n\t\ttrustedOrigins: string;\n\t\tcookieDomain: string;\n\t};\n\n\t/**\n\t * The logger every endpoint on this surface runs with.\n\t *\n\t * Always defined — the surface's own if it was given one, the console\n\t * logger otherwise — so nothing downstream has to decide what to do about a\n\t * missing one. The generated entry reads it from here.\n\t */\n\treadonly logger: Logger;\n\n\t/**\n\t * The environment parser every endpoint on this surface runs with.\n\t *\n\t * Always defined, and normally the default: `process.env` merged with the\n\t * credentials `gkm dev`/`gkm exec` injected. That is what every\n\t * application's own `config/env.ts` was — boilerplate identical in every\n\t * project, and mandatory, which is a poor combination.\n\t */\n\treadonly envParser: EnvironmentParser<{}>;\n\n\t/** The Telescope instance, when this surface was given one. */\n\treadonly telescope?: Telescope;\n\n\t/** What this surface's process emits, when it was given a `Telemetry`. */\n\treadonly telemetry?: Telemetry;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: RestApiConfig<TAuthorizers>,\n\t\t/** Internal: how `.calls()` carries edges into the copy it returns. */\n\t\tprivate readonly dependencies: readonly Dependency[] = [],\n\t\t/** Internal: how `.auth()` carries the authenticator into its copy. */\n\t\tprivate readonly authenticator?: Authenticator,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\n\t\tthis.keys = {\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\tthis.logger = config.logger ?? DEFAULT_LOGGER;\n\t\tthis.telescope = config.telescope;\n\t\tthis.telemetry = config.telemetry;\n\t\tthis.envParser = envParserFor(\n\t\t\tconfig.envParser\n\t\t\t\t? { id: canonical, envParser: config.envParser }\n\t\t\t\t: undefined,\n\t\t);\n\n\t\tthis.#endpoints = new EndpointFactory({\n\t\t\tdefaultLogger: this.logger,\n\t\t\t...(config.authorizers\n\t\t\t\t? {\n\t\t\t\t\t\t// With the scheme a built-in name stands for, as the factory's own\n\t\t\t\t\t\t// `.authorizers()` resolves it. Bare names reached the OpenAPI\n\t\t\t\t\t\t// document with no scheme, so a guarded endpoint read as public.\n\t\t\t\t\t\tavailableAuthorizers: config.authorizers.map((name) => {\n\t\t\t\t\t\t\tconst securityScheme = getSecurityScheme(name);\n\t\t\t\t\t\t\treturn securityScheme ? { name, securityScheme } : { name };\n\t\t\t\t\t\t}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t// `'none'` reaches the factory as no default at all, which is what\n\t\t\t// public means to an endpoint that names no authorizer.\n\t\t\t...(config.defaultAuthorizer && config.defaultAuthorizer !== 'none'\n\t\t\t\t? { defaultAuthorizerName: config.defaultAuthorizer }\n\t\t\t\t: {}),\n\t\t\tsurface: {\n\t\t\t\tid: this.id,\n\t\t\t\tenvParser: this.envParser,\n\t\t\t\t...(authenticator ? { auth: authenticator } : {}),\n\t\t\t},\n\t\t});\n\n\t\tconst endpoints = this.#endpoints;\n\t\tthis.get = endpoints.get.bind(endpoints);\n\t\tthis.post = endpoints.post.bind(endpoints);\n\t\tthis.put = endpoints.put.bind(endpoints);\n\t\tthis.patch = endpoints.patch.bind(endpoints);\n\t\tthis.delete = endpoints.delete.bind(endpoints);\n\t\tthis.options = endpoints.options.bind(endpoints);\n\t\tthis.database = endpoints.database.bind(endpoints);\n\t\tthis.session = endpoints.session.bind(endpoints);\n\t\tthis.auditor = endpoints.auditor.bind(endpoints);\n\t\tthis.actor = endpoints.actor.bind(endpoints);\n\t\tthis.authorizer = endpoints.authorizer.bind(endpoints);\n\t\tthis.authorize = endpoints.authorize.bind(endpoints);\n\t\tthis.rls = endpoints.rls.bind(endpoints);\n\t\tthis.route = endpoints.route.bind(endpoints);\n\t}\n\n\t/**\n\t * This surface's endpoint factory, which every method below starts from.\n\t *\n\t * Private: a surface *is* where endpoints are built, so there is no second\n\t * object to reach through first. `api.database(db)` said the same\n\t * thing as `api.database(db)` with one more word to learn.\n\t */\n\treadonly #endpoints: Endpoints;\n\n\t/** `api.get('/users')` — one route on this surface. */\n\treadonly get: Endpoints['get'];\n\treadonly post: Endpoints['post'];\n\treadonly put: Endpoints['put'];\n\treadonly patch: Endpoints['patch'];\n\treadonly delete: Endpoints['delete'];\n\treadonly options: Endpoints['options'];\n\n\t/**\n\t * A branch for a *group* of endpoints that shares what a single route would\n\t * otherwise repeat — a database, an auditor, a publisher, a session:\n\t *\n\t * ```ts\n\t * export const router = api.database(database);\n\t * export const createUser = router.post('/users').handle(({ db }) => …);\n\t * ```\n\t *\n\t * Each returns a new factory and leaves the surface as it was. That is the\n\t * whole difference from putting the same thing in the surface's config: a\n\t * group opts in, where the surface would grant it to every route it serves —\n\t * a health check handed the database because a profile endpoint needed it.\n\t *\n\t * `dependsOn` is deliberately not here. It is per endpoint, and on the\n\t * surface it would read as the API depending on something, which is what\n\t * `.calls()` and `.auth()` say instead.\n\t */\n\treadonly database: Endpoints['database'];\n\treadonly session: Endpoints['session'];\n\treadonly auditor: Endpoints['auditor'];\n\treadonly actor: Endpoints['actor'];\n\treadonly authorizer: Endpoints['authorizer'];\n\treadonly authorize: Endpoints['authorize'];\n\treadonly rls: Endpoints['rls'];\n\treadonly route: Endpoints['route'];\n\n\t/**\n\t * What authenticates this surface.\n\t *\n\t * An edge like `.calls()` — the auth server learns this origin, and the two\n\t * share a cookie domain — but a named one, because *who authenticates me* is\n\t * a different fact from *who I happen to call*, and only one of them decides\n\t * what a request is allowed to be. A surface with two of the first is a\n\t * mistake; two of the second is Tuesday.\n\t *\n\t * It declares the id, and keeps the construct: a session callback reads from\n\t * it as `auth` — `session(async ({ auth }) => auth.getSession())` — which\n\t * calls the construct's `verify(headers)`. That is the one thing every\n\t * provider shares, whether the server is mounted in this process, deployed\n\t * beside it, or an OIDC issuer somebody else runs.\n\t */\n\tauth(construct: Authenticator): RestApi<TName, TAuthorizers> {\n\t\treturn new RestApi<TName, TAuthorizers>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, edgeTo(construct)],\n\t\t\tconstruct,\n\t\t);\n\t}\n\n\t/**\n\t * Other surfaces this one calls.\n\t *\n\t * **Not `.dependsOn()`, and the difference matters.** An endpoint's\n\t * `.dependsOn()` injects a client into that handler and grants it exactly\n\t * what it named. This grants nothing and injects nothing: it records that\n\t * this API calls another surface, which is what puts this API's origin on\n\t * that surface's trusted-origin list.\n\t *\n\t * Spelling it `dependsOn` would invite the thing least privilege forbids —\n\t * every route on the surface receiving whatever the surface named.\n\t *\n\t * Immutable, like every other builder here.\n\t */\n\tcalls(constructs: readonly Declarable[]): RestApi<TName, TAuthorizers> {\n\t\treturn new RestApi<TName, TAuthorizers>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, ...constructs.map(edgeTo)],\n\t\t\tthis.authenticator,\n\t\t);\n\t}\n\n\t/**\n\t * One surface node, with its endpoints left to the build.\n\t *\n\t * The three provided keys are one fact about this surface and two about its\n\t * callers. Declaring the caller-derived pair here rather than having the\n\t * target invent them is what makes the contract checkable: a target that\n\t * resolves no origins is caught against this list instead of being noticed\n\t * when a browser is refused in production.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\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.telescope ? { telescope: true } : {}),\n\t\t\t\t...(this.config.cors ? { cors: this.config.cors } : {}),\n\t\t\t\t...(this.authenticator ? { auth: this.authenticator.id } : {}),\n\t\t\t\t// Filled by the build, which already generates one handler per\n\t\t\t\t// endpoint and knows the path it wrote it to. A surface that\n\t\t\t\t// enumerates its own routes statically — an auth server's single\n\t\t\t\t// wildcard — puts them here instead.\n\t\t\t\tendpoints: [],\n\t\t\t\t...(this.dependencies.length ? { calls: this.dependencies } : {}),\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\t...(this.config.authorizers?.length\n\t\t\t\t\t? { authorizers: this.config.authorizers }\n\t\t\t\t\t: {}),\n\t\t\t\tdefaultAuthorizer: this.config.defaultAuthorizer,\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},\n\t\t];\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwKA,IAAa,UAAb,MAAa,QAIb;CAyCmB;CAEA;CAEA;CA5ClB;;;;;;CAOA;;;;;;;;CAaA;;;;;;;;;CAUA;;CAGA;;CAGA;CAEA,YACC,IACA,QAEA,eAAuD,CAAC,GAExD,eACC;EALgB,KAAA,SAAA;EAEA,KAAA,eAAA;EAEA,KAAA,gBAAA;EAEjB,MAAM,YAAY,YAAY,EAAY;EAE1C,KAAK,KAAK;EAEV,KAAK,OAAO;GACX,KAAK,WAAW,WAAW,KAAK;GAChC,gBAAgB,WAAW,WAAW,gBAAgB;GACtD,cAAc,WAAW,WAAW,cAAc;EACnD;EAEA,KAAK,SAAS,OAAO,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CAGA;CACA;CACA;CACA;CACA;CACA;;;;;;;;;;;;;;;;;;;CAoBA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;;;;;;;;;;;;;;;;CAiBA,KAAK,WAAwD;EAC5D,OAAO,IAAI,QACV,KAAK,IACL,KAAK,QACL,CAAC,GAAG,KAAK,cAAc,OAAO,SAAS,CAAC,GACxC,SACD;CACD;;;;;;;;;;;;;;;CAgBA,MAAM,YAAiE;EACtE,OAAO,IAAI,QACV,KAAK,IACL,KAAK,QACL,CAAC,GAAG,KAAK,cAAc,GAAG,WAAW,IAAI,MAAM,CAAC,GAChD,KAAK,aACN;CACD;;;;;;;;;;CAWA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,MAAM,KAAK,OAAO;GAClB,GAAI,KAAK,OAAO,YAAY,EAAE,WAAW,KAAK,OAAO,UAAU,IAAI,CAAC;GACpE,GAAI,KAAK,OAAO,YAAY,EAAE,WAAW,KAAK,IAAI,CAAC;GACnD,GAAI,KAAK,OAAO,OAAO,EAAE,MAAM,KAAK,OAAO,KAAK,IAAI,CAAC;GACrD,GAAI,KAAK,gBAAgB,EAAE,MAAM,KAAK,cAAc,GAAG,IAAI,CAAC;GAK5D,WAAW,CAAC;GACZ,GAAI,KAAK,aAAa,SAAS,EAAE,OAAO,KAAK,aAAa,IAAI,CAAC;GAC/D,GAAI,KAAK,OAAO,YACb,EAAE,WAAW,KAAK,OAAO,UAAU,GAAG,IACtC,CAAC;GACJ,GAAI,KAAK,OAAO,aAAa,SAC1B,EAAE,aAAa,KAAK,OAAO,YAAY,IACvC,CAAC;GACJ,mBAAmB,KAAK,OAAO;GAC/B,UAAU;IACT,KAAK,KAAK;IACV,KAAK,KAAK;IACV,KAAK,KAAK;GACX;EACD,CACD;CACD;AACD"}
|
package/dist/site.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"site.cjs","names":["canonicalId","provideKey","edgeTo"],"sources":["../src/site.ts"],"sourcesContent":["/**\n * `StaticSite` — a frontend, declared like anything else.\n *\n * The point is not that a site needs provisioning; it is that a site is the\n * *consumer* whose edges make four hand-maintained lists derivable. Declaring it\n * is what turns \"which origins does the API allow\" from something a person keeps\n * in step into something the graph already knows.\n *\n * ```ts\n * export const console = new StaticSite('Console', { path: 'apps/console' })\n * .dependsOn([api, auth]);\n * ```\n *\n * It has no `.service`. A site is not a process that registers clients — it is\n * built, and the values it needs are inlined or fetched by its own framework —\n * so the edge is {@link Declarable} rather than {@link Consumable}, and the\n * asymmetry is the honest one: a site consumes addresses, not connections.\n *\n * Only the static variant ships. SSR deploy shapes are unstable and each one is\n * its own maintenance, so they follow rather than arrive together. A mobile app\n * is not a site — it is reached by a scheme, not a URL — and is its own\n * construct: see `MobileApp`.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n\tprovideKey,\n\ttype SiteDeclaration,\n} from '@geekmidas/manifest';\nimport { type Declarable, edgeTo } from './construct-interface';\nimport type { Telemetry } from './telemetry';\n\n/**\n * Where a site's source lives, and the little else a layout can differ by.\n *\n * Only `path` is required: `new StaticSite('Web', { path: 'apps/web' })` is a\n * complete site.\n */\nexport interface StaticSiteConfig {\n\t/**\n\t * Where its source lives, relative to the workspace root — `'apps/web'`.\n\t *\n\t * Required, the same field `RestApi` and `BetterAuth` take. It was\n\t * inferred from the id, which made a site's home whatever was on disk.\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 `
|
|
1
|
+
{"version":3,"file":"site.cjs","names":["canonicalId","provideKey","edgeTo"],"sources":["../src/site.ts"],"sourcesContent":["/**\n * `StaticSite` — a frontend, declared like anything else.\n *\n * The point is not that a site needs provisioning; it is that a site is the\n * *consumer* whose edges make four hand-maintained lists derivable. Declaring it\n * is what turns \"which origins does the API allow\" from something a person keeps\n * in step into something the graph already knows.\n *\n * ```ts\n * export const console = new StaticSite('Console', { path: 'apps/console' })\n * .dependsOn([api, auth]);\n * ```\n *\n * It has no `.service`. A site is not a process that registers clients — it is\n * built, and the values it needs are inlined or fetched by its own framework —\n * so the edge is {@link Declarable} rather than {@link Consumable}, and the\n * asymmetry is the honest one: a site consumes addresses, not connections.\n *\n * Only the static variant ships. SSR deploy shapes are unstable and each one is\n * its own maintenance, so they follow rather than arrive together. A mobile app\n * is not a site — it is reached by a scheme, not a URL — and is its own\n * construct: see `MobileApp`.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n\tprovideKey,\n\ttype SiteDeclaration,\n} from '@geekmidas/manifest';\nimport { type Declarable, edgeTo } from './construct-interface';\nimport type { Telemetry } from './telemetry';\n\n/**\n * Where a site's source lives, and the little else a layout can differ by.\n *\n * Only `path` is required: `new StaticSite('Web', { path: 'apps/web' })` is a\n * complete site.\n */\nexport interface StaticSiteConfig {\n\t/**\n\t * Where its source lives, relative to the workspace root — `'apps/web'`.\n\t *\n\t * Required, the same field `RestApi` and `BetterAuth` take. It was\n\t * inferred from the id, which made a site's home whatever was on disk.\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 * The port it answers on locally.\n\t *\n\t * Normally omitted: ports are assigned in a stable order, so adding a site\n\t * does not renumber the ones already running.\n\t */\n\tport?: number;\n\t/**\n\t * Modules to import when sniffing which env vars this site reads.\n\t *\n\t * A frontend's values are inlined at build time, so the build has to know\n\t * which ones it reads before it reads them.\n\t */\n\tconfig?: { client?: string; server?: string };\n\t/**\n\t * Whether the base domain points at this site.\n\t *\n\t * A project with one site needs this no more than a project with one\n\t * database needs to say which database. It matters when there are several\n\t * and none is called `web`: the base domain then belongs to whichever site\n\t * says so, rather than to whichever file the glob happened to reach first.\n\t */\n\troot?: boolean;\n\t/**\n\t * Which framework builds it.\n\t *\n\t * It selects how values are delivered — `VITE_`, `NEXT_PUBLIC_`, a fetched\n\t * `config.json` — and never which values there are. One neutral name from the\n\t * construct, one serialisation per framework, the same rule as everywhere\n\t * else.\n\t */\n\tvariant?: SiteDeclaration['variant'];\n\t/**\n\t * What the site emits — the `Telemetry` construct. An edge to the node and\n\t * nothing more for now: a site is handed none of its server keys, and the\n\t * browser half (propagation from the generated client, then a browser SDK\n\t * exporting through the API) builds on this edge.\n\t */\n\ttelemetry?: Telemetry;\n}\n\nexport class StaticSite<TName extends string = string>\n\timplements Declarable<TName>\n{\n\treadonly id: TName;\n\treadonly keys: { url: string };\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: StaticSiteConfig,\n\t\t/**\n\t\t * Internal: how `.dependsOn()` carries edges into the copy it returns.\n\t\t * Written as a parameter rather than a mutable field so the builder can\n\t\t * stay immutable without a clone method, the same shape\n\t\t * `KyselyDatabase` uses for its derived forms.\n\t\t */\n\t\tprivate readonly dependencies: readonly Dependency[] = [],\n\t) {\n\t\tthis.id = canonicalId(id as string) as TName;\n\t\tthis.keys = { url: provideKey(this.id, 'url') };\n\t}\n\n\t/**\n\t * What this site calls.\n\t *\n\t * Immutable, like every other builder here: it returns a new site rather than\n\t * mutating this one, so a module that exports both a base and a variant of it\n\t * cannot have the second silently change the first.\n\t *\n\t * Takes {@link Declarable} rather than {@link Consumable} because a site's\n\t * edge is a build-time link and not a service injection — requiring a client\n\t * would exclude exactly the surfaces a frontend actually depends on.\n\t */\n\tdependsOn(constructs: readonly Declarable[]): StaticSite<TName> {\n\t\treturn new StaticSite<TName>(this.id as ConstructName<TName>, this.config, [\n\t\t\t...this.dependencies,\n\t\t\t...constructs.map(edgeTo),\n\t\t]);\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'site',\n\t\t\t\tid: this.id,\n\t\t\t\tvariant: this.config.variant ?? 'static',\n\t\t\t\t...(this.config.subdomain ? { subdomain: this.config.subdomain } : {}),\n\t\t\t\tapp: {\n\t\t\t\t\tpath: this.config.path,\n\t\t\t\t\t...(this.config.port ? { port: this.config.port } : {}),\n\t\t\t\t\t...(this.config.config ? { config: this.config.config } : {}),\n\t\t\t\t},\n\t\t\t\t...(this.config.root ? { root: true } : {}),\n\t\t\t\tdependencies: this.dependencies,\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: [this.keys.url],\n\t\t\t},\n\t\t];\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,IAAa,aAAb,MAAa,WAEb;CAMmB;CAOA;CAZlB;CACA;CAEA,YACC,IACA,QAOA,eAAuD,CAAC,GACvD;EARgB,KAAA,SAAA;EAOA,KAAA,eAAA;EAEjB,KAAK,MAAA,GAAKA,oBAAAA,YAAAA,CAAY,EAAY;EAClC,KAAK,OAAO,EAAE,MAAA,GAAKC,oBAAAA,WAAAA,CAAW,KAAK,IAAI,KAAK,EAAE;CAC/C;;;;;;;;;;;;CAaA,UAAU,YAAsD;EAC/D,OAAO,IAAI,WAAkB,KAAK,IAA4B,KAAK,QAAQ,CAC1E,GAAG,KAAK,cACR,GAAG,WAAW,IAAIC,4BAAAA,MAAM,CACzB,CAAC;CACF;CAEA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,SAAS,KAAK,OAAO,WAAW;GAChC,GAAI,KAAK,OAAO,YAAY,EAAE,WAAW,KAAK,OAAO,UAAU,IAAI,CAAC;GACpE,KAAK;IACJ,MAAM,KAAK,OAAO;IAClB,GAAI,KAAK,OAAO,OAAO,EAAE,MAAM,KAAK,OAAO,KAAK,IAAI,CAAC;IACrD,GAAI,KAAK,OAAO,SAAS,EAAE,QAAQ,KAAK,OAAO,OAAO,IAAI,CAAC;GAC5D;GACA,GAAI,KAAK,OAAO,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;GACzC,cAAc,KAAK;GACnB,GAAI,KAAK,OAAO,YACb,EAAE,WAAW,KAAK,OAAO,UAAU,GAAG,IACtC,CAAC;GACJ,UAAU,CAAC,KAAK,KAAK,GAAG;EACzB,CACD;CACD;AACD"}
|
package/dist/site.d.cts
CHANGED
|
@@ -18,7 +18,7 @@ export interface StaticSiteConfig {
|
|
|
18
18
|
path: string;
|
|
19
19
|
/**
|
|
20
20
|
* The label it answers on under a stage's domain — `api` for
|
|
21
|
-
* `api.myapp.com`, from `
|
|
21
|
+
* `api.myapp.com`, from `domains` — and under the project locally,
|
|
22
22
|
* `api.myapp.localhost`. Absent, its id kebab-cased.
|
|
23
23
|
*/
|
|
24
24
|
subdomain?: string;
|
package/dist/site.d.mts
CHANGED
|
@@ -18,7 +18,7 @@ export interface StaticSiteConfig {
|
|
|
18
18
|
path: string;
|
|
19
19
|
/**
|
|
20
20
|
* The label it answers on under a stage's domain — `api` for
|
|
21
|
-
* `api.myapp.com`, from `
|
|
21
|
+
* `api.myapp.com`, from `domains` — and under the project locally,
|
|
22
22
|
* `api.myapp.localhost`. Absent, its id kebab-cased.
|
|
23
23
|
*/
|
|
24
24
|
subdomain?: string;
|
package/dist/site.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"site.mjs","names":[],"sources":["../src/site.ts"],"sourcesContent":["/**\n * `StaticSite` — a frontend, declared like anything else.\n *\n * The point is not that a site needs provisioning; it is that a site is the\n * *consumer* whose edges make four hand-maintained lists derivable. Declaring it\n * is what turns \"which origins does the API allow\" from something a person keeps\n * in step into something the graph already knows.\n *\n * ```ts\n * export const console = new StaticSite('Console', { path: 'apps/console' })\n * .dependsOn([api, auth]);\n * ```\n *\n * It has no `.service`. A site is not a process that registers clients — it is\n * built, and the values it needs are inlined or fetched by its own framework —\n * so the edge is {@link Declarable} rather than {@link Consumable}, and the\n * asymmetry is the honest one: a site consumes addresses, not connections.\n *\n * Only the static variant ships. SSR deploy shapes are unstable and each one is\n * its own maintenance, so they follow rather than arrive together. A mobile app\n * is not a site — it is reached by a scheme, not a URL — and is its own\n * construct: see `MobileApp`.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n\tprovideKey,\n\ttype SiteDeclaration,\n} from '@geekmidas/manifest';\nimport { type Declarable, edgeTo } from './construct-interface';\nimport type { Telemetry } from './telemetry';\n\n/**\n * Where a site's source lives, and the little else a layout can differ by.\n *\n * Only `path` is required: `new StaticSite('Web', { path: 'apps/web' })` is a\n * complete site.\n */\nexport interface StaticSiteConfig {\n\t/**\n\t * Where its source lives, relative to the workspace root — `'apps/web'`.\n\t *\n\t * Required, the same field `RestApi` and `BetterAuth` take. It was\n\t * inferred from the id, which made a site's home whatever was on disk.\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 `
|
|
1
|
+
{"version":3,"file":"site.mjs","names":[],"sources":["../src/site.ts"],"sourcesContent":["/**\n * `StaticSite` — a frontend, declared like anything else.\n *\n * The point is not that a site needs provisioning; it is that a site is the\n * *consumer* whose edges make four hand-maintained lists derivable. Declaring it\n * is what turns \"which origins does the API allow\" from something a person keeps\n * in step into something the graph already knows.\n *\n * ```ts\n * export const console = new StaticSite('Console', { path: 'apps/console' })\n * .dependsOn([api, auth]);\n * ```\n *\n * It has no `.service`. A site is not a process that registers clients — it is\n * built, and the values it needs are inlined or fetched by its own framework —\n * so the edge is {@link Declarable} rather than {@link Consumable}, and the\n * asymmetry is the honest one: a site consumes addresses, not connections.\n *\n * Only the static variant ships. SSR deploy shapes are unstable and each one is\n * its own maintenance, so they follow rather than arrive together. A mobile app\n * is not a site — it is reached by a scheme, not a URL — and is its own\n * construct: see `MobileApp`.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n\tprovideKey,\n\ttype SiteDeclaration,\n} from '@geekmidas/manifest';\nimport { type Declarable, edgeTo } from './construct-interface';\nimport type { Telemetry } from './telemetry';\n\n/**\n * Where a site's source lives, and the little else a layout can differ by.\n *\n * Only `path` is required: `new StaticSite('Web', { path: 'apps/web' })` is a\n * complete site.\n */\nexport interface StaticSiteConfig {\n\t/**\n\t * Where its source lives, relative to the workspace root — `'apps/web'`.\n\t *\n\t * Required, the same field `RestApi` and `BetterAuth` take. It was\n\t * inferred from the id, which made a site's home whatever was on disk.\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 * The port it answers on locally.\n\t *\n\t * Normally omitted: ports are assigned in a stable order, so adding a site\n\t * does not renumber the ones already running.\n\t */\n\tport?: number;\n\t/**\n\t * Modules to import when sniffing which env vars this site reads.\n\t *\n\t * A frontend's values are inlined at build time, so the build has to know\n\t * which ones it reads before it reads them.\n\t */\n\tconfig?: { client?: string; server?: string };\n\t/**\n\t * Whether the base domain points at this site.\n\t *\n\t * A project with one site needs this no more than a project with one\n\t * database needs to say which database. It matters when there are several\n\t * and none is called `web`: the base domain then belongs to whichever site\n\t * says so, rather than to whichever file the glob happened to reach first.\n\t */\n\troot?: boolean;\n\t/**\n\t * Which framework builds it.\n\t *\n\t * It selects how values are delivered — `VITE_`, `NEXT_PUBLIC_`, a fetched\n\t * `config.json` — and never which values there are. One neutral name from the\n\t * construct, one serialisation per framework, the same rule as everywhere\n\t * else.\n\t */\n\tvariant?: SiteDeclaration['variant'];\n\t/**\n\t * What the site emits — the `Telemetry` construct. An edge to the node and\n\t * nothing more for now: a site is handed none of its server keys, and the\n\t * browser half (propagation from the generated client, then a browser SDK\n\t * exporting through the API) builds on this edge.\n\t */\n\ttelemetry?: Telemetry;\n}\n\nexport class StaticSite<TName extends string = string>\n\timplements Declarable<TName>\n{\n\treadonly id: TName;\n\treadonly keys: { url: string };\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: StaticSiteConfig,\n\t\t/**\n\t\t * Internal: how `.dependsOn()` carries edges into the copy it returns.\n\t\t * Written as a parameter rather than a mutable field so the builder can\n\t\t * stay immutable without a clone method, the same shape\n\t\t * `KyselyDatabase` uses for its derived forms.\n\t\t */\n\t\tprivate readonly dependencies: readonly Dependency[] = [],\n\t) {\n\t\tthis.id = canonicalId(id as string) as TName;\n\t\tthis.keys = { url: provideKey(this.id, 'url') };\n\t}\n\n\t/**\n\t * What this site calls.\n\t *\n\t * Immutable, like every other builder here: it returns a new site rather than\n\t * mutating this one, so a module that exports both a base and a variant of it\n\t * cannot have the second silently change the first.\n\t *\n\t * Takes {@link Declarable} rather than {@link Consumable} because a site's\n\t * edge is a build-time link and not a service injection — requiring a client\n\t * would exclude exactly the surfaces a frontend actually depends on.\n\t */\n\tdependsOn(constructs: readonly Declarable[]): StaticSite<TName> {\n\t\treturn new StaticSite<TName>(this.id as ConstructName<TName>, this.config, [\n\t\t\t...this.dependencies,\n\t\t\t...constructs.map(edgeTo),\n\t\t]);\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'site',\n\t\t\t\tid: this.id,\n\t\t\t\tvariant: this.config.variant ?? 'static',\n\t\t\t\t...(this.config.subdomain ? { subdomain: this.config.subdomain } : {}),\n\t\t\t\tapp: {\n\t\t\t\t\tpath: this.config.path,\n\t\t\t\t\t...(this.config.port ? { port: this.config.port } : {}),\n\t\t\t\t\t...(this.config.config ? { config: this.config.config } : {}),\n\t\t\t\t},\n\t\t\t\t...(this.config.root ? { root: true } : {}),\n\t\t\t\tdependencies: this.dependencies,\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: [this.keys.url],\n\t\t\t},\n\t\t];\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,IAAa,aAAb,MAAa,WAEb;CAMmB;CAOA;CAZlB;CACA;CAEA,YACC,IACA,QAOA,eAAuD,CAAC,GACvD;EARgB,KAAA,SAAA;EAOA,KAAA,eAAA;EAEjB,KAAK,KAAK,YAAY,EAAY;EAClC,KAAK,OAAO,EAAE,KAAK,WAAW,KAAK,IAAI,KAAK,EAAE;CAC/C;;;;;;;;;;;;CAaA,UAAU,YAAsD;EAC/D,OAAO,IAAI,WAAkB,KAAK,IAA4B,KAAK,QAAQ,CAC1E,GAAG,KAAK,cACR,GAAG,WAAW,IAAI,MAAM,CACzB,CAAC;CACF;CAEA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,SAAS,KAAK,OAAO,WAAW;GAChC,GAAI,KAAK,OAAO,YAAY,EAAE,WAAW,KAAK,OAAO,UAAU,IAAI,CAAC;GACpE,KAAK;IACJ,MAAM,KAAK,OAAO;IAClB,GAAI,KAAK,OAAO,OAAO,EAAE,MAAM,KAAK,OAAO,KAAK,IAAI,CAAC;IACrD,GAAI,KAAK,OAAO,SAAS,EAAE,QAAQ,KAAK,OAAO,OAAO,IAAI,CAAC;GAC5D;GACA,GAAI,KAAK,OAAO,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;GACzC,cAAc,KAAK;GACnB,GAAI,KAAK,OAAO,YACb,EAAE,WAAW,KAAK,OAAO,UAAU,GAAG,IACtC,CAAC;GACJ,UAAU,CAAC,KAAK,KAAK,GAAG;EACzB,CACD;CACD;AACD"}
|