@enlitt/sdk 0.0.0-stage → 0.1.1
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/CHANGELOG.md +35 -0
- package/LICENSE +21 -0
- package/README.md +63 -2
- package/dist/browser/auth.d.cts +44 -0
- package/dist/browser/auth.d.ts +45 -0
- package/dist/browser/auth.d.ts.map +1 -0
- package/dist/browser.cjs +35 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.d.cts +12 -0
- package/dist/browser.d.ts +13 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +32 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-2BGWYTJM.cjs +1097 -0
- package/dist/chunk-2BGWYTJM.cjs.map +1 -0
- package/dist/chunk-6OWXYBBT.cjs +146 -0
- package/dist/chunk-6OWXYBBT.cjs.map +1 -0
- package/dist/chunk-NI6WH5FI.js +33 -0
- package/dist/chunk-NI6WH5FI.js.map +1 -0
- package/dist/chunk-O6ASIA3X.js +866 -0
- package/dist/chunk-O6ASIA3X.js.map +1 -0
- package/dist/chunk-PPOUNWNA.cjs +895 -0
- package/dist/chunk-PPOUNWNA.cjs.map +1 -0
- package/dist/chunk-UVZMKGIL.js +1091 -0
- package/dist/chunk-UVZMKGIL.js.map +1 -0
- package/dist/chunk-V5TCSQ7C.js +143 -0
- package/dist/chunk-V5TCSQ7C.js.map +1 -0
- package/dist/chunk-YPA4R65T.cjs +35 -0
- package/dist/chunk-YPA4R65T.cjs.map +1 -0
- package/dist/core/errors.d.cts +262 -0
- package/dist/core/errors.d.ts +263 -0
- package/dist/core/errors.d.ts.map +1 -0
- package/dist/core/index.d.cts +24 -0
- package/dist/core/index.d.ts +25 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/premium.d.cts +230 -0
- package/dist/core/premium.d.ts +231 -0
- package/dist/core/premium.d.ts.map +1 -0
- package/dist/core/session.d.cts +122 -0
- package/dist/core/session.d.ts +123 -0
- package/dist/core/session.d.ts.map +1 -0
- package/dist/core/sse.d.cts +79 -0
- package/dist/core/sse.d.ts +80 -0
- package/dist/core/sse.d.ts.map +1 -0
- package/dist/core/transport.d.cts +223 -0
- package/dist/core/transport.d.ts +224 -0
- package/dist/core/transport.d.ts.map +1 -0
- package/dist/core/usage.d.cts +35 -0
- package/dist/core/usage.d.ts +36 -0
- package/dist/core/usage.d.ts.map +1 -0
- package/dist/core.cjs +77 -0
- package/dist/core.cjs.map +1 -0
- package/dist/core.js +4 -0
- package/dist/core.js.map +1 -0
- package/dist/index.cjs +4 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +16 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/openai/client.d.cts +72 -0
- package/dist/openai/client.d.ts +73 -0
- package/dist/openai/client.d.ts.map +1 -0
- package/dist/openai/index.d.cts +2 -0
- package/dist/openai/index.d.ts +3 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/media.d.cts +108 -0
- package/dist/openai/media.d.ts +109 -0
- package/dist/openai/media.d.ts.map +1 -0
- package/dist/openai.cjs +623 -0
- package/dist/openai.cjs.map +1 -0
- package/dist/openai.js +617 -0
- package/dist/openai.js.map +1 -0
- package/dist/server/callback.d.cts +107 -0
- package/dist/server/callback.d.ts +108 -0
- package/dist/server/callback.d.ts.map +1 -0
- package/dist/server/client-sign-in.d.cts +77 -0
- package/dist/server/client-sign-in.d.ts +78 -0
- package/dist/server/client-sign-in.d.ts.map +1 -0
- package/dist/server/index.d.cts +20 -0
- package/dist/server/index.d.ts +21 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/secrets.d.cts +46 -0
- package/dist/server/secrets.d.ts +47 -0
- package/dist/server/secrets.d.ts.map +1 -0
- package/dist/server-unavailable.cjs +8 -0
- package/dist/server-unavailable.cjs.map +1 -0
- package/dist/server-unavailable.d.cts +10 -0
- package/dist/server-unavailable.d.ts +11 -0
- package/dist/server-unavailable.d.ts.map +1 -0
- package/dist/server-unavailable.js +6 -0
- package/dist/server-unavailable.js.map +1 -0
- package/dist/server.cjs +880 -0
- package/dist/server.cjs.map +1 -0
- package/dist/server.js +795 -0
- package/dist/server.js.map +1 -0
- package/dist/vercel/index.d.cts +17 -0
- package/dist/vercel/index.d.ts +18 -0
- package/dist/vercel/index.d.ts.map +1 -0
- package/dist/vercel/language-model.d.cts +146 -0
- package/dist/vercel/language-model.d.ts +147 -0
- package/dist/vercel/language-model.d.ts.map +1 -0
- package/dist/vercel/premium-language-model.d.cts +127 -0
- package/dist/vercel/premium-language-model.d.ts +128 -0
- package/dist/vercel/premium-language-model.d.ts.map +1 -0
- package/dist/vercel/premium-media-model.d.cts +101 -0
- package/dist/vercel/premium-media-model.d.ts +102 -0
- package/dist/vercel/premium-media-model.d.ts.map +1 -0
- package/dist/vercel/standard-language-model.d.cts +104 -0
- package/dist/vercel/standard-language-model.d.ts +105 -0
- package/dist/vercel/standard-language-model.d.ts.map +1 -0
- package/dist/vercel.cjs +22 -0
- package/dist/vercel.cjs.map +1 -0
- package/dist/vercel.js +5 -0
- package/dist/vercel.js.map +1 -0
- package/package.json +139 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/callback.ts","../src/server/client-sign-in.ts"],"names":["readCookie","pairing"],"mappings":";;;;;;;;AAoGA,IAAM,qBAAA,GAAwB,oBAAA;AAM9B,IAAM,cAAA,GAAiB,wBAAA;AACvB,IAAM,UAAA,GAAa,oBAAA;AACnB,IAAM,WAAA,GAAc,qBAAA;AAMpB,IAAM,eAAA,GAAkB,WAAA;AAGxB,IAAM,YAAA,GAAe,KAAK,EAAA,GAAK,GAAA;AAM/B,IAAM,cAAA,GAAiB,gEAAA;AACvB,IAAM,YAAA,GAAe,EAAA;AAUrB,IAAM,gBAAA,GAAmB,GAAA,GAAO,GAAA,GAAM,cAAA,CAAe,MAAA;AAGrD,IAAM,gBAAA,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I,QAAA,CAAS,UAAA,CAAW,GAAG,QAAQ,CAAA,CAAA,CAAG,CAAA,EAAG,OAAO,QAAA,EAAS;AAC9D,IAAA,MAAM,KAAA,GAAQ,GAAA,CAAI,QAAA,CAAS,KAAA,CAAM,SAAS,MAAM,CAAA;AAChD,IAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,MAAA,CAAO,WAAA,EAAY;AAE1C,IAAA,QAAQ,KAAA;AAAO,MACb,KAAK,QAAA;AACH,QAAA,OAAO,WAAW,KAAA,GAAQ,KAAA,CAAM,GAAG,CAAA,GAAI,iBAAiB,KAAK,CAAA;AAAA,MAC/D,KAAK,WAAA;AACH,QAAA,OAAO,WAAW,KAAA,GAAQ,QAAA,CAAS,SAAS,GAAG,CAAA,GAAI,iBAAiB,KAAK,CAAA;AAAA,MAC3E,KAAK,QAAA;AACH,QAAA,OAAO,WAAW,MAAA,GAAS,KAAA,CAAM,OAAO,CAAA,GAAI,iBAAiB,MAAM,CAAA;AAAA,MACrE,KAAK,SAAA;AACH,QAAA,OAAO,WAAW,MAAA,GAAS,MAAA,CAAO,OAAO,CAAA,GAAI,iBAAiB,MAAM,CAAA;AAAA,MACtE,KAAK,UAAA;AACH,QAAA,IAAI,CAAC,cAAA,EAAgB,OAAO,QAAA,EAAS;AACrC,QAAA,OAAO,WAAW,MAAA,GAAS,OAAA,CAAQ,OAAO,CAAA,GAAI,iBAAiB,MAAM,CAAA;AAAA,MACvE,KAAK,OAAA;AACH,QAAA,IAAI,CAAC,cAAA,EAAgB,OAAO,QAAA,EAAS;AACrC,QAAA,OAAO,MAAA,KAAW,SAAS,MAAA,KAAW,MAAA,GAClC,KAAK,OAAO,CAAA,GACZ,iBAAiB,WAAW,CAAA;AAAA,MAClC;AACE,QAAA,OAAO,QAAA,EAAS;AAAA;AACpB,EACF,CAAA;AACF","file":"server.js","sourcesContent":["/**\n * The authorization callback a business mounts at its registered redirect URL,\n * and the one place a consumer session token becomes a cookie.\n *\n * This is the mint end of the token's lifecycle. Login-start issues the\n * `state`, the callback validates it, exchanges the one-time code with Enlitt\n * authenticated by the business's own secret key, and sets the resulting\n * opaque session token as an HttpOnly, Secure, SameSite=Lax cookie on the\n * business's own domain. Reading that cookie back on later requests is\n * `./session.ts`, which SDK-side routing owns and which also owns the\n * cookie's name: the mint end and the read end of one cookie cannot disagree,\n * so the default comes from there rather than from a second literal here.\n *\n * The core here is framework-agnostic over `Request` and `Response`;\n * per-framework adapters are separate entry points over this same core, so\n * behaviour cannot drift between frameworks.\n *\n * Invariants this file exists to hold:\n *\n * - No cookie is ever set from an unverified value, and no token supplied in\n * the callback request itself is ever honoured — the only source of a\n * session token is the authenticated exchange response.\n * - The token and the one-time code are never written into a URL, a redirect\n * target, a log line, a trace, or an error body. Nothing in this file\n * prints.\n * - Every onward redirect resolves to `appOrigin` or is replaced by\n * `defaultReturnTo`, so a login link can never become an open redirect.\n * - A rejected `state`, a failed exchange, or an Enlitt error yields a\n * signed-out outcome and no cookie. A rejected `state` lands on\n * `defaultReturnTo`; after a live `state`, the stored `returnTo`.\n */\n\nimport { resolveBusinessAuthorizationHeader } from \"./secrets.js\";\nimport { ENLITT_SESSION_COOKIE_NAME } from \"../core/session.js\";\nimport { ENLITT_API_VERSION, ENLITT_VERSION_HEADER, validateAuthorizationExchangeResponse } from \"@enlitt/protocol\";\n\n/** A store may be synchronous (an in-process map) or asynchronous (Redis). */\ntype Awaitable<T> = T | Promise<T>;\n\n/**\n * What login-start remembers about a pending login, server-side.\n *\n * The post-login destination is captured here rather than carried through the\n * round trip in a parameter the callback reads back, so a crafted callback URL\n * has nothing to say about where the consumer lands.\n */\nexport interface StateRecord {\n /** The destination requested at login-start, still unvalidated. */\n readonly returnTo?: string;\n readonly createdAt: number;\n readonly expiresAt: number;\n}\n\n/**\n * Server-side storage for issued `state` values, with a TTL.\n *\n * `consume` must be single-use: it returns the record and removes it in one\n * step, so a replayed callback finds nothing. `get` exists for callers that\n * need to inspect a pending login without spending it; the callback handler\n * never uses it.\n */\nexport interface StateStore {\n set(state: string, record: StateRecord, ttlMs: number): Awaitable<void>;\n get(state: string): Awaitable<StateRecord | null>;\n consume(state: string): Awaitable<StateRecord | null>;\n}\n\nexport interface CallbackConfig {\n readonly clientId: string;\n /** Falls back to `ENLITT_SECRET_KEY`; never reaches a browser bundle. */\n readonly secretKey?: string;\n /** Must equal a registered redirect URI exactly. */\n readonly redirectUri: string;\n /** Enlitt's authorization origin (the dashboard host). Defaults to the deployed one. */\n readonly enlittOrigin?: string;\n /**\n * Origin for the two server-to-server requests (code exchange and\n * revocation). Defaults to `enlittOrigin`. A server running as a Cloudflare\n * Worker in Enlitt's own zone must pass the API host: Cloudflare does not run\n * the route-bound Worker behind `enlittOrigin/auth/*` for a same-zone Worker\n * subrequest, so the exchange would reach the wrong Worker and fail.\n */\n readonly enlittApiOrigin?: string;\n /** The business's own origin. It bounds every redirect this file emits. */\n readonly appOrigin: string;\n /** Path on `appOrigin`, used whenever no valid destination survives. */\n readonly defaultReturnTo: string;\n readonly cookieName?: string;\n readonly stateStore: StateStore;\n /** Link your own user/session before login completes; no token is passed. */\n readonly onSignIn?: (identity: { readonly subject: string }, response: Response) => Awaitable<void>;\n}\n\n/**\n * The deployed Enlitt authorization origin: the dashboard host, not the model\n * API host. The consumer's browser is sent to `AUTHORIZE_PATH` here, and only\n * this host carries the consumer's Enlitt dashboard session cookie, so an\n * authorize request sent to the API host would always find the consumer\n * signed out. Model calls keep their own default in `../language-model.ts`.\n */\nconst DEFAULT_ENLITT_ORIGIN = \"https://enlitt.com\";\n\n/**\n * Enlitt's authorization-server endpoints, under the `/auth/*` prefix the\n * backend serves.\n */\nconst AUTHORIZE_PATH = \"/auth/oauth2/authorize\";\nconst TOKEN_PATH = \"/auth/oauth2/token\";\nconst REVOKE_PATH = \"/auth/oauth2/revoke\";\n\n/**\n * The query parameter carrying a post-flow destination. `../browser/auth.ts`\n * writes this name; this file is the only place its value is validated.\n */\nconst RETURN_TO_PARAM = \"return_to\";\n\n/** How long an issued `state` stays redeemable. */\nconst STATE_TTL_MS = 10 * 60 * 1000;\n\n/**\n * The `state` alphabet and length: 32 symbols over 62 characters is a little\n * over 190 bits.\n */\nconst STATE_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\nconst STATE_LENGTH = 32;\n\n/**\n * The largest multiple of the alphabet size that fits in a byte.\n *\n * Bytes at or above this bound are discarded rather than reduced. A plain\n * `byte % 62` would map the first `256 % 62` symbols more often than the rest,\n * which silently costs entropy in a value whose only job is to be unguessable;\n * rejecting the tail is what makes the distribution exactly uniform.\n */\nconst STATE_BYTE_LIMIT = 256 - (256 % STATE_ALPHABET.length);\n\n/** A cookie name: an HTTP token. */\nconst SAFE_COOKIE_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\n\n/**\n * Generate one `state` value from a cryptographically secure source, uniformly\n * over `STATE_ALPHABET`.\n */\nfunction generateState(): string {\n const source = (globalThis as { crypto?: Crypto }).crypto;\n if (!source?.getRandomValues) {\n throw new Error(\n \"@enlitt/sdk: no Web Crypto implementation is available, so no unguessable \" +\n \"login state can be generated. Node 20+, Deno, Bun, and Workers all provide one.\"\n );\n }\n\n let out = \"\";\n while (out.length < STATE_LENGTH) {\n // Over-draw: on average about 3% of bytes are rejected, so asking for a\n // little more than is needed usually finishes in one draw.\n const bytes = source.getRandomValues(new Uint8Array(STATE_LENGTH));\n for (const byte of bytes) {\n if (byte >= STATE_BYTE_LIMIT) continue;\n out += STATE_ALPHABET[byte % STATE_ALPHABET.length];\n if (out.length === STATE_LENGTH) break;\n }\n }\n return out;\n}\n\n/**\n * Reduce a requested destination to a path on `appOrigin`, or reject it.\n *\n * The checks run on the raw form and on its single-decoded form, because a\n * server or proxy in front of the business may decode once before anything\n * else sees the value: `%2f%2fevil.com` is `//evil.com` to whoever decodes it,\n * and a scheme-relative target resolves to another origin. A traversal segment\n * is refused outright rather than normalised, since a destination that has to\n * climb out of a path is never a destination this handler was asked for.\n */\nfunction safeReturnPath(target: string | null | undefined, appOrigin: string): string | null {\n if (typeof target !== \"string\" || target.length === 0) return null;\n\n let decoded: string;\n try {\n decoded = decodeURIComponent(target);\n } catch {\n // A malformed escape is not a destination.\n return null;\n }\n\n for (const form of [target, decoded]) {\n if (!form.startsWith(\"/\")) return null;\n if (form.startsWith(\"//\") || form.startsWith(\"/\\\\\")) return null;\n if (form.includes(\"\\\\\")) return null;\n if (form.split(/[/?#]/).includes(\"..\")) return null;\n // Control characters, including a bare CR or LF, would split a `Location`\n // header. Checked by code point rather than by regex so the bytes being\n // refused are visible in the source rather than embedded in it.\n for (let i = 0; i < form.length; i += 1) {\n const point = form.charCodeAt(i);\n if (point < 0x20 || point === 0x7f) return null;\n }\n }\n\n let resolved: URL;\n let base: URL;\n try {\n base = new URL(appOrigin);\n resolved = new URL(target, base);\n } catch {\n return null;\n }\n // Belt and braces: whatever the parser made of it must still be here.\n if (resolved.origin !== base.origin) return null;\n\n return `${resolved.pathname}${resolved.search}${resolved.hash}`;\n}\n\ninterface ResolvedConfig {\n readonly clientId: string;\n readonly secretKey?: string;\n readonly redirectUri: string;\n readonly enlittOrigin: string;\n readonly enlittApiOrigin: string;\n readonly appOrigin: string;\n readonly defaultReturnTo: string;\n readonly cookieName: string;\n readonly stateStore: StateStore;\n readonly onSignIn?: NonNullable<CallbackConfig[\"onSignIn\"]>;\n}\n\n/**\n * Validate the configuration once, when the handler is built, rather than on\n * the first consumer request. A malformed origin is a deployment mistake and\n * should fail at boot.\n */\nfunction resolveConfig(config: CallbackConfig): ResolvedConfig {\n if (config.onSignIn !== undefined && typeof config.onSignIn !== \"function\") {\n throw new Error(\"@enlitt/sdk: onSignIn must be a function.\");\n }\n if (config.clientId.length === 0) {\n throw new Error(\"@enlitt/sdk: clientId is required.\");\n }\n\n let appOrigin: string;\n try {\n appOrigin = new URL(config.appOrigin).origin;\n } catch {\n throw new Error(\"@enlitt/sdk: appOrigin must be an absolute origin, e.g. https://app.example.com.\");\n }\n if (appOrigin === \"null\") {\n throw new Error(\"@enlitt/sdk: appOrigin must be an absolute origin, e.g. https://app.example.com.\");\n }\n\n let enlittOrigin: string;\n try {\n enlittOrigin = new URL(config.enlittOrigin ?? DEFAULT_ENLITT_ORIGIN).origin;\n } catch {\n throw new Error(\"@enlitt/sdk: enlittOrigin must be an absolute origin.\");\n }\n\n let enlittApiOrigin: string;\n try {\n enlittApiOrigin = new URL(config.enlittApiOrigin ?? enlittOrigin).origin;\n } catch {\n throw new Error(\"@enlitt/sdk: enlittApiOrigin must be an absolute origin.\");\n }\n\n try {\n void new URL(config.redirectUri);\n } catch {\n throw new Error(\"@enlitt/sdk: redirectUri must be the absolute URL registered with Enlitt.\");\n }\n\n const defaultReturnTo = safeReturnPath(config.defaultReturnTo, appOrigin);\n if (defaultReturnTo === null) {\n throw new Error(\"@enlitt/sdk: defaultReturnTo must be a path on appOrigin, e.g. \\\"/\\\".\");\n }\n\n const cookieName = config.cookieName ?? ENLITT_SESSION_COOKIE_NAME;\n if (!SAFE_COOKIE_NAME.test(cookieName)) {\n throw new Error(\"@enlitt/sdk: cookieName must be a valid cookie name.\");\n }\n\n const resolved: ResolvedConfig = {\n clientId: config.clientId,\n redirectUri: config.redirectUri,\n enlittOrigin,\n enlittApiOrigin,\n appOrigin,\n defaultReturnTo,\n cookieName,\n stateStore: config.stateStore,\n ...(config.onSignIn === undefined ? {} : { onSignIn: config.onSignIn })\n };\n // `exactOptionalPropertyTypes` keeps an absent secret absent rather than\n // present-and-undefined, so the fallback in `secrets.ts` still fires.\n return config.secretKey === undefined ? resolved : { ...resolved, secretKey: config.secretKey };\n}\n\nfunction redirectTo(location: string, cookie?: string): Response {\n const headers = new Headers({\n location,\n // A login outcome is never a cacheable page.\n \"cache-control\": \"no-store\"\n });\n if (cookie !== undefined) headers.append(\"set-cookie\", cookie);\n // 303: whatever the callback's method was, the consumer now GETs a page.\n return new Response(null, { status: 303, headers });\n}\n\nfunction sessionCookie(name: string, value: string, maxAgeSeconds?: number): string {\n const parts = [`${name}=${value}`, \"Path=/\", \"HttpOnly\", \"Secure\", \"SameSite=Lax\"];\n if (maxAgeSeconds !== undefined) parts.push(`Max-Age=${String(maxAgeSeconds)}`);\n return parts.join(\"; \");\n}\n\nfunction clearedCookie(name: string): string {\n return [\n `${name}=`,\n \"Path=/\",\n \"HttpOnly\",\n \"Secure\",\n \"SameSite=Lax\",\n \"Max-Age=0\",\n \"Expires=Thu, 01 Jan 1970 00:00:00 GMT\"\n ].join(\"; \");\n}\n\nfunction readCookie(request: Request, name: string): string | null {\n const header = request.headers.get(\"cookie\");\n if (header === null) return null;\n for (const pair of header.split(\";\")) {\n const separator = pair.indexOf(\"=\");\n if (separator === -1) continue;\n if (pair.slice(0, separator).trim() !== name) continue;\n const value = pair.slice(separator + 1).trim();\n return value.length === 0 ? null : value;\n }\n return null;\n}\n\n/**\n * The exchange response, read defensively.\n *\n * The credential remains opaque. The separately verified subject links the\n * application's own user database and never becomes part of that credential.\n */\ninterface ExchangeResult {\n readonly sessionToken: string;\n readonly subject: string;\n readonly expiresInSeconds?: number;\n}\n\nfunction readExchangeResult(payload: unknown): ExchangeResult | null {\n const parsed = validateAuthorizationExchangeResponse(payload, { mode: \"tolerant\" });\n if (!parsed.ok) return null;\n const body = payload as Record<string, unknown>;\n const identity = { sessionToken: parsed.value.session_token, subject: parsed.value.subject };\n\n const expiresIn = body.expires_in;\n if (typeof expiresIn === \"number\" && Number.isInteger(expiresIn) && expiresIn > 0) {\n return { ...identity, expiresInSeconds: expiresIn };\n }\n return identity;\n}\n\n/**\n * Exchange the one-time code, authenticated as a confidential client.\n *\n * Returns `null` for every failure. No branch here reports what Enlitt said:\n * the code and the token must not reach a log, a trace, or an error body, and\n * the caller's only decision is signed in or signed out.\n */\nasync function exchangeCode(config: ResolvedConfig, code: string): Promise<ExchangeResult | null> {\n // Resolved before the request is built. A business with no secret gets a\n // local failure rather than an unauthenticated exchange attempt.\n const authorization = resolveBusinessAuthorizationHeader(\n config.secretKey === undefined ? {} : { secretKey: config.secretKey }\n );\n\n const body = new URLSearchParams({\n grant_type: \"authorization_code\",\n code,\n redirect_uri: config.redirectUri,\n client_id: config.clientId\n });\n\n let response: Response;\n try {\n response = await fetch(new URL(TOKEN_PATH, config.enlittApiOrigin), {\n method: \"POST\",\n headers: {\n authorization,\n [ENLITT_VERSION_HEADER]: ENLITT_API_VERSION,\n \"content-type\": \"application/x-www-form-urlencoded\",\n accept: \"application/json\"\n },\n body\n });\n } catch {\n return null;\n }\n\n if (!response.ok) return null;\n\n try {\n return readExchangeResult(await response.json());\n } catch {\n return null;\n }\n}\n\n/**\n * Begin login: issue a `state`, remember it server-side, and send the consumer\n * to Enlitt's authorization endpoint.\n */\nexport function createLoginStartHandler(config: CallbackConfig): (request: Request) => Promise<Response> {\n const resolved = resolveConfig(config);\n\n return async function handleLoginStart(request: Request): Promise<Response> {\n const state = generateState();\n const now = Date.now();\n const requested = new URL(request.url).searchParams.get(RETURN_TO_PARAM);\n\n const base = { createdAt: now, expiresAt: now + STATE_TTL_MS };\n // The raw request is stored, not a validated one: validation happens where\n // the value is used, so a stored value can never be mistaken for a checked\n // one.\n await resolved.stateStore.set(\n state,\n requested === null ? base : { ...base, returnTo: requested },\n STATE_TTL_MS\n );\n\n const authorize = new URL(AUTHORIZE_PATH, resolved.enlittOrigin);\n authorize.searchParams.set(\"response_type\", \"code\");\n authorize.searchParams.set(\"client_id\", resolved.clientId);\n authorize.searchParams.set(\"redirect_uri\", resolved.redirectUri);\n authorize.searchParams.set(\"state\", state);\n\n return redirectTo(authorize.toString());\n };\n}\n\n/**\n * Receive Enlitt's callback: validate `state`, exchange the code, set the one\n * cookie, and send the consumer onward within `appOrigin`.\n */\nexport function createCallbackHandler(config: CallbackConfig): (request: Request) => Promise<Response> {\n const resolved = resolveConfig(config);\n const signedOut = (): Response =>\n redirectTo(new URL(resolved.defaultReturnTo, resolved.appOrigin).toString());\n\n return async function handleCallback(request: Request): Promise<Response> {\n const params = new URL(request.url).searchParams;\n\n // `state` first, and spent before anything else happens: a missing,\n // unknown, replayed, or expired value must be refused before an exchange\n // is attempted, not after.\n const state = params.get(\"state\");\n if (state === null || state.length === 0) return signedOut();\n\n const record = await resolved.stateStore.consume(state);\n if (record === null) return signedOut();\n if (record.expiresAt <= Date.now()) return signedOut();\n\n // From here on the `state` record is trusted, so every outcome — signed in\n // or not — goes to the page the consumer was heading for. A signed-out\n // arrival there carries no cookie; the page sees no session and acts on\n // it (client sign-in's `complete` reports `access_denied` this way).\n const destination =\n safeReturnPath(record.returnTo, resolved.appOrigin) ?? resolved.defaultReturnTo;\n const signedOutToDestination = (): Response =>\n redirectTo(new URL(destination, resolved.appOrigin).toString());\n\n // An `error` from Enlitt, or no code at all, ends the flow here. Nothing\n // else in the request can stand in for the code — a token parameter on the\n // callback URL is never read, because the only source of a session token\n // is the authenticated exchange below.\n if (params.get(\"error\") !== null) return signedOutToDestination();\n const code = params.get(\"code\");\n if (code === null || code.length === 0) return signedOutToDestination();\n\n const exchanged = await exchangeCode(resolved, code);\n if (exchanged === null) return signedOutToDestination();\n\n const response = redirectTo(new URL(destination, resolved.appOrigin).toString());\n // The application's session must be ready before the browser receives an\n // Enlitt credential. Propagate setup errors to its server, preserving the\n // original cause; never return a successful login after a failed hook.\n await resolved.onSignIn?.({ subject: exchanged.subject }, response);\n response.headers.append(\"set-cookie\", sessionCookie(resolved.cookieName, exchanged.sessionToken, exchanged.expiresInSeconds));\n return response;\n };\n}\n\n/**\n * End the session: clear the cookie and ask Enlitt to revoke the token.\n *\n * Revocation is what makes the opaque token worth its lookup, so a signed-out\n * consumer is signed out server-side and not merely cookie-less. A revocation\n * that fails still clears the cookie: leaving the consumer holding a cookie\n * because Enlitt was briefly unreachable would be the worse of the two\n * outcomes, and the token stays revocable from the dashboard.\n */\nexport function createLogoutHandler(config: CallbackConfig): (request: Request) => Promise<Response> {\n const resolved = resolveConfig(config);\n\n return async function handleLogout(request: Request): Promise<Response> {\n const token = readCookie(request, resolved.cookieName);\n\n if (token !== null) {\n try {\n const authorization = resolveBusinessAuthorizationHeader(\n resolved.secretKey === undefined ? {} : { secretKey: resolved.secretKey }\n );\n await fetch(new URL(REVOKE_PATH, resolved.enlittApiOrigin), {\n method: \"POST\",\n headers: {\n authorization,\n [ENLITT_VERSION_HEADER]: ENLITT_API_VERSION,\n \"content-type\": \"application/x-www-form-urlencoded\",\n accept: \"application/json\"\n },\n // The token travels in the body, never in the URL.\n body: new URLSearchParams({ token, client_id: resolved.clientId })\n });\n } catch {\n // Deliberately swallowed and never reported: the outcome is the same\n // either way, and an error body here is a place a token could leak.\n }\n }\n\n const requested = new URL(request.url).searchParams.get(RETURN_TO_PARAM);\n const destination = safeReturnPath(requested, resolved.appOrigin) ?? resolved.defaultReturnTo;\n\n return redirectTo(\n new URL(destination, resolved.appOrigin).toString(),\n clearedCookie(resolved.cookieName)\n );\n };\n}\n","/**\n * Client sign-in handoff: the business-hosted half of signing in a game or\n * native client that has no cookie jar and no secret.\n *\n * The wire is `specs/PROTOCOLS.md` \"Client sign-in handoff\"; the behavior is\n * `specs/Account.md` \"Client sign-in handoff\". In short, the business's own\n * backend runs the ordinary Enlitt login in the player's browser (through the\n * existing `createLoginStartHandler` / `createCallbackHandler` pair), then hands\n * the resulting opaque session token to the client over a PKCE-protected\n * one-time code (loopback, deep link) or a device-style pairing code. Enlitt sees\n * only its unchanged authorization, code exchange, and revocation routes.\n *\n * One handler serves every path under `basePath`:\n *\n * GET <base>/start begin a loopback or deep-link sign-in\n * GET <base>/complete reached only through the business's own callback redirect\n * POST <base>/pairing begin a pairing (device-style) sign-in\n * GET/POST <base>/pair the HTML pages the person opens on another device\n * POST <base>/token the client trades a code or pairing for the session token\n * POST <base>/logout the client ends its session\n *\n * The session token leaves this file only in the `token` response body. It is\n * never written to a URL, a page, a log, or an error.\n */\n\nimport { createHash, randomBytes, randomInt, timingSafeEqual } from \"node:crypto\";\nimport {\n ENLITT_SESSION_COOKIE_NAME,\n ENLITT_SESSION_HEADER_NAME,\n EnlittConfigurationError\n} from \"../core/index.js\";\nimport { createLoginStartHandler, createLogoutHandler, type CallbackConfig } from \"./callback.js\";\n\ntype Awaitable<T> = T | Promise<T>;\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Server-side storage for handoffs, codes, and pairings. Values are opaque\n * strings: the handler owns their format (JSON it writes and parses itself).\n * Like `StateStore`, it must be shared across processes in a multi-process\n * deployment. `consume` is an atomic read-and-delete, which is what makes a code\n * single-use.\n */\nexport interface ClientSignInStore {\n /** Stores `value` under `key`, overwriting any existing value, for `ttlMs`. */\n set(key: string, value: string, ttlMs: number): Awaitable<void>;\n get(key: string): Awaitable<string | null>;\n consume(key: string): Awaitable<string | null>;\n}\n\nexport interface ClientSignInConfig {\n /** The same object the login-start, callback, and logout handlers are mounted with. */\n readonly callback: CallbackConfig;\n /** Path on `callback.appOrigin`, e.g. `/enlitt/client`; no trailing slash. */\n readonly basePath: string;\n /** Shown on the pairing pages (1-60 characters). */\n readonly appName: string;\n /** Allow `mode=loopback` sign-ins to `127.0.0.1`. Defaults to true. */\n readonly loopback?: boolean;\n /** Exact deep-link targets allowed for `mode=redirect`. Defaults to none. */\n readonly returnUrls?: readonly string[];\n /** Serve the pairing routes. Defaults to false. */\n readonly pairing?: boolean;\n /** Shared across processes, like `callback.stateStore`. */\n readonly store: ClientSignInStore;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** How long a started sign-in (the handoff) may take, and how long a pairing lives. */\nconst HANDOFF_TTL_MS = 10 * 60 * 1000;\nconst PAIRING_TTL_MS = 10 * 60 * 1000;\n/** How long a one-time code may wait for the client to redeem it. */\nconst CODE_TTL_MS = 5 * 60 * 1000;\n/** Seconds a pairing client waits between `token` polls. */\nconst PAIRING_INTERVAL_SECONDS = 5;\n\n/** Pairing user codes: 8 letters from an alphabet with no vowels and no look-alikes. */\nconst USER_CODE_ALPHABET = \"BCDFGHJKLMNPQRSTVWXZ\";\nconst USER_CODE_LENGTH = 8;\n\n/** The CSRF double-submit cookie of the pairing pages. */\nconst CSRF_COOKIE_NAME = \"enlitt_pair_csrf\";\n\n/** Value rules from PROTOCOLS \"Client sign-in handoff / Shared value rules\". */\nconst STATE_PATTERN = /^[A-Za-z0-9._~-]{1,128}$/;\nconst CODE_VERIFIER_PATTERN = /^[A-Za-z0-9._~-]{43,128}$/;\nconst CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;\n/** Codes and pairing IDs are 32 random bytes in unpadded base64url. */\nconst RANDOM_ID_PATTERN = /^[A-Za-z0-9_-]{43}$/;\n\n/** Schemes a private-use `returnUrls` entry may never use. */\nconst FORBIDDEN_SCHEMES = new Set([\"http\", \"javascript\", \"data\", \"file\", \"vbscript\"]);\n\n/** Longest `Enlitt-Session` header value `logout` forwards. */\nconst MAX_LOGOUT_TOKEN_LENGTH = 4096;\n\n// ---------------------------------------------------------------------------\n// Stored record shapes (JSON the handler writes and parses itself)\n// ---------------------------------------------------------------------------\n\ntype HandoffTarget =\n | { readonly mode: \"loopback\"; readonly port: number }\n | { readonly mode: \"redirect\"; readonly redirectUri: string }\n | { readonly mode: \"pairing\"; readonly pairingId: string };\n\n/** `h:<id>`: a started sign-in, waiting for the business's callback redirect. */\ninterface Handoff {\n readonly target: HandoffTarget;\n /** Echoed to loopback/redirect targets; absent for pairing. */\n readonly state?: string;\n readonly codeChallenge: string;\n}\n\n/** `c:<code>`: a one-time code waiting for the client to redeem it. */\ninterface CodeRecord {\n readonly sessionToken: string;\n readonly codeChallenge: string;\n}\n\n/** `p:<pairing id>` (and `u:<user code>` pointing at it). */\ninterface PairingRecord {\n readonly status: \"pending\" | \"ready\" | \"denied\";\n readonly codeChallenge: string;\n readonly userCode: string;\n readonly sessionToken?: string;\n /** Absolute expiry in epoch ms, so an update can keep the time left. */\n readonly expiresAt: number;\n}\n\n// ---------------------------------------------------------------------------\n// In-memory store (development only)\n// ---------------------------------------------------------------------------\n\n/** Options for `createMemoryClientSignInStore()`. */\nexport interface MemoryClientSignInStoreOptions {\n /** Clock in epoch milliseconds; defaults to `Date.now`. Tests inject one. */\n readonly now?: () => number;\n}\n\n/**\n * A `ClientSignInStore` held in this process's memory, for development and\n * tests. It does NOT work across processes or restarts: a code started on one\n * server instance cannot be redeemed on another. Production uses a shared store\n * (Redis, a database) implementing the same three methods.\n */\nexport function createMemoryClientSignInStore(\n options: MemoryClientSignInStoreOptions = {}\n): ClientSignInStore {\n const now = options.now ?? Date.now;\n const entries = new Map<string, { value: string; expiresAt: number }>();\n\n /** Reads a live entry, dropping it first when its TTL has passed. */\n function live(key: string): { value: string; expiresAt: number } | undefined {\n const entry = entries.get(key);\n if (entry !== undefined && entry.expiresAt <= now()) {\n entries.delete(key);\n return undefined;\n }\n return entry;\n }\n\n return {\n set(key, value, ttlMs) {\n // Opportunistic sweep so abandoned sign-ins do not accumulate forever.\n if (entries.size > 1000) {\n for (const existing of [...entries.keys()]) live(existing);\n }\n entries.set(key, { value, expiresAt: now() + ttlMs });\n },\n get(key) {\n return live(key)?.value ?? null;\n },\n consume(key) {\n const entry = live(key);\n entries.delete(key);\n return entry?.value ?? null;\n }\n };\n}\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\n/** 32 cryptographically random bytes as 43 characters of unpadded base64url. */\nfunction randomId(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\n/** `base64url(SHA-256(ASCII(verifier)))`: the PKCE S256 transform. */\nfunction challengeOf(verifier: string): string {\n return createHash(\"sha256\").update(verifier, \"ascii\").digest(\"base64url\");\n}\n\n/** Constant-time string equality; unequal lengths are simply unequal. */\nfunction safeEqual(left: string, right: string): boolean {\n const a = Buffer.from(left);\n const b = Buffer.from(right);\n return a.length === b.length && timingSafeEqual(a, b);\n}\n\n/**\n * A user code: 8 letters from `USER_CODE_ALPHABET`. `randomInt` draws by\n * rejection sampling, so no letter is more likely than another.\n */\nfunction randomUserCode(): string {\n let code = \"\";\n for (let i = 0; i < USER_CODE_LENGTH; i += 1) {\n code += USER_CODE_ALPHABET[randomInt(USER_CODE_ALPHABET.length)];\n }\n return code;\n}\n\n/** `ABCDEFGH` shown as `ABCD-EFGH`. */\nfunction formatUserCode(code: string): string {\n return `${code.slice(0, 4)}-${code.slice(4)}`;\n}\n\n/** Uppercases and drops every non-letter, so people may type `abcd efgh`. */\nfunction normalizeUserCode(input: string): string {\n return input.toUpperCase().replace(/[^A-Z]/g, \"\");\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n\n/** Parses a stored JSON object, or null for anything else (never throws). */\nfunction parseRecord(text: string | null): Record<string, unknown> | null {\n if (text === null) return null;\n try {\n const parsed: unknown = JSON.parse(text);\n return typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\nfunction readHandoff(text: string | null): Handoff | null {\n const record = parseRecord(text);\n if (record === null || typeof record.codeChallenge !== \"string\") return null;\n const target = record.target as Record<string, unknown> | null | undefined;\n if (typeof target !== \"object\" || target === null) return null;\n if (target.mode === \"loopback\" && typeof target.port === \"number\") {\n return record as unknown as Handoff;\n }\n if (target.mode === \"redirect\" && typeof target.redirectUri === \"string\") {\n return record as unknown as Handoff;\n }\n if (target.mode === \"pairing\" && typeof target.pairingId === \"string\") {\n return record as unknown as Handoff;\n }\n return null;\n}\n\nfunction readCode(text: string | null): CodeRecord | null {\n const record = parseRecord(text);\n if (\n record === null ||\n typeof record.sessionToken !== \"string\" ||\n typeof record.codeChallenge !== \"string\"\n ) {\n return null;\n }\n return { sessionToken: record.sessionToken, codeChallenge: record.codeChallenge };\n}\n\nfunction readPairing(text: string | null): PairingRecord | null {\n const record = parseRecord(text);\n if (\n record === null ||\n (record.status !== \"pending\" && record.status !== \"ready\" && record.status !== \"denied\") ||\n typeof record.codeChallenge !== \"string\" ||\n typeof record.userCode !== \"string\" ||\n typeof record.expiresAt !== \"number\"\n ) {\n return null;\n }\n return record as unknown as PairingRecord;\n}\n\n/** Reads one cookie off the request's `Cookie` header, or null. */\nfunction readCookie(request: Request, name: string): string | null {\n const header = request.headers.get(\"cookie\");\n if (header === null) return null;\n for (const part of header.split(\";\")) {\n const separator = part.indexOf(\"=\");\n if (separator === -1 || part.slice(0, separator).trim() !== name) continue;\n const raw = part.slice(separator + 1).trim();\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n }\n return null;\n}\n\n/** Security headers every HTML page carries. */\nconst PAGE_HEADERS: Readonly<Record<string, string>> = {\n \"Content-Type\": \"text/html; charset=utf-8\",\n \"Cache-Control\": \"no-store\",\n \"X-Frame-Options\": \"DENY\",\n \"Content-Security-Policy\":\n \"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'\",\n \"Referrer-Policy\": \"no-referrer\"\n};\n\n/** Wraps `body` (already-escaped HTML) in a minimal page and security headers. */\nfunction htmlPage(\n status: number,\n title: string,\n body: string,\n extraHeaders: Headers = new Headers()\n): Response {\n const html =\n `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">` +\n `<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">` +\n `<title>${escapeHtml(title)}</title>` +\n `<style>body{font-family:system-ui,sans-serif;max-width:32rem;margin:3rem auto;padding:0 1rem;line-height:1.5}` +\n `button,input{font:inherit;padding:.5rem 1rem;margin:.25rem 0}.code{font-size:2rem;letter-spacing:.2em;font-weight:600}</style>` +\n `</head><body>${body}</body></html>`;\n const headers = new Headers(extraHeaders);\n for (const [name, value] of Object.entries(PAGE_HEADERS)) headers.set(name, value);\n return new Response(html, { status, headers });\n}\n\n/** The plain `400` page for a refused `start`. It echoes nothing the client sent. */\nfunction invalidRequestPage(): Response {\n return htmlPage(\n 400,\n \"Sign-in unavailable\",\n \"<p>This sign-in request is not valid. Go back to the app and try again.</p>\"\n );\n}\n\nfunction expiredPage(): Response {\n return htmlPage(\n 400,\n \"Sign-in expired\",\n \"<p>This sign-in link has expired. Go back to the app and try again.</p>\"\n );\n}\n\n/** A JSON response that is never cached. */\nfunction jsonResponse(status: number, body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", \"Cache-Control\": \"no-store\" }\n });\n}\n\nfunction tokenError(error: string): Response {\n return jsonResponse(400, { error });\n}\n\n/** Parses a JSON request body that must be an object, or null. */\nasync function readJsonObject(request: Request): Promise<Record<string, unknown> | null> {\n const contentType = request.headers.get(\"content-type\") ?? \"\";\n if (!contentType.toLowerCase().startsWith(\"application/json\")) return null;\n try {\n const parsed: unknown = await request.json();\n return typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\n/** True when `object` has exactly the keys in `keys`. */\nfunction hasExactKeys(object: Record<string, unknown>, keys: readonly string[]): boolean {\n const actual = Object.keys(object);\n return (\n actual.length === keys.length &&\n keys.every((key) => Object.prototype.hasOwnProperty.call(object, key))\n );\n}\n\n// ---------------------------------------------------------------------------\n// Construction checks\n// ---------------------------------------------------------------------------\n\n/**\n * Checks one `returnUrls` entry: an absolute URL without a fragment that is\n * either `https:` or a private-use reverse-DNS scheme (lowercase, containing a\n * `.`, and not a scheme a browser would treat specially).\n */\nfunction checkReturnUrl(entry: string): void {\n const refuse = (): never => {\n throw new EnlittConfigurationError(\n `createClientSignInHandler(): returnUrls entry ${JSON.stringify(entry)} must be an absolute ` +\n \"https: URL or a private-use reverse-DNS scheme (for example com.example.game://auth), without a fragment.\"\n );\n };\n if (typeof entry !== \"string\" || entry.includes(\"#\")) return refuse();\n try {\n new URL(entry);\n } catch {\n return refuse();\n }\n const colon = entry.indexOf(\":\");\n const scheme = entry.slice(0, colon);\n if (scheme === \"https\") return;\n if (!/^[a-z][a-z0-9-]*(\\.[a-z0-9-]+)+$/.test(scheme) || FORBIDDEN_SCHEMES.has(scheme)) {\n return refuse();\n }\n}\n\nfunction checkConfig(config: ClientSignInConfig): void {\n const { basePath } = config;\n if (\n typeof basePath !== \"string\" ||\n !basePath.startsWith(\"/\") ||\n basePath.endsWith(\"/\") ||\n basePath.includes(\"?\") ||\n basePath.includes(\"#\")\n ) {\n throw new EnlittConfigurationError(\n \"createClientSignInHandler(): basePath must start with '/', must not end with '/', \" +\n \"and must not contain '?' or '#'.\"\n );\n }\n for (const entry of config.returnUrls ?? []) checkReturnUrl(entry);\n const loopback = config.loopback ?? true;\n if (!loopback && (config.returnUrls ?? []).length === 0 && config.pairing !== true) {\n throw new EnlittConfigurationError(\n \"createClientSignInHandler(): enable at least one of loopback, returnUrls, or pairing.\"\n );\n }\n if (\n typeof config.appName !== \"string\" ||\n config.appName.length < 1 ||\n config.appName.length > 60\n ) {\n throw new EnlittConfigurationError(\n \"createClientSignInHandler(): appName must be 1-60 characters.\"\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// The handler\n// ---------------------------------------------------------------------------\n\n/**\n * Builds the single handler that serves every path under `config.basePath`.\n * Mount it with one catch-all route. Construction throws\n * `EnlittConfigurationError` for a bad config, never at the first request.\n *\n * The business must rate-limit `POST <basePath>/pair` and `POST <basePath>/token`\n * per client IP with its own limiter; this handler has none.\n */\nexport function createClientSignInHandler(\n config: ClientSignInConfig\n): (request: Request) => Promise<Response> {\n checkConfig(config);\n\n const { store, basePath, appName } = config;\n const loopbackEnabled = config.loopback ?? true;\n const returnUrls = config.returnUrls ?? [];\n const pairingEnabled = config.pairing === true;\n const appOrigin = new URL(config.callback.appOrigin).origin;\n const cookieName = config.callback.cookieName ?? ENLITT_SESSION_COOKIE_NAME;\n const loginStart = createLoginStartHandler(config.callback);\n const logoutHandler = createLogoutHandler(config.callback);\n\n /**\n * A `Set-Cookie` that clears the Enlitt session cookie.\n *\n * Cleared at `start` so a session cookie seen at `complete` was minted by\n * this very sign-in (otherwise a browser already signed in to the business's\n * website would hand its existing web session to the client), and cleared at\n * `complete` because the token now belongs to the client and the browser must\n * not keep a second copy.\n */\n const clearSessionCookie = `${cookieName}=; Max-Age=0; Path=/; HttpOnly; Secure; SameSite=Lax`;\n\n /** A `303` to `location` that clears the session cookie and is never cached. */\n function redirectClearingCookie(location: string): Response {\n const headers = new Headers({\n Location: location,\n \"Cache-Control\": \"no-store\",\n \"Referrer-Policy\": \"no-referrer\"\n });\n headers.append(\"Set-Cookie\", clearSessionCookie);\n return new Response(null, { status: 303, headers });\n }\n\n /**\n * Writes the handoff and sends the browser into the business's login start\n * with `return_to` pointing back at `complete`. Shared by `start` and the\n * pairing confirmation, so the cookie clearing cannot differ between them.\n */\n async function beginLogin(handoff: Handoff): Promise<Response> {\n const id = randomId();\n await store.set(`h:${id}`, JSON.stringify(handoff), HANDOFF_TTL_MS);\n const returnTo = `${basePath}/complete?${new URLSearchParams({ h: id }).toString()}`;\n const internal = new Request(\n `${appOrigin}${basePath}/start?${new URLSearchParams({ return_to: returnTo }).toString()}`,\n { method: \"GET\" }\n );\n const response = await loginStart(internal);\n // Rebuild the response so its headers are certainly mutable, then add the cookie clearing.\n const headers = new Headers(response.headers);\n headers.append(\"Set-Cookie\", clearSessionCookie);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n }\n\n // ---- start ---------------------------------------------------------------\n\n async function start(url: URL): Promise<Response> {\n const params = url.searchParams;\n const names = [...params.keys()];\n // Every parameter must appear exactly once.\n if (new Set(names).size !== names.length) return invalidRequestPage();\n\n const mode = params.get(\"mode\");\n const allowed = [\"mode\", \"state\", \"code_challenge\", \"code_challenge_method\"];\n if (mode === \"loopback\" && loopbackEnabled) allowed.push(\"port\");\n else if (mode === \"redirect\" && returnUrls.length > 0) allowed.push(\"redirect_uri\");\n else return invalidRequestPage(); // unknown, pairing-only, or disabled mode\n if (names.length !== allowed.length || !names.every((name) => allowed.includes(name))) {\n return invalidRequestPage();\n }\n\n const state = params.get(\"state\") ?? \"\";\n const codeChallenge = params.get(\"code_challenge\") ?? \"\";\n if (!STATE_PATTERN.test(state)) return invalidRequestPage();\n if (!CODE_CHALLENGE_PATTERN.test(codeChallenge)) return invalidRequestPage();\n if (params.get(\"code_challenge_method\") !== \"S256\") return invalidRequestPage();\n\n let target: HandoffTarget;\n if (mode === \"loopback\") {\n const rawPort = params.get(\"port\") ?? \"\";\n const port = Number(rawPort);\n // Canonical decimal only: \"08080\" and \"8080.0\" are refused.\n if (\n !/^[0-9]{4,5}$/.test(rawPort) ||\n String(port) !== rawPort ||\n port < 1024 ||\n port > 65535\n ) {\n return invalidRequestPage();\n }\n target = { mode: \"loopback\", port };\n } else {\n const redirectUri = params.get(\"redirect_uri\") ?? \"\";\n // Exact match against the configured list; nothing else is ever trusted.\n if (!returnUrls.includes(redirectUri)) return invalidRequestPage();\n target = { mode: \"redirect\", redirectUri };\n }\n\n return beginLogin({ target, state, codeChallenge });\n }\n\n // ---- complete ------------------------------------------------------------\n\n /** Appends query parameters to a client target and redirects there. */\n function redirectToTarget(base: string, query: Record<string, string>): Response {\n const target = new URL(base);\n for (const [name, value] of Object.entries(query)) target.searchParams.append(name, value);\n return redirectClearingCookie(target.toString());\n }\n\n async function complete(request: Request, url: URL): Promise<Response> {\n const id = url.searchParams.get(\"h\") ?? \"\";\n const handoff = readHandoff(await store.consume(`h:${id}`));\n if (handoff === null) return expiredPage();\n\n // The session cookie is the one the business's callback just set, because\n // `start` cleared any earlier one.\n const sessionToken = readCookie(request, cookieName);\n const hasSession = sessionToken !== null && sessionToken !== \"\";\n\n const { target } = handoff;\n if (target.mode === \"pairing\") {\n const key = `p:${target.pairingId}`;\n const pairing = readPairing(await store.get(key));\n const remaining = pairing === null ? 0 : pairing.expiresAt - Date.now();\n if (pairing === null || remaining <= 0) return expiredPage();\n const updated: PairingRecord = hasSession\n ? { ...pairing, status: \"ready\", sessionToken }\n : { ...pairing, status: \"denied\" };\n await store.set(key, JSON.stringify(updated), remaining);\n const headers = new Headers();\n headers.append(\"Set-Cookie\", clearSessionCookie);\n return hasSession\n ? htmlPage(\n 200,\n \"Signed in\",\n \"<p>Signed in. You can go back to your other device.</p>\",\n headers\n )\n : htmlPage(\n 200,\n \"Sign-in cancelled\",\n \"<p>Sign-in cancelled. You can close this page.</p>\",\n headers\n );\n }\n\n const base =\n target.mode === \"loopback\" ? `http://127.0.0.1:${target.port}/callback` : target.redirectUri;\n const state = handoff.state ?? \"\";\n if (!hasSession) return redirectToTarget(base, { error: \"access_denied\", state });\n\n const code = randomId();\n const record: CodeRecord = { sessionToken, codeChallenge: handoff.codeChallenge };\n await store.set(`c:${code}`, JSON.stringify(record), CODE_TTL_MS);\n return redirectToTarget(base, { code, state });\n }\n\n // ---- pairing -------------------------------------------------------------\n\n async function pairing(request: Request): Promise<Response> {\n const body = await readJsonObject(request);\n if (\n body === null ||\n !hasExactKeys(body, [\"code_challenge\", \"code_challenge_method\"]) ||\n typeof body.code_challenge !== \"string\" ||\n !CODE_CHALLENGE_PATTERN.test(body.code_challenge) ||\n body.code_challenge_method !== \"S256\"\n ) {\n return tokenError(\"invalid_request\");\n }\n\n // A user code that collides with a live one is simply redrawn.\n let userCode = randomUserCode();\n while ((await store.get(`u:${userCode}`)) !== null) userCode = randomUserCode();\n\n const pairingId = randomId();\n const record: PairingRecord = {\n status: \"pending\",\n codeChallenge: body.code_challenge,\n userCode,\n expiresAt: Date.now() + PAIRING_TTL_MS\n };\n await store.set(`p:${pairingId}`, JSON.stringify(record), PAIRING_TTL_MS);\n await store.set(`u:${userCode}`, pairingId, PAIRING_TTL_MS);\n\n return jsonResponse(200, {\n pairing_id: pairingId,\n user_code: userCode,\n verification_uri: `${appOrigin}${basePath}/pair`,\n expires_in: PAIRING_TTL_MS / 1000,\n interval: PAIRING_INTERVAL_SECONDS\n });\n }\n\n // ---- pair pages ----------------------------------------------------------\n\n /** A page carrying the CSRF cookie, so every form on it can double-submit. */\n function csrfCookieHeaders(csrf: string): Headers {\n const headers = new Headers();\n headers.append(\n \"Set-Cookie\",\n `${CSRF_COOKIE_NAME}=${csrf}; HttpOnly; Secure; SameSite=Strict; Path=${basePath}`\n );\n return headers;\n }\n\n function entryFormPage(csrf: string, message?: string): Response {\n const notice = message === undefined ? \"\" : `<p role=\"alert\">${escapeHtml(message)}</p>`;\n return htmlPage(\n 200,\n `Sign in to ${appName}`,\n `<h1>Sign in to ${escapeHtml(appName)}</h1>${notice}` +\n `<form method=\"post\" action=\"${escapeHtml(basePath)}/pair\">` +\n `<input type=\"hidden\" name=\"csrf\" value=\"${escapeHtml(csrf)}\">` +\n `<label>Code shown on your other device<br>` +\n `<input name=\"user_code\" autocomplete=\"off\" autocapitalize=\"characters\" required></label><br>` +\n `<button type=\"submit\">Next</button></form>`,\n csrfCookieHeaders(csrf)\n );\n }\n\n function confirmationPage(csrf: string, userCode: string): Response {\n const shown = escapeHtml(formatUserCode(userCode));\n return htmlPage(\n 200,\n `Sign in to ${appName}`,\n `<h1>Sign in to ${escapeHtml(appName)} on another device?</h1>` +\n `<p class=\"code\">${shown}</p>` +\n `<p>Sign in to ${escapeHtml(appName)} on another device? Only continue if this code is on a screen ` +\n `in front of you right now. If someone sent you this code, do not continue — they are trying to use your account.</p>` +\n `<form method=\"post\" action=\"${escapeHtml(basePath)}/pair\">` +\n `<input type=\"hidden\" name=\"csrf\" value=\"${escapeHtml(csrf)}\">` +\n `<input type=\"hidden\" name=\"user_code\" value=\"${escapeHtml(userCode)}\">` +\n `<button type=\"submit\" name=\"action\" value=\"confirm\">Continue</button> ` +\n `<button type=\"submit\" name=\"action\" value=\"cancel\">Cancel</button></form>`,\n csrfCookieHeaders(csrf)\n );\n }\n\n /** Looks up the pending pairing a (normalized) user code names. */\n async function pendingPairingFor(\n userCode: string\n ): Promise<{ id: string; record: PairingRecord } | null> {\n if (userCode.length !== USER_CODE_LENGTH) return null;\n const id = await store.get(`u:${userCode}`);\n if (id === null) return null;\n const record = readPairing(await store.get(`p:${id}`));\n if (record?.status !== \"pending\" || record.expiresAt <= Date.now()) return null;\n return { id, record };\n }\n\n async function pair(request: Request): Promise<Response> {\n if (request.method === \"GET\") return entryFormPage(randomId());\n\n // POST: double-submit CSRF plus an Origin check.\n const origin = request.headers.get(\"origin\");\n if (origin !== null && origin !== appOrigin) return forbidden();\n const cookieCsrf = readCookie(request, CSRF_COOKIE_NAME);\n const form = new URLSearchParams(await request.text());\n const csrf = form.get(\"csrf\");\n if (cookieCsrf === null || csrf === null || cookieCsrf === \"\" || !safeEqual(cookieCsrf, csrf)) {\n return forbidden();\n }\n\n const userCode = normalizeUserCode(form.get(\"user_code\") ?? \"\");\n const action = form.get(\"action\");\n const found = await pendingPairingFor(userCode);\n if (found === null) return entryFormPage(csrf, \"That code is not valid or has expired.\");\n\n if (action === \"cancel\") {\n const remaining = found.record.expiresAt - Date.now();\n await store.set(\n `p:${found.id}`,\n JSON.stringify({ ...found.record, status: \"denied\" }),\n remaining\n );\n return htmlPage(\n 200,\n \"Sign-in cancelled\",\n \"<p>Sign-in cancelled. You can close this page.</p>\"\n );\n }\n if (action === \"confirm\") {\n return beginLogin({\n target: { mode: \"pairing\", pairingId: found.id },\n codeChallenge: found.record.codeChallenge\n });\n }\n return confirmationPage(csrf, userCode);\n }\n\n function forbidden(): Response {\n return htmlPage(\n 403,\n \"Forbidden\",\n \"<p>This request could not be verified. Go back and try again.</p>\"\n );\n }\n\n // ---- token ---------------------------------------------------------------\n\n async function token(request: Request): Promise<Response> {\n const body = await readJsonObject(request);\n if (body === null) return tokenError(\"invalid_request\");\n\n const verifier = body.code_verifier;\n if (body.grant_type === \"code\") {\n if (!hasExactKeys(body, [\"grant_type\", \"code\", \"code_verifier\"]))\n return tokenError(\"invalid_request\");\n if (typeof body.code !== \"string\" || typeof verifier !== \"string\")\n return tokenError(\"invalid_request\");\n return redeemCode(body.code, verifier);\n }\n if (body.grant_type === \"pairing\") {\n if (!hasExactKeys(body, [\"grant_type\", \"pairing_id\", \"code_verifier\"]))\n return tokenError(\"invalid_request\");\n if (typeof body.pairing_id !== \"string\" || typeof verifier !== \"string\")\n return tokenError(\"invalid_request\");\n return redeemPairing(body.pairing_id, verifier);\n }\n return tokenError(\"invalid_request\");\n }\n\n /** True when `verifier` is well formed and hashes to `challenge`. */\n function verifierMatches(verifier: string, challenge: string): boolean {\n return CODE_VERIFIER_PATTERN.test(verifier) && safeEqual(challengeOf(verifier), challenge);\n }\n\n /**\n * Redeems a code. It is consumed before the verifier is compared, so every\n * code is single-use and a wrong verifier also spends it.\n */\n async function redeemCode(code: string, verifier: string): Promise<Response> {\n if (!RANDOM_ID_PATTERN.test(code)) return tokenError(\"invalid_grant\");\n const record = readCode(await store.consume(`c:${code}`));\n if (record === null || !verifierMatches(verifier, record.codeChallenge))\n return tokenError(\"invalid_grant\");\n return jsonResponse(200, { session_token: record.sessionToken });\n }\n\n async function redeemPairing(pairingId: string, verifier: string): Promise<Response> {\n if (!RANDOM_ID_PATTERN.test(pairingId)) return tokenError(\"invalid_grant\");\n const key = `p:${pairingId}`;\n const current = readPairing(await store.get(key));\n if (current === null) return tokenError(\"invalid_grant\");\n // Still waiting for the person: leave the pairing alone so the client polls again.\n if (current.status === \"pending\" && current.expiresAt > Date.now())\n return tokenError(\"authorization_pending\");\n\n // Anything else ends the pairing now. Decide on the record this call\n // actually consumed, so two racing polls cannot both succeed.\n const record = readPairing(await store.consume(key));\n if (record === null) return tokenError(\"invalid_grant\");\n await store.consume(`u:${record.userCode}`);\n\n if (record.expiresAt <= Date.now() && record.status === \"pending\")\n return tokenError(\"expired_token\");\n if (record.status === \"denied\") return tokenError(\"access_denied\");\n if (record.status !== \"ready\" || record.sessionToken === undefined)\n return tokenError(\"invalid_grant\");\n if (!verifierMatches(verifier, record.codeChallenge)) return tokenError(\"invalid_grant\");\n return jsonResponse(200, { session_token: record.sessionToken });\n }\n\n // ---- logout --------------------------------------------------------------\n\n /**\n * Revokes the header token through the callback's logout handler, so\n * revocation has exactly one implementation. Always answers `204`.\n */\n async function logout(request: Request): Promise<Response> {\n const sessionToken = request.headers.get(ENLITT_SESSION_HEADER_NAME);\n if (\n sessionToken !== null &&\n sessionToken !== \"\" &&\n sessionToken.length <= MAX_LOGOUT_TOKEN_LENGTH\n ) {\n try {\n await logoutHandler(\n new Request(`${appOrigin}${basePath}/logout`, {\n method: \"POST\",\n headers: { cookie: `${cookieName}=${encodeURIComponent(sessionToken)}` }\n })\n );\n } catch {\n // A revocation failure has the same outcome as success for the client.\n }\n }\n return new Response(null, { status: 204, headers: { \"Cache-Control\": \"no-store\" } });\n }\n\n // ---- routing -------------------------------------------------------------\n\n function methodNotAllowed(allow: string): Response {\n return new Response(null, {\n status: 405,\n headers: { Allow: allow, \"Cache-Control\": \"no-store\" }\n });\n }\n\n function notFound(): Response {\n return new Response(\"Not found\", { status: 404, headers: { \"Cache-Control\": \"no-store\" } });\n }\n\n return async function handleClientSignIn(request: Request): Promise<Response> {\n const url = new URL(request.url);\n if (!url.pathname.startsWith(`${basePath}/`)) return notFound();\n const route = url.pathname.slice(basePath.length);\n const method = request.method.toUpperCase();\n\n switch (route) {\n case \"/start\":\n return method === \"GET\" ? start(url) : methodNotAllowed(\"GET\");\n case \"/complete\":\n return method === \"GET\" ? complete(request, url) : methodNotAllowed(\"GET\");\n case \"/token\":\n return method === \"POST\" ? token(request) : methodNotAllowed(\"POST\");\n case \"/logout\":\n return method === \"POST\" ? logout(request) : methodNotAllowed(\"POST\");\n case \"/pairing\":\n if (!pairingEnabled) return notFound();\n return method === \"POST\" ? pairing(request) : methodNotAllowed(\"POST\");\n case \"/pair\":\n if (!pairingEnabled) return notFound();\n return method === \"GET\" || method === \"POST\"\n ? pair(request)\n : methodNotAllowed(\"GET, POST\");\n default:\n return notFound();\n }\n };\n}\n"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@enlitt/sdk/vercel` — the Vercel AI SDK adapter entry.
|
|
3
|
+
*
|
|
4
|
+
* Exactly the surface a business using the Vercel AI SDK needs: the `enlitt()`
|
|
5
|
+
* model factory, the one standard model string, the `perToken()` price helper
|
|
6
|
+
* for language models (image, speech, and transcription calls have no helper:
|
|
7
|
+
* the business passes a constant or its own price function), and the types a business writes down when it wraps `enlitt()` or builds a
|
|
8
|
+
* premium price. Shared construction options (`EnlittOptions`), errors, and
|
|
9
|
+
* session helpers are not redeclared here; they live in `@enlitt/sdk/core`.
|
|
10
|
+
*
|
|
11
|
+
* Everything reachable from here may read the business secret key, so the
|
|
12
|
+
* package export map resolves this subpath's `browser` condition to
|
|
13
|
+
* `server-unavailable.ts`.
|
|
14
|
+
*/
|
|
15
|
+
export { enlitt, ENLITT_STANDARD_MODEL, type EnlittPrice, type EnlittProviderOptions, type EnlittTarget, type PremiumPriceContext } from "./language-model.cjs";
|
|
16
|
+
export { perToken } from "./premium-language-model.cjs";
|
|
17
|
+
export { type EnlittMediaPrice, type PremiumMediaPriceContext } from "./premium-media-model.cjs";
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@enlitt/sdk/vercel` — the Vercel AI SDK adapter entry.
|
|
3
|
+
*
|
|
4
|
+
* Exactly the surface a business using the Vercel AI SDK needs: the `enlitt()`
|
|
5
|
+
* model factory, the one standard model string, the `perToken()` price helper
|
|
6
|
+
* for language models (image, speech, and transcription calls have no helper:
|
|
7
|
+
* the business passes a constant or its own price function), and the types a business writes down when it wraps `enlitt()` or builds a
|
|
8
|
+
* premium price. Shared construction options (`EnlittOptions`), errors, and
|
|
9
|
+
* session helpers are not redeclared here; they live in `@enlitt/sdk/core`.
|
|
10
|
+
*
|
|
11
|
+
* Everything reachable from here may read the business secret key, so the
|
|
12
|
+
* package export map resolves this subpath's `browser` condition to
|
|
13
|
+
* `server-unavailable.ts`.
|
|
14
|
+
*/
|
|
15
|
+
export { enlitt, ENLITT_STANDARD_MODEL, type EnlittPrice, type EnlittProviderOptions, type EnlittTarget, type PremiumPriceContext } from "./language-model.js";
|
|
16
|
+
export { perToken } from "./premium-language-model.js";
|
|
17
|
+
export { type EnlittMediaPrice, type PremiumMediaPriceContext } from "./premium-media-model.js";
|
|
18
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/vercel/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EACL,MAAM,EACN,qBAAqB,EACrB,KAAK,WAAW,EAChB,KAAK,qBAAqB,EAC1B,KAAK,YAAY,EACjB,KAAK,mBAAmB,EACzB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,wBAAwB,EAC9B,MAAM,0BAA0B,CAAC"}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import type { ImageModelV3, ImageModelV4, LanguageModelV3, LanguageModelV4, LanguageModelV3CallOptions, LanguageModelV3Content, LanguageModelV3FinishReason, LanguageModelV3StreamPart, LanguageModelV3Usage, SharedV3ProviderMetadata, SharedV3ProviderOptions, SpeechModelV3, SpeechModelV4, TranscriptionModelV3, TranscriptionModelV4 } from "@ai-sdk/provider";
|
|
2
|
+
import { ENLITT_STANDARD_MODEL } from "@enlitt/protocol";
|
|
3
|
+
import { type EnlittOptions } from "../core/transport.cjs";
|
|
4
|
+
/**
|
|
5
|
+
* The only standard model string. There is no second public factory, client
|
|
6
|
+
* class, or model string in v1: this is a re-export of `@enlitt/protocol`'s
|
|
7
|
+
* own constant rather than a second literal, so the string a business passes
|
|
8
|
+
* to `enlitt()` and the `model` field the wire actually sees can never drift
|
|
9
|
+
* apart.
|
|
10
|
+
*/
|
|
11
|
+
export { ENLITT_STANDARD_MODEL };
|
|
12
|
+
/**
|
|
13
|
+
* What `enlitt()` accepts as its first argument: Enlitt's own standard model
|
|
14
|
+
* string, or a provider model the business selected and pays for. The mode
|
|
15
|
+
* is the argument's type, not a separate field, so there is no "unknown
|
|
16
|
+
* mode" case and no "premium model missing" case; both are unrepresentable.
|
|
17
|
+
*
|
|
18
|
+
* It names the `v3` language model only, as it did before `v4` support (Bug
|
|
19
|
+
* #28): widening it would turn a business's `Exclude<EnlittTarget, string>`
|
|
20
|
+
* into a union that `ai@6`'s `generateText` rejects. A `v4` model has its own
|
|
21
|
+
* `enlitt()` overload instead, and `enlitt()` itself accepts either.
|
|
22
|
+
*/
|
|
23
|
+
export type EnlittTarget = typeof ENLITT_STANDARD_MODEL | LanguageModelV3;
|
|
24
|
+
/**
|
|
25
|
+
* The only public model factory in this package.
|
|
26
|
+
*
|
|
27
|
+
* `enlitt("enlitt-standard")` returns Enlitt's own standard model;
|
|
28
|
+
* `enlitt(myProviderModel)` returns transparent middleware around it in
|
|
29
|
+
* premium mode. A provider model may be a language, image, speech, or
|
|
30
|
+
* transcription model, and the result has the same interface as the model
|
|
31
|
+
* passed in, including its specification version: `v3` for `ai@6`, `v4` for
|
|
32
|
+
* `ai@7` (Bug #28). Standard is a language model only. Both modes require the business's application secret, resolved
|
|
33
|
+
* once here by `createInternalClient()`, which also asserts a server runtime
|
|
34
|
+
* (before any secret is touched) and resolves and validates the base URL once.
|
|
35
|
+
* A missing or invalid secret is an `EnlittConfigurationError` thrown before the
|
|
36
|
+
* first request, in premium exactly as in standard. There is no configuration
|
|
37
|
+
* under which this function returns a model that would reach a provider without
|
|
38
|
+
* Enlitt: a business whose configuration silently degraded would pay for its
|
|
39
|
+
* users' premium calls and see nothing wrong until the provider bill arrived.
|
|
40
|
+
*
|
|
41
|
+
* It builds exactly one internal client per call and hands it to whichever
|
|
42
|
+
* model it returns. `EnlittOptions` is declared once, in core, and shared with
|
|
43
|
+
* `withPremiumCharge()` and `usage()`.
|
|
44
|
+
*/
|
|
45
|
+
export declare function enlitt(target: EnlittTarget, options?: EnlittOptions): LanguageModelV3;
|
|
46
|
+
export declare function enlitt(target: LanguageModelV4, options?: EnlittOptions): LanguageModelV4;
|
|
47
|
+
export declare function enlitt(target: ImageModelV3, options?: EnlittOptions): ImageModelV3;
|
|
48
|
+
export declare function enlitt(target: ImageModelV4, options?: EnlittOptions): ImageModelV4;
|
|
49
|
+
export declare function enlitt(target: SpeechModelV3, options?: EnlittOptions): SpeechModelV3;
|
|
50
|
+
export declare function enlitt(target: SpeechModelV4, options?: EnlittOptions): SpeechModelV4;
|
|
51
|
+
export declare function enlitt(target: TranscriptionModelV3, options?: EnlittOptions): TranscriptionModelV3;
|
|
52
|
+
export declare function enlitt(target: TranscriptionModelV4, options?: EnlittOptions): TranscriptionModelV4;
|
|
53
|
+
/**
|
|
54
|
+
* What a premium call states it costs: a constant NANOUSD amount, or a
|
|
55
|
+
* function that computes one once the call has ended. A function runs exactly
|
|
56
|
+
* once per operation, only when the call ends `completed` or `canceled`, may be
|
|
57
|
+
* async, and is never called for `failed`, which reports `"0"`.
|
|
58
|
+
*/
|
|
59
|
+
export type EnlittPrice = string | ((context: PremiumPriceContext) => string | Promise<string>);
|
|
60
|
+
/**
|
|
61
|
+
* Everything the SDK knows when a premium call ends, and nothing it does not.
|
|
62
|
+
* It never leaves the business's process.
|
|
63
|
+
*/
|
|
64
|
+
export interface PremiumPriceContext {
|
|
65
|
+
readonly status: "completed" | "canceled";
|
|
66
|
+
/**
|
|
67
|
+
* For `doGenerate`, the result's content. For `doStream`, every part the
|
|
68
|
+
* provider emitted up to its end or the cancellation, in order. Stream parts
|
|
69
|
+
* are collected only when `price` is a function.
|
|
70
|
+
*/
|
|
71
|
+
readonly output: {
|
|
72
|
+
readonly kind: "generate";
|
|
73
|
+
readonly content: readonly LanguageModelV3Content[];
|
|
74
|
+
} | {
|
|
75
|
+
readonly kind: "stream";
|
|
76
|
+
readonly parts: readonly LanguageModelV3StreamPart[];
|
|
77
|
+
};
|
|
78
|
+
/** Possibly absent on a cancellation. */
|
|
79
|
+
readonly usage?: LanguageModelV3Usage;
|
|
80
|
+
/** Absent on a cancellation before a finish part. */
|
|
81
|
+
readonly finishReason?: LanguageModelV3FinishReason;
|
|
82
|
+
readonly providerMetadata?: SharedV3ProviderMetadata;
|
|
83
|
+
/** Provider invocation start. */
|
|
84
|
+
readonly startedAt: Date;
|
|
85
|
+
/** The end or cancellation instant. */
|
|
86
|
+
readonly endedAt: Date;
|
|
87
|
+
readonly durationMs: number;
|
|
88
|
+
/** Present only for a stream that emitted a content part. */
|
|
89
|
+
readonly timeToFirstTokenMs?: number;
|
|
90
|
+
/** The bound every price for this call is lowered to; it may be below the declared `maxCharge`. */
|
|
91
|
+
readonly effectiveMaxChargeNanoUsd: string;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The validated result of `readEnlittCallOptions()`: `providerOptions.enlitt`
|
|
95
|
+
* as the SDK works with it. Every field is optional at the type level because
|
|
96
|
+
* validity depends on `mode`; `readEnlittCallOptions()` is the one place that
|
|
97
|
+
* mode-dependent shape is enforced.
|
|
98
|
+
*/
|
|
99
|
+
export interface EnlittProviderOptions {
|
|
100
|
+
/** A base for the call identity, not the identity itself; see `resolveCallId()`. 16-200 visible ASCII characters. */
|
|
101
|
+
idempotencyKey?: string;
|
|
102
|
+
/** NANOUSD, premium only. Required unless `price` is a constant, in which case it defaults to that constant. */
|
|
103
|
+
maxCharge?: string;
|
|
104
|
+
/** Premium only. Without it a call charges `"0"` for every status. */
|
|
105
|
+
price?: EnlittPrice;
|
|
106
|
+
/** Premium only. How long the business needs before it will report the terminal outcome. */
|
|
107
|
+
reportingDeadlineMs?: number;
|
|
108
|
+
/** At most 16 entries, keys at most 64 characters, values at most 512, no key beginning with `enlitt_`. */
|
|
109
|
+
metadata?: Record<string, string>;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Runtime-validates `providerOptions.enlitt` on every invocation. There is no
|
|
113
|
+
* `managed` parameter and no unmanaged case: every call in either mode is
|
|
114
|
+
* managed. Every failure is an `EnlittConfigurationError` raised before any
|
|
115
|
+
* Enlitt or provider request, and other provider namespaces are never touched.
|
|
116
|
+
*
|
|
117
|
+
* Premium combinations: a constant `price` alone sets `maxCharge` to it;
|
|
118
|
+
* `maxCharge` alone charges `"0"`; a function `price` without `maxCharge` is
|
|
119
|
+
* rejected (a function's result is only known after the provider has run and
|
|
120
|
+
* the maximum must be known before); a constant `price` above `maxCharge` is
|
|
121
|
+
* rejected (it could never be charged in full); neither is rejected.
|
|
122
|
+
*/
|
|
123
|
+
export declare function readEnlittCallOptions(providerOptions: SharedV3ProviderOptions | undefined, mode: "standard" | "premium"): EnlittProviderOptions;
|
|
124
|
+
/**
|
|
125
|
+
* Derives the one identity of a single underlying model invocation. Sent as
|
|
126
|
+
* `Idempotency-Key` on both paths and as `call_id` (via the same
|
|
127
|
+
* `Idempotency-Key`) on the premium preflight; there is no second identifier.
|
|
128
|
+
*
|
|
129
|
+
* `callId` is `` `${base}.${params.prompt.length}` ``, where `base` is
|
|
130
|
+
* `options.idempotencyKey` when supplied and otherwise a freshly generated
|
|
131
|
+
* random value unique per invocation. The suffix — the count of prompt items,
|
|
132
|
+
* never a hash or any other read of content — is what makes the identity
|
|
133
|
+
* behave correctly in a tool loop: within one `generateText` loop the prompt
|
|
134
|
+
* grows by at least one item before each subsequent provider invocation, so
|
|
135
|
+
* distinct steps get distinct IDs, while a retry of the same step
|
|
136
|
+
* re-presents the identical prompt and so reuses the ID.
|
|
137
|
+
*
|
|
138
|
+
* The resulting ID is validated against the protocol's own 16-255
|
|
139
|
+
* visible-ASCII `Idempotency-Key` bound before it is returned, converting a
|
|
140
|
+
* violation into `EnlittConfigurationError` rather than sending an
|
|
141
|
+
* out-of-bounds header. With `idempotencyKey` bounded at the protocol's own
|
|
142
|
+
* floor by `readEnlittCallOptions()`, no reachable input violates that bound;
|
|
143
|
+
* the check stays as the one place the wire rule is enforced, so a future
|
|
144
|
+
* change to either end cannot ship an out-of-bounds header silently.
|
|
145
|
+
*/
|
|
146
|
+
export declare function resolveCallId(options: EnlittProviderOptions, params: LanguageModelV3CallOptions): string;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import type { ImageModelV3, ImageModelV4, LanguageModelV3, LanguageModelV4, LanguageModelV3CallOptions, LanguageModelV3Content, LanguageModelV3FinishReason, LanguageModelV3StreamPart, LanguageModelV3Usage, SharedV3ProviderMetadata, SharedV3ProviderOptions, SpeechModelV3, SpeechModelV4, TranscriptionModelV3, TranscriptionModelV4 } from "@ai-sdk/provider";
|
|
2
|
+
import { ENLITT_STANDARD_MODEL } from "@enlitt/protocol";
|
|
3
|
+
import { type EnlittOptions } from "../core/transport.js";
|
|
4
|
+
/**
|
|
5
|
+
* The only standard model string. There is no second public factory, client
|
|
6
|
+
* class, or model string in v1: this is a re-export of `@enlitt/protocol`'s
|
|
7
|
+
* own constant rather than a second literal, so the string a business passes
|
|
8
|
+
* to `enlitt()` and the `model` field the wire actually sees can never drift
|
|
9
|
+
* apart.
|
|
10
|
+
*/
|
|
11
|
+
export { ENLITT_STANDARD_MODEL };
|
|
12
|
+
/**
|
|
13
|
+
* What `enlitt()` accepts as its first argument: Enlitt's own standard model
|
|
14
|
+
* string, or a provider model the business selected and pays for. The mode
|
|
15
|
+
* is the argument's type, not a separate field, so there is no "unknown
|
|
16
|
+
* mode" case and no "premium model missing" case; both are unrepresentable.
|
|
17
|
+
*
|
|
18
|
+
* It names the `v3` language model only, as it did before `v4` support (Bug
|
|
19
|
+
* #28): widening it would turn a business's `Exclude<EnlittTarget, string>`
|
|
20
|
+
* into a union that `ai@6`'s `generateText` rejects. A `v4` model has its own
|
|
21
|
+
* `enlitt()` overload instead, and `enlitt()` itself accepts either.
|
|
22
|
+
*/
|
|
23
|
+
export type EnlittTarget = typeof ENLITT_STANDARD_MODEL | LanguageModelV3;
|
|
24
|
+
/**
|
|
25
|
+
* The only public model factory in this package.
|
|
26
|
+
*
|
|
27
|
+
* `enlitt("enlitt-standard")` returns Enlitt's own standard model;
|
|
28
|
+
* `enlitt(myProviderModel)` returns transparent middleware around it in
|
|
29
|
+
* premium mode. A provider model may be a language, image, speech, or
|
|
30
|
+
* transcription model, and the result has the same interface as the model
|
|
31
|
+
* passed in, including its specification version: `v3` for `ai@6`, `v4` for
|
|
32
|
+
* `ai@7` (Bug #28). Standard is a language model only. Both modes require the business's application secret, resolved
|
|
33
|
+
* once here by `createInternalClient()`, which also asserts a server runtime
|
|
34
|
+
* (before any secret is touched) and resolves and validates the base URL once.
|
|
35
|
+
* A missing or invalid secret is an `EnlittConfigurationError` thrown before the
|
|
36
|
+
* first request, in premium exactly as in standard. There is no configuration
|
|
37
|
+
* under which this function returns a model that would reach a provider without
|
|
38
|
+
* Enlitt: a business whose configuration silently degraded would pay for its
|
|
39
|
+
* users' premium calls and see nothing wrong until the provider bill arrived.
|
|
40
|
+
*
|
|
41
|
+
* It builds exactly one internal client per call and hands it to whichever
|
|
42
|
+
* model it returns. `EnlittOptions` is declared once, in core, and shared with
|
|
43
|
+
* `withPremiumCharge()` and `usage()`.
|
|
44
|
+
*/
|
|
45
|
+
export declare function enlitt(target: EnlittTarget, options?: EnlittOptions): LanguageModelV3;
|
|
46
|
+
export declare function enlitt(target: LanguageModelV4, options?: EnlittOptions): LanguageModelV4;
|
|
47
|
+
export declare function enlitt(target: ImageModelV3, options?: EnlittOptions): ImageModelV3;
|
|
48
|
+
export declare function enlitt(target: ImageModelV4, options?: EnlittOptions): ImageModelV4;
|
|
49
|
+
export declare function enlitt(target: SpeechModelV3, options?: EnlittOptions): SpeechModelV3;
|
|
50
|
+
export declare function enlitt(target: SpeechModelV4, options?: EnlittOptions): SpeechModelV4;
|
|
51
|
+
export declare function enlitt(target: TranscriptionModelV3, options?: EnlittOptions): TranscriptionModelV3;
|
|
52
|
+
export declare function enlitt(target: TranscriptionModelV4, options?: EnlittOptions): TranscriptionModelV4;
|
|
53
|
+
/**
|
|
54
|
+
* What a premium call states it costs: a constant NANOUSD amount, or a
|
|
55
|
+
* function that computes one once the call has ended. A function runs exactly
|
|
56
|
+
* once per operation, only when the call ends `completed` or `canceled`, may be
|
|
57
|
+
* async, and is never called for `failed`, which reports `"0"`.
|
|
58
|
+
*/
|
|
59
|
+
export type EnlittPrice = string | ((context: PremiumPriceContext) => string | Promise<string>);
|
|
60
|
+
/**
|
|
61
|
+
* Everything the SDK knows when a premium call ends, and nothing it does not.
|
|
62
|
+
* It never leaves the business's process.
|
|
63
|
+
*/
|
|
64
|
+
export interface PremiumPriceContext {
|
|
65
|
+
readonly status: "completed" | "canceled";
|
|
66
|
+
/**
|
|
67
|
+
* For `doGenerate`, the result's content. For `doStream`, every part the
|
|
68
|
+
* provider emitted up to its end or the cancellation, in order. Stream parts
|
|
69
|
+
* are collected only when `price` is a function.
|
|
70
|
+
*/
|
|
71
|
+
readonly output: {
|
|
72
|
+
readonly kind: "generate";
|
|
73
|
+
readonly content: readonly LanguageModelV3Content[];
|
|
74
|
+
} | {
|
|
75
|
+
readonly kind: "stream";
|
|
76
|
+
readonly parts: readonly LanguageModelV3StreamPart[];
|
|
77
|
+
};
|
|
78
|
+
/** Possibly absent on a cancellation. */
|
|
79
|
+
readonly usage?: LanguageModelV3Usage;
|
|
80
|
+
/** Absent on a cancellation before a finish part. */
|
|
81
|
+
readonly finishReason?: LanguageModelV3FinishReason;
|
|
82
|
+
readonly providerMetadata?: SharedV3ProviderMetadata;
|
|
83
|
+
/** Provider invocation start. */
|
|
84
|
+
readonly startedAt: Date;
|
|
85
|
+
/** The end or cancellation instant. */
|
|
86
|
+
readonly endedAt: Date;
|
|
87
|
+
readonly durationMs: number;
|
|
88
|
+
/** Present only for a stream that emitted a content part. */
|
|
89
|
+
readonly timeToFirstTokenMs?: number;
|
|
90
|
+
/** The bound every price for this call is lowered to; it may be below the declared `maxCharge`. */
|
|
91
|
+
readonly effectiveMaxChargeNanoUsd: string;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The validated result of `readEnlittCallOptions()`: `providerOptions.enlitt`
|
|
95
|
+
* as the SDK works with it. Every field is optional at the type level because
|
|
96
|
+
* validity depends on `mode`; `readEnlittCallOptions()` is the one place that
|
|
97
|
+
* mode-dependent shape is enforced.
|
|
98
|
+
*/
|
|
99
|
+
export interface EnlittProviderOptions {
|
|
100
|
+
/** A base for the call identity, not the identity itself; see `resolveCallId()`. 16-200 visible ASCII characters. */
|
|
101
|
+
idempotencyKey?: string;
|
|
102
|
+
/** NANOUSD, premium only. Required unless `price` is a constant, in which case it defaults to that constant. */
|
|
103
|
+
maxCharge?: string;
|
|
104
|
+
/** Premium only. Without it a call charges `"0"` for every status. */
|
|
105
|
+
price?: EnlittPrice;
|
|
106
|
+
/** Premium only. How long the business needs before it will report the terminal outcome. */
|
|
107
|
+
reportingDeadlineMs?: number;
|
|
108
|
+
/** At most 16 entries, keys at most 64 characters, values at most 512, no key beginning with `enlitt_`. */
|
|
109
|
+
metadata?: Record<string, string>;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Runtime-validates `providerOptions.enlitt` on every invocation. There is no
|
|
113
|
+
* `managed` parameter and no unmanaged case: every call in either mode is
|
|
114
|
+
* managed. Every failure is an `EnlittConfigurationError` raised before any
|
|
115
|
+
* Enlitt or provider request, and other provider namespaces are never touched.
|
|
116
|
+
*
|
|
117
|
+
* Premium combinations: a constant `price` alone sets `maxCharge` to it;
|
|
118
|
+
* `maxCharge` alone charges `"0"`; a function `price` without `maxCharge` is
|
|
119
|
+
* rejected (a function's result is only known after the provider has run and
|
|
120
|
+
* the maximum must be known before); a constant `price` above `maxCharge` is
|
|
121
|
+
* rejected (it could never be charged in full); neither is rejected.
|
|
122
|
+
*/
|
|
123
|
+
export declare function readEnlittCallOptions(providerOptions: SharedV3ProviderOptions | undefined, mode: "standard" | "premium"): EnlittProviderOptions;
|
|
124
|
+
/**
|
|
125
|
+
* Derives the one identity of a single underlying model invocation. Sent as
|
|
126
|
+
* `Idempotency-Key` on both paths and as `call_id` (via the same
|
|
127
|
+
* `Idempotency-Key`) on the premium preflight; there is no second identifier.
|
|
128
|
+
*
|
|
129
|
+
* `callId` is `` `${base}.${params.prompt.length}` ``, where `base` is
|
|
130
|
+
* `options.idempotencyKey` when supplied and otherwise a freshly generated
|
|
131
|
+
* random value unique per invocation. The suffix — the count of prompt items,
|
|
132
|
+
* never a hash or any other read of content — is what makes the identity
|
|
133
|
+
* behave correctly in a tool loop: within one `generateText` loop the prompt
|
|
134
|
+
* grows by at least one item before each subsequent provider invocation, so
|
|
135
|
+
* distinct steps get distinct IDs, while a retry of the same step
|
|
136
|
+
* re-presents the identical prompt and so reuses the ID.
|
|
137
|
+
*
|
|
138
|
+
* The resulting ID is validated against the protocol's own 16-255
|
|
139
|
+
* visible-ASCII `Idempotency-Key` bound before it is returned, converting a
|
|
140
|
+
* violation into `EnlittConfigurationError` rather than sending an
|
|
141
|
+
* out-of-bounds header. With `idempotencyKey` bounded at the protocol's own
|
|
142
|
+
* floor by `readEnlittCallOptions()`, no reachable input violates that bound;
|
|
143
|
+
* the check stays as the one place the wire rule is enforced, so a future
|
|
144
|
+
* change to either end cannot ship an out-of-bounds header silently.
|
|
145
|
+
*/
|
|
146
|
+
export declare function resolveCallId(options: EnlittProviderOptions, params: LanguageModelV3CallOptions): string;
|
|
147
|
+
//# sourceMappingURL=language-model.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"language-model.d.ts","sourceRoot":"","sources":["../../src/vercel/language-model.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,YAAY,EACZ,YAAY,EACZ,eAAe,EACf,eAAe,EACf,0BAA0B,EAC1B,sBAAsB,EACtB,2BAA2B,EAC3B,yBAAyB,EACzB,oBAAoB,EACpB,wBAAwB,EACxB,uBAAuB,EACvB,aAAa,EACb,aAAa,EACb,oBAAoB,EACpB,oBAAoB,EACrB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAUzD,OAAO,EAAwB,KAAK,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAKhF;;;;;;GAMG;AACH,OAAO,EAAE,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