@enlitt/sdk 0.0.0-stage → 0.1.0
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 +8 -0
- package/LICENSE +21 -0
- package/README.md +61 -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-26SW63P5.cjs +883 -0
- package/dist/chunk-26SW63P5.cjs.map +1 -0
- package/dist/chunk-6DPBYLA5.js +855 -0
- package/dist/chunk-6DPBYLA5.js.map +1 -0
- package/dist/chunk-6OWXYBBT.cjs +146 -0
- package/dist/chunk-6OWXYBBT.cjs.map +1 -0
- package/dist/chunk-C76K6HLL.cjs +906 -0
- package/dist/chunk-C76K6HLL.cjs.map +1 -0
- package/dist/chunk-G4DTTV5E.cjs +35 -0
- package/dist/chunk-G4DTTV5E.cjs.map +1 -0
- package/dist/chunk-SFI4RLNN.js +900 -0
- package/dist/chunk-SFI4RLNN.js.map +1 -0
- package/dist/chunk-V5TCSQ7C.js +143 -0
- package/dist/chunk-V5TCSQ7C.js.map +1 -0
- package/dist/chunk-VNVMEU34.js +33 -0
- package/dist/chunk-VNVMEU34.js.map +1 -0
- package/dist/core/errors.d.cts +254 -0
- package/dist/core/errors.d.ts +255 -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 +107 -0
- package/dist/core/session.d.ts +108 -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 +73 -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 +48 -0
- package/dist/openai/client.d.ts +49 -0
- package/dist/openai/client.d.ts.map +1 -0
- package/dist/openai/index.d.cts +1 -0
- package/dist/openai/index.d.ts +2 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai.cjs +479 -0
- package/dist/openai.cjs.map +1 -0
- package/dist/openai.js +473 -0
- package/dist/openai.js.map +1 -0
- package/dist/server/callback.d.cts +106 -0
- package/dist/server/callback.d.ts +107 -0
- package/dist/server/callback.d.ts.map +1 -0
- package/dist/server/index.d.cts +19 -0
- package/dist/server/index.d.ts +20 -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 +354 -0
- package/dist/server.cjs.map +1 -0
- package/dist/server.js +275 -0
- package/dist/server.js.map +1 -0
- package/dist/vercel/index.d.cts +15 -0
- package/dist/vercel/index.d.ts +16 -0
- package/dist/vercel/index.d.ts.map +1 -0
- package/dist/vercel/language-model.d.cts +131 -0
- package/dist/vercel/language-model.d.ts +132 -0
- package/dist/vercel/language-model.d.ts.map +1 -0
- package/dist/vercel/premium-language-model.d.cts +98 -0
- package/dist/vercel/premium-language-model.d.ts +99 -0
- package/dist/vercel/premium-language-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 +129 -3
package/dist/server.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
export { usage } from './chunk-VNVMEU34.js';
|
|
2
|
+
export { ENLITT_STANDARD_MODEL, enlitt, perToken } from './chunk-SFI4RLNN.js';
|
|
3
|
+
import './chunk-V5TCSQ7C.js';
|
|
4
|
+
import { resolveBusinessAuthorizationHeader, ENLITT_SESSION_COOKIE_NAME } from './chunk-6DPBYLA5.js';
|
|
5
|
+
export { ENLITT_SESSION_COOKIE_NAME, EnlittAuthenticationError, EnlittAuthorizationError, EnlittConfigurationError, EnlittError, EnlittInsufficientCreditsError, EnlittLimitExceededError, EnlittLoginRequiredError, EnlittRateLimitError, EnlittSubscriptionInactiveError, enlittSession, enlittSessionMiddleware, getEnlittSession, runWithEnlittSession, withPremiumCharge } from './chunk-6DPBYLA5.js';
|
|
6
|
+
import { ENLITT_VERSION_HEADER, ENLITT_API_VERSION, validateAuthorizationExchangeResponse } from '@enlitt/protocol';
|
|
7
|
+
|
|
8
|
+
var DEFAULT_ENLITT_ORIGIN = "https://enlitt.com";
|
|
9
|
+
var AUTHORIZE_PATH = "/auth/oauth2/authorize";
|
|
10
|
+
var TOKEN_PATH = "/auth/oauth2/token";
|
|
11
|
+
var REVOKE_PATH = "/auth/oauth2/revoke";
|
|
12
|
+
var RETURN_TO_PARAM = "return_to";
|
|
13
|
+
var STATE_TTL_MS = 10 * 60 * 1e3;
|
|
14
|
+
var STATE_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
|
15
|
+
var STATE_LENGTH = 32;
|
|
16
|
+
var STATE_BYTE_LIMIT = 256 - 256 % STATE_ALPHABET.length;
|
|
17
|
+
var SAFE_COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
18
|
+
function generateState() {
|
|
19
|
+
const source = globalThis.crypto;
|
|
20
|
+
if (!source?.getRandomValues) {
|
|
21
|
+
throw new Error(
|
|
22
|
+
"@enlitt/sdk: no Web Crypto implementation is available, so no unguessable login state can be generated. Node 20+, Deno, Bun, and Workers all provide one."
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
let out = "";
|
|
26
|
+
while (out.length < STATE_LENGTH) {
|
|
27
|
+
const bytes = source.getRandomValues(new Uint8Array(STATE_LENGTH));
|
|
28
|
+
for (const byte of bytes) {
|
|
29
|
+
if (byte >= STATE_BYTE_LIMIT) continue;
|
|
30
|
+
out += STATE_ALPHABET[byte % STATE_ALPHABET.length];
|
|
31
|
+
if (out.length === STATE_LENGTH) break;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
function safeReturnPath(target, appOrigin) {
|
|
37
|
+
if (typeof target !== "string" || target.length === 0) return null;
|
|
38
|
+
let decoded;
|
|
39
|
+
try {
|
|
40
|
+
decoded = decodeURIComponent(target);
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
for (const form of [target, decoded]) {
|
|
45
|
+
if (!form.startsWith("/")) return null;
|
|
46
|
+
if (form.startsWith("//") || form.startsWith("/\\")) return null;
|
|
47
|
+
if (form.includes("\\")) return null;
|
|
48
|
+
if (form.split(/[/?#]/).includes("..")) return null;
|
|
49
|
+
for (let i = 0; i < form.length; i += 1) {
|
|
50
|
+
const point = form.charCodeAt(i);
|
|
51
|
+
if (point < 32 || point === 127) return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
let resolved;
|
|
55
|
+
let base;
|
|
56
|
+
try {
|
|
57
|
+
base = new URL(appOrigin);
|
|
58
|
+
resolved = new URL(target, base);
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
if (resolved.origin !== base.origin) return null;
|
|
63
|
+
return `${resolved.pathname}${resolved.search}${resolved.hash}`;
|
|
64
|
+
}
|
|
65
|
+
function resolveConfig(config) {
|
|
66
|
+
if (config.onSignIn !== void 0 && typeof config.onSignIn !== "function") {
|
|
67
|
+
throw new Error("@enlitt/sdk: onSignIn must be a function.");
|
|
68
|
+
}
|
|
69
|
+
if (config.clientId.length === 0) {
|
|
70
|
+
throw new Error("@enlitt/sdk: clientId is required.");
|
|
71
|
+
}
|
|
72
|
+
let appOrigin;
|
|
73
|
+
try {
|
|
74
|
+
appOrigin = new URL(config.appOrigin).origin;
|
|
75
|
+
} catch {
|
|
76
|
+
throw new Error("@enlitt/sdk: appOrigin must be an absolute origin, e.g. https://app.example.com.");
|
|
77
|
+
}
|
|
78
|
+
if (appOrigin === "null") {
|
|
79
|
+
throw new Error("@enlitt/sdk: appOrigin must be an absolute origin, e.g. https://app.example.com.");
|
|
80
|
+
}
|
|
81
|
+
let enlittOrigin;
|
|
82
|
+
try {
|
|
83
|
+
enlittOrigin = new URL(config.enlittOrigin ?? DEFAULT_ENLITT_ORIGIN).origin;
|
|
84
|
+
} catch {
|
|
85
|
+
throw new Error("@enlitt/sdk: enlittOrigin must be an absolute origin.");
|
|
86
|
+
}
|
|
87
|
+
let enlittApiOrigin;
|
|
88
|
+
try {
|
|
89
|
+
enlittApiOrigin = new URL(config.enlittApiOrigin ?? enlittOrigin).origin;
|
|
90
|
+
} catch {
|
|
91
|
+
throw new Error("@enlitt/sdk: enlittApiOrigin must be an absolute origin.");
|
|
92
|
+
}
|
|
93
|
+
try {
|
|
94
|
+
void new URL(config.redirectUri);
|
|
95
|
+
} catch {
|
|
96
|
+
throw new Error("@enlitt/sdk: redirectUri must be the absolute URL registered with Enlitt.");
|
|
97
|
+
}
|
|
98
|
+
const defaultReturnTo = safeReturnPath(config.defaultReturnTo, appOrigin);
|
|
99
|
+
if (defaultReturnTo === null) {
|
|
100
|
+
throw new Error('@enlitt/sdk: defaultReturnTo must be a path on appOrigin, e.g. "/".');
|
|
101
|
+
}
|
|
102
|
+
const cookieName = config.cookieName ?? ENLITT_SESSION_COOKIE_NAME;
|
|
103
|
+
if (!SAFE_COOKIE_NAME.test(cookieName)) {
|
|
104
|
+
throw new Error("@enlitt/sdk: cookieName must be a valid cookie name.");
|
|
105
|
+
}
|
|
106
|
+
const resolved = {
|
|
107
|
+
clientId: config.clientId,
|
|
108
|
+
redirectUri: config.redirectUri,
|
|
109
|
+
enlittOrigin,
|
|
110
|
+
enlittApiOrigin,
|
|
111
|
+
appOrigin,
|
|
112
|
+
defaultReturnTo,
|
|
113
|
+
cookieName,
|
|
114
|
+
stateStore: config.stateStore,
|
|
115
|
+
...config.onSignIn === void 0 ? {} : { onSignIn: config.onSignIn }
|
|
116
|
+
};
|
|
117
|
+
return config.secretKey === void 0 ? resolved : { ...resolved, secretKey: config.secretKey };
|
|
118
|
+
}
|
|
119
|
+
function redirectTo(location, cookie) {
|
|
120
|
+
const headers = new Headers({
|
|
121
|
+
location,
|
|
122
|
+
// A login outcome is never a cacheable page.
|
|
123
|
+
"cache-control": "no-store"
|
|
124
|
+
});
|
|
125
|
+
if (cookie !== void 0) headers.append("set-cookie", cookie);
|
|
126
|
+
return new Response(null, { status: 303, headers });
|
|
127
|
+
}
|
|
128
|
+
function sessionCookie(name, value, maxAgeSeconds) {
|
|
129
|
+
const parts = [`${name}=${value}`, "Path=/", "HttpOnly", "Secure", "SameSite=Lax"];
|
|
130
|
+
if (maxAgeSeconds !== void 0) parts.push(`Max-Age=${String(maxAgeSeconds)}`);
|
|
131
|
+
return parts.join("; ");
|
|
132
|
+
}
|
|
133
|
+
function clearedCookie(name) {
|
|
134
|
+
return [
|
|
135
|
+
`${name}=`,
|
|
136
|
+
"Path=/",
|
|
137
|
+
"HttpOnly",
|
|
138
|
+
"Secure",
|
|
139
|
+
"SameSite=Lax",
|
|
140
|
+
"Max-Age=0",
|
|
141
|
+
"Expires=Thu, 01 Jan 1970 00:00:00 GMT"
|
|
142
|
+
].join("; ");
|
|
143
|
+
}
|
|
144
|
+
function readCookie(request, name) {
|
|
145
|
+
const header = request.headers.get("cookie");
|
|
146
|
+
if (header === null) return null;
|
|
147
|
+
for (const pair of header.split(";")) {
|
|
148
|
+
const separator = pair.indexOf("=");
|
|
149
|
+
if (separator === -1) continue;
|
|
150
|
+
if (pair.slice(0, separator).trim() !== name) continue;
|
|
151
|
+
const value = pair.slice(separator + 1).trim();
|
|
152
|
+
return value.length === 0 ? null : value;
|
|
153
|
+
}
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
function readExchangeResult(payload) {
|
|
157
|
+
const parsed = validateAuthorizationExchangeResponse(payload, { mode: "tolerant" });
|
|
158
|
+
if (!parsed.ok) return null;
|
|
159
|
+
const body = payload;
|
|
160
|
+
const identity = { sessionToken: parsed.value.session_token, subject: parsed.value.subject };
|
|
161
|
+
const expiresIn = body.expires_in;
|
|
162
|
+
if (typeof expiresIn === "number" && Number.isInteger(expiresIn) && expiresIn > 0) {
|
|
163
|
+
return { ...identity, expiresInSeconds: expiresIn };
|
|
164
|
+
}
|
|
165
|
+
return identity;
|
|
166
|
+
}
|
|
167
|
+
async function exchangeCode(config, code) {
|
|
168
|
+
const authorization = resolveBusinessAuthorizationHeader(
|
|
169
|
+
config.secretKey === void 0 ? {} : { secretKey: config.secretKey }
|
|
170
|
+
);
|
|
171
|
+
const body = new URLSearchParams({
|
|
172
|
+
grant_type: "authorization_code",
|
|
173
|
+
code,
|
|
174
|
+
redirect_uri: config.redirectUri,
|
|
175
|
+
client_id: config.clientId
|
|
176
|
+
});
|
|
177
|
+
let response;
|
|
178
|
+
try {
|
|
179
|
+
response = await fetch(new URL(TOKEN_PATH, config.enlittApiOrigin), {
|
|
180
|
+
method: "POST",
|
|
181
|
+
headers: {
|
|
182
|
+
authorization,
|
|
183
|
+
[ENLITT_VERSION_HEADER]: ENLITT_API_VERSION,
|
|
184
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
185
|
+
accept: "application/json"
|
|
186
|
+
},
|
|
187
|
+
body
|
|
188
|
+
});
|
|
189
|
+
} catch {
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
if (!response.ok) return null;
|
|
193
|
+
try {
|
|
194
|
+
return readExchangeResult(await response.json());
|
|
195
|
+
} catch {
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
function createLoginStartHandler(config) {
|
|
200
|
+
const resolved = resolveConfig(config);
|
|
201
|
+
return async function handleLoginStart(request) {
|
|
202
|
+
const state = generateState();
|
|
203
|
+
const now = Date.now();
|
|
204
|
+
const requested = new URL(request.url).searchParams.get(RETURN_TO_PARAM);
|
|
205
|
+
const base = { createdAt: now, expiresAt: now + STATE_TTL_MS };
|
|
206
|
+
await resolved.stateStore.set(
|
|
207
|
+
state,
|
|
208
|
+
requested === null ? base : { ...base, returnTo: requested },
|
|
209
|
+
STATE_TTL_MS
|
|
210
|
+
);
|
|
211
|
+
const authorize = new URL(AUTHORIZE_PATH, resolved.enlittOrigin);
|
|
212
|
+
authorize.searchParams.set("response_type", "code");
|
|
213
|
+
authorize.searchParams.set("client_id", resolved.clientId);
|
|
214
|
+
authorize.searchParams.set("redirect_uri", resolved.redirectUri);
|
|
215
|
+
authorize.searchParams.set("state", state);
|
|
216
|
+
return redirectTo(authorize.toString());
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
function createCallbackHandler(config) {
|
|
220
|
+
const resolved = resolveConfig(config);
|
|
221
|
+
const signedOut = () => redirectTo(new URL(resolved.defaultReturnTo, resolved.appOrigin).toString());
|
|
222
|
+
return async function handleCallback(request) {
|
|
223
|
+
const params = new URL(request.url).searchParams;
|
|
224
|
+
const state = params.get("state");
|
|
225
|
+
if (state === null || state.length === 0) return signedOut();
|
|
226
|
+
const record = await resolved.stateStore.consume(state);
|
|
227
|
+
if (record === null) return signedOut();
|
|
228
|
+
if (record.expiresAt <= Date.now()) return signedOut();
|
|
229
|
+
if (params.get("error") !== null) return signedOut();
|
|
230
|
+
const code = params.get("code");
|
|
231
|
+
if (code === null || code.length === 0) return signedOut();
|
|
232
|
+
const exchanged = await exchangeCode(resolved, code);
|
|
233
|
+
if (exchanged === null) return signedOut();
|
|
234
|
+
const destination = safeReturnPath(record.returnTo, resolved.appOrigin) ?? resolved.defaultReturnTo;
|
|
235
|
+
const response = redirectTo(new URL(destination, resolved.appOrigin).toString());
|
|
236
|
+
await resolved.onSignIn?.({ subject: exchanged.subject }, response);
|
|
237
|
+
response.headers.append("set-cookie", sessionCookie(resolved.cookieName, exchanged.sessionToken, exchanged.expiresInSeconds));
|
|
238
|
+
return response;
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
function createLogoutHandler(config) {
|
|
242
|
+
const resolved = resolveConfig(config);
|
|
243
|
+
return async function handleLogout(request) {
|
|
244
|
+
const token = readCookie(request, resolved.cookieName);
|
|
245
|
+
if (token !== null) {
|
|
246
|
+
try {
|
|
247
|
+
const authorization = resolveBusinessAuthorizationHeader(
|
|
248
|
+
resolved.secretKey === void 0 ? {} : { secretKey: resolved.secretKey }
|
|
249
|
+
);
|
|
250
|
+
await fetch(new URL(REVOKE_PATH, resolved.enlittApiOrigin), {
|
|
251
|
+
method: "POST",
|
|
252
|
+
headers: {
|
|
253
|
+
authorization,
|
|
254
|
+
[ENLITT_VERSION_HEADER]: ENLITT_API_VERSION,
|
|
255
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
256
|
+
accept: "application/json"
|
|
257
|
+
},
|
|
258
|
+
// The token travels in the body, never in the URL.
|
|
259
|
+
body: new URLSearchParams({ token, client_id: resolved.clientId })
|
|
260
|
+
});
|
|
261
|
+
} catch {
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
const requested = new URL(request.url).searchParams.get(RETURN_TO_PARAM);
|
|
265
|
+
const destination = safeReturnPath(requested, resolved.appOrigin) ?? resolved.defaultReturnTo;
|
|
266
|
+
return redirectTo(
|
|
267
|
+
new URL(destination, resolved.appOrigin).toString(),
|
|
268
|
+
clearedCookie(resolved.cookieName)
|
|
269
|
+
);
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export { createCallbackHandler, createLoginStartHandler, createLogoutHandler };
|
|
274
|
+
//# sourceMappingURL=server.js.map
|
|
275
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/callback.ts"],"names":[],"mappings":";;;;;;;AAmGA,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,GAAmB,gCAAA;AAMzB,SAAS,aAAA,GAAwB;AAC/B,EAAA,MAAM,SAAU,UAAA,CAAmC,MAAA;AACnD,EAAA,IAAI,CAAC,QAAQ,eAAA,EAAiB;AAC5B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAEF;AAAA,EACF;AAEA,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,E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;AACF,QAAA,MAAM,aAAA,GAAgB,kCAAA;AAAA,UACpB,QAAA,CAAS,cAAc,KAAA,CAAA,GAAY,KAAK,EAAE,SAAA,EAAW,SAAS,SAAA;AAAU,SAC1E;AACA,QAAA,MAAM,MAAM,IAAI,GAAA,CAAI,WAAA,EAAa,QAAA,CAAS,eAAe,CAAA,EAAG;AAAA,UAC1D,MAAA,EAAQ,MAAA;AAAA,UACR,OAAA,EAAS;AAAA,YACP,aAAA;AAAA,YACA,CAAC,qBAAqB,GAAG,kBAAA;AAAA,YACzB,cAAA,EAAgB,mCAAA;AAAA,YAChB,MAAA,EAAQ;AAAA,WACV;AAAA;AAAA,UAEA,IAAA,EAAM,IAAI,eAAA,CAAgB,EAAE,OAAO,SAAA,EAAW,QAAA,CAAS,UAAU;AAAA,SAClE,CAAA;AAAA,MACH,CAAA,CAAA,MAAQ;AAAA,MAGR;AAAA,IACF;AAEA,IAAA,MAAM,SAAA,GAAY,IAAI,GAAA,CAAI,OAAA,CAAQ,GAAG,CAAA,CAAE,YAAA,CAAa,IAAI,eAAe,CAAA;AACvE,IAAA,MAAM,cAAc,cAAA,CAAe,SAAA,EAAW,QAAA,CAAS,SAAS,KAAK,QAAA,CAAS,eAAA;AAE9E,IAAA,OAAO,UAAA;AAAA,MACL,IAAI,GAAA,CAAI,WAAA,EAAa,QAAA,CAAS,SAAS,EAAE,QAAA,EAAS;AAAA,MAClD,aAAA,CAAc,SAAS,UAAU;AAAA,KACnC;AAAA,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.\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 // 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 signedOut();\n const code = params.get(\"code\");\n if (code === null || code.length === 0) return signedOut();\n\n const exchanged = await exchangeCode(resolved, code);\n if (exchanged === null) return signedOut();\n\n const destination =\n safeReturnPath(record.returnTo, resolved.appOrigin) ?? resolved.defaultReturnTo;\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"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
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
|
+
* and the types a business writes down when it wraps `enlitt()` or builds a
|
|
7
|
+
* premium price. Shared construction options (`EnlittOptions`), errors, and
|
|
8
|
+
* session helpers are not redeclared here; they live in `@enlitt/sdk/core`.
|
|
9
|
+
*
|
|
10
|
+
* Everything reachable from here may read the business secret key, so the
|
|
11
|
+
* package export map resolves this subpath's `browser` condition to
|
|
12
|
+
* `server-unavailable.ts`.
|
|
13
|
+
*/
|
|
14
|
+
export { enlitt, ENLITT_STANDARD_MODEL, type EnlittPrice, type EnlittProviderOptions, type EnlittTarget, type PremiumPriceContext } from "./language-model.cjs";
|
|
15
|
+
export { perToken } from "./premium-language-model.cjs";
|
|
@@ -0,0 +1,16 @@
|
|
|
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
|
+
* and the types a business writes down when it wraps `enlitt()` or builds a
|
|
7
|
+
* premium price. Shared construction options (`EnlittOptions`), errors, and
|
|
8
|
+
* session helpers are not redeclared here; they live in `@enlitt/sdk/core`.
|
|
9
|
+
*
|
|
10
|
+
* Everything reachable from here may read the business secret key, so the
|
|
11
|
+
* package export map resolves this subpath's `browser` condition to
|
|
12
|
+
* `server-unavailable.ts`.
|
|
13
|
+
*/
|
|
14
|
+
export { enlitt, ENLITT_STANDARD_MODEL, type EnlittPrice, type EnlittProviderOptions, type EnlittTarget, type PremiumPriceContext } from "./language-model.js";
|
|
15
|
+
export { perToken } from "./premium-language-model.js";
|
|
16
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/vercel/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;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"}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import type { LanguageModelV3, LanguageModelV3CallOptions, LanguageModelV3Content, LanguageModelV3FinishReason, LanguageModelV3StreamPart, LanguageModelV3Usage, SharedV3ProviderMetadata, SharedV3ProviderOptions } 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
|
+
export type EnlittTarget = typeof ENLITT_STANDARD_MODEL | LanguageModelV3;
|
|
19
|
+
/**
|
|
20
|
+
* The only public model factory in this package.
|
|
21
|
+
*
|
|
22
|
+
* `enlitt("enlitt-standard")` returns Enlitt's own standard model;
|
|
23
|
+
* `enlitt(myProviderModel)` returns transparent middleware around it in
|
|
24
|
+
* premium mode. Both modes require the business's application secret, resolved
|
|
25
|
+
* once here by `createInternalClient()`, which also asserts a server runtime
|
|
26
|
+
* (before any secret is touched) and resolves and validates the base URL once.
|
|
27
|
+
* A missing or invalid secret is an `EnlittConfigurationError` thrown before the
|
|
28
|
+
* first request, in premium exactly as in standard. There is no configuration
|
|
29
|
+
* under which this function returns a model that would reach a provider without
|
|
30
|
+
* Enlitt: a business whose configuration silently degraded would pay for its
|
|
31
|
+
* users' premium calls and see nothing wrong until the provider bill arrived.
|
|
32
|
+
*
|
|
33
|
+
* It builds exactly one internal client per call and hands it to whichever
|
|
34
|
+
* model it returns. `EnlittOptions` is declared once, in core, and shared with
|
|
35
|
+
* `withPremiumCharge()` and `usage()`.
|
|
36
|
+
*/
|
|
37
|
+
export declare function enlitt(target: EnlittTarget, options?: EnlittOptions): LanguageModelV3;
|
|
38
|
+
/**
|
|
39
|
+
* What a premium call states it costs: a constant NANOUSD amount, or a
|
|
40
|
+
* function that computes one once the call has ended. A function runs exactly
|
|
41
|
+
* once per operation, only when the call ends `completed` or `canceled`, may be
|
|
42
|
+
* async, and is never called for `failed`, which reports `"0"`.
|
|
43
|
+
*/
|
|
44
|
+
export type EnlittPrice = string | ((context: PremiumPriceContext) => string | Promise<string>);
|
|
45
|
+
/**
|
|
46
|
+
* Everything the SDK knows when a premium call ends, and nothing it does not.
|
|
47
|
+
* It never leaves the business's process.
|
|
48
|
+
*/
|
|
49
|
+
export interface PremiumPriceContext {
|
|
50
|
+
readonly status: "completed" | "canceled";
|
|
51
|
+
/**
|
|
52
|
+
* For `doGenerate`, the result's content. For `doStream`, every part the
|
|
53
|
+
* provider emitted up to its end or the cancellation, in order. Stream parts
|
|
54
|
+
* are collected only when `price` is a function.
|
|
55
|
+
*/
|
|
56
|
+
readonly output: {
|
|
57
|
+
readonly kind: "generate";
|
|
58
|
+
readonly content: readonly LanguageModelV3Content[];
|
|
59
|
+
} | {
|
|
60
|
+
readonly kind: "stream";
|
|
61
|
+
readonly parts: readonly LanguageModelV3StreamPart[];
|
|
62
|
+
};
|
|
63
|
+
/** Possibly absent on a cancellation. */
|
|
64
|
+
readonly usage?: LanguageModelV3Usage;
|
|
65
|
+
/** Absent on a cancellation before a finish part. */
|
|
66
|
+
readonly finishReason?: LanguageModelV3FinishReason;
|
|
67
|
+
readonly providerMetadata?: SharedV3ProviderMetadata;
|
|
68
|
+
/** Provider invocation start. */
|
|
69
|
+
readonly startedAt: Date;
|
|
70
|
+
/** The end or cancellation instant. */
|
|
71
|
+
readonly endedAt: Date;
|
|
72
|
+
readonly durationMs: number;
|
|
73
|
+
/** Present only for a stream that emitted a content part. */
|
|
74
|
+
readonly timeToFirstTokenMs?: number;
|
|
75
|
+
/** The bound every price for this call is lowered to; it may be below the declared `maxCharge`. */
|
|
76
|
+
readonly effectiveMaxChargeNanoUsd: string;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The validated result of `readEnlittCallOptions()`: `providerOptions.enlitt`
|
|
80
|
+
* as the SDK works with it. Every field is optional at the type level because
|
|
81
|
+
* validity depends on `mode`; `readEnlittCallOptions()` is the one place that
|
|
82
|
+
* mode-dependent shape is enforced.
|
|
83
|
+
*/
|
|
84
|
+
export interface EnlittProviderOptions {
|
|
85
|
+
/** A base for the call identity, not the identity itself; see `resolveCallId()`. 16-200 visible ASCII characters. */
|
|
86
|
+
idempotencyKey?: string;
|
|
87
|
+
/** NANOUSD, premium only. Required unless `price` is a constant, in which case it defaults to that constant. */
|
|
88
|
+
maxCharge?: string;
|
|
89
|
+
/** Premium only. Without it a call charges `"0"` for every status. */
|
|
90
|
+
price?: EnlittPrice;
|
|
91
|
+
/** Premium only. How long the business needs before it will report the terminal outcome. */
|
|
92
|
+
reportingDeadlineMs?: number;
|
|
93
|
+
/** At most 16 entries, keys at most 64 characters, values at most 512, no key beginning with `enlitt_`. */
|
|
94
|
+
metadata?: Record<string, string>;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Runtime-validates `providerOptions.enlitt` on every invocation. There is no
|
|
98
|
+
* `managed` parameter and no unmanaged case: every call in either mode is
|
|
99
|
+
* managed. Every failure is an `EnlittConfigurationError` raised before any
|
|
100
|
+
* Enlitt or provider request, and other provider namespaces are never touched.
|
|
101
|
+
*
|
|
102
|
+
* Premium combinations: a constant `price` alone sets `maxCharge` to it;
|
|
103
|
+
* `maxCharge` alone charges `"0"`; a function `price` without `maxCharge` is
|
|
104
|
+
* rejected (a function's result is only known after the provider has run and
|
|
105
|
+
* the maximum must be known before); a constant `price` above `maxCharge` is
|
|
106
|
+
* rejected (it could never be charged in full); neither is rejected.
|
|
107
|
+
*/
|
|
108
|
+
export declare function readEnlittCallOptions(providerOptions: SharedV3ProviderOptions | undefined, mode: "standard" | "premium"): EnlittProviderOptions;
|
|
109
|
+
/**
|
|
110
|
+
* Derives the one identity of a single underlying model invocation. Sent as
|
|
111
|
+
* `Idempotency-Key` on both paths and as `call_id` (via the same
|
|
112
|
+
* `Idempotency-Key`) on the premium preflight; there is no second identifier.
|
|
113
|
+
*
|
|
114
|
+
* `callId` is `` `${base}.${params.prompt.length}` ``, where `base` is
|
|
115
|
+
* `options.idempotencyKey` when supplied and otherwise a freshly generated
|
|
116
|
+
* random value unique per invocation. The suffix — the count of prompt items,
|
|
117
|
+
* never a hash or any other read of content — is what makes the identity
|
|
118
|
+
* behave correctly in a tool loop: within one `generateText` loop the prompt
|
|
119
|
+
* grows by at least one item before each subsequent provider invocation, so
|
|
120
|
+
* distinct steps get distinct IDs, while a retry of the same step
|
|
121
|
+
* re-presents the identical prompt and so reuses the ID.
|
|
122
|
+
*
|
|
123
|
+
* The resulting ID is validated against the protocol's own 16-255
|
|
124
|
+
* visible-ASCII `Idempotency-Key` bound before it is returned, converting a
|
|
125
|
+
* violation into `EnlittConfigurationError` rather than sending an
|
|
126
|
+
* out-of-bounds header. With `idempotencyKey` bounded at the protocol's own
|
|
127
|
+
* floor by `readEnlittCallOptions()`, no reachable input violates that bound;
|
|
128
|
+
* the check stays as the one place the wire rule is enforced, so a future
|
|
129
|
+
* change to either end cannot ship an out-of-bounds header silently.
|
|
130
|
+
*/
|
|
131
|
+
export declare function resolveCallId(options: EnlittProviderOptions, params: LanguageModelV3CallOptions): string;
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import type { LanguageModelV3, LanguageModelV3CallOptions, LanguageModelV3Content, LanguageModelV3FinishReason, LanguageModelV3StreamPart, LanguageModelV3Usage, SharedV3ProviderMetadata, SharedV3ProviderOptions } 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
|
+
export type EnlittTarget = typeof ENLITT_STANDARD_MODEL | LanguageModelV3;
|
|
19
|
+
/**
|
|
20
|
+
* The only public model factory in this package.
|
|
21
|
+
*
|
|
22
|
+
* `enlitt("enlitt-standard")` returns Enlitt's own standard model;
|
|
23
|
+
* `enlitt(myProviderModel)` returns transparent middleware around it in
|
|
24
|
+
* premium mode. Both modes require the business's application secret, resolved
|
|
25
|
+
* once here by `createInternalClient()`, which also asserts a server runtime
|
|
26
|
+
* (before any secret is touched) and resolves and validates the base URL once.
|
|
27
|
+
* A missing or invalid secret is an `EnlittConfigurationError` thrown before the
|
|
28
|
+
* first request, in premium exactly as in standard. There is no configuration
|
|
29
|
+
* under which this function returns a model that would reach a provider without
|
|
30
|
+
* Enlitt: a business whose configuration silently degraded would pay for its
|
|
31
|
+
* users' premium calls and see nothing wrong until the provider bill arrived.
|
|
32
|
+
*
|
|
33
|
+
* It builds exactly one internal client per call and hands it to whichever
|
|
34
|
+
* model it returns. `EnlittOptions` is declared once, in core, and shared with
|
|
35
|
+
* `withPremiumCharge()` and `usage()`.
|
|
36
|
+
*/
|
|
37
|
+
export declare function enlitt(target: EnlittTarget, options?: EnlittOptions): LanguageModelV3;
|
|
38
|
+
/**
|
|
39
|
+
* What a premium call states it costs: a constant NANOUSD amount, or a
|
|
40
|
+
* function that computes one once the call has ended. A function runs exactly
|
|
41
|
+
* once per operation, only when the call ends `completed` or `canceled`, may be
|
|
42
|
+
* async, and is never called for `failed`, which reports `"0"`.
|
|
43
|
+
*/
|
|
44
|
+
export type EnlittPrice = string | ((context: PremiumPriceContext) => string | Promise<string>);
|
|
45
|
+
/**
|
|
46
|
+
* Everything the SDK knows when a premium call ends, and nothing it does not.
|
|
47
|
+
* It never leaves the business's process.
|
|
48
|
+
*/
|
|
49
|
+
export interface PremiumPriceContext {
|
|
50
|
+
readonly status: "completed" | "canceled";
|
|
51
|
+
/**
|
|
52
|
+
* For `doGenerate`, the result's content. For `doStream`, every part the
|
|
53
|
+
* provider emitted up to its end or the cancellation, in order. Stream parts
|
|
54
|
+
* are collected only when `price` is a function.
|
|
55
|
+
*/
|
|
56
|
+
readonly output: {
|
|
57
|
+
readonly kind: "generate";
|
|
58
|
+
readonly content: readonly LanguageModelV3Content[];
|
|
59
|
+
} | {
|
|
60
|
+
readonly kind: "stream";
|
|
61
|
+
readonly parts: readonly LanguageModelV3StreamPart[];
|
|
62
|
+
};
|
|
63
|
+
/** Possibly absent on a cancellation. */
|
|
64
|
+
readonly usage?: LanguageModelV3Usage;
|
|
65
|
+
/** Absent on a cancellation before a finish part. */
|
|
66
|
+
readonly finishReason?: LanguageModelV3FinishReason;
|
|
67
|
+
readonly providerMetadata?: SharedV3ProviderMetadata;
|
|
68
|
+
/** Provider invocation start. */
|
|
69
|
+
readonly startedAt: Date;
|
|
70
|
+
/** The end or cancellation instant. */
|
|
71
|
+
readonly endedAt: Date;
|
|
72
|
+
readonly durationMs: number;
|
|
73
|
+
/** Present only for a stream that emitted a content part. */
|
|
74
|
+
readonly timeToFirstTokenMs?: number;
|
|
75
|
+
/** The bound every price for this call is lowered to; it may be below the declared `maxCharge`. */
|
|
76
|
+
readonly effectiveMaxChargeNanoUsd: string;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The validated result of `readEnlittCallOptions()`: `providerOptions.enlitt`
|
|
80
|
+
* as the SDK works with it. Every field is optional at the type level because
|
|
81
|
+
* validity depends on `mode`; `readEnlittCallOptions()` is the one place that
|
|
82
|
+
* mode-dependent shape is enforced.
|
|
83
|
+
*/
|
|
84
|
+
export interface EnlittProviderOptions {
|
|
85
|
+
/** A base for the call identity, not the identity itself; see `resolveCallId()`. 16-200 visible ASCII characters. */
|
|
86
|
+
idempotencyKey?: string;
|
|
87
|
+
/** NANOUSD, premium only. Required unless `price` is a constant, in which case it defaults to that constant. */
|
|
88
|
+
maxCharge?: string;
|
|
89
|
+
/** Premium only. Without it a call charges `"0"` for every status. */
|
|
90
|
+
price?: EnlittPrice;
|
|
91
|
+
/** Premium only. How long the business needs before it will report the terminal outcome. */
|
|
92
|
+
reportingDeadlineMs?: number;
|
|
93
|
+
/** At most 16 entries, keys at most 64 characters, values at most 512, no key beginning with `enlitt_`. */
|
|
94
|
+
metadata?: Record<string, string>;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Runtime-validates `providerOptions.enlitt` on every invocation. There is no
|
|
98
|
+
* `managed` parameter and no unmanaged case: every call in either mode is
|
|
99
|
+
* managed. Every failure is an `EnlittConfigurationError` raised before any
|
|
100
|
+
* Enlitt or provider request, and other provider namespaces are never touched.
|
|
101
|
+
*
|
|
102
|
+
* Premium combinations: a constant `price` alone sets `maxCharge` to it;
|
|
103
|
+
* `maxCharge` alone charges `"0"`; a function `price` without `maxCharge` is
|
|
104
|
+
* rejected (a function's result is only known after the provider has run and
|
|
105
|
+
* the maximum must be known before); a constant `price` above `maxCharge` is
|
|
106
|
+
* rejected (it could never be charged in full); neither is rejected.
|
|
107
|
+
*/
|
|
108
|
+
export declare function readEnlittCallOptions(providerOptions: SharedV3ProviderOptions | undefined, mode: "standard" | "premium"): EnlittProviderOptions;
|
|
109
|
+
/**
|
|
110
|
+
* Derives the one identity of a single underlying model invocation. Sent as
|
|
111
|
+
* `Idempotency-Key` on both paths and as `call_id` (via the same
|
|
112
|
+
* `Idempotency-Key`) on the premium preflight; there is no second identifier.
|
|
113
|
+
*
|
|
114
|
+
* `callId` is `` `${base}.${params.prompt.length}` ``, where `base` is
|
|
115
|
+
* `options.idempotencyKey` when supplied and otherwise a freshly generated
|
|
116
|
+
* random value unique per invocation. The suffix — the count of prompt items,
|
|
117
|
+
* never a hash or any other read of content — is what makes the identity
|
|
118
|
+
* behave correctly in a tool loop: within one `generateText` loop the prompt
|
|
119
|
+
* grows by at least one item before each subsequent provider invocation, so
|
|
120
|
+
* distinct steps get distinct IDs, while a retry of the same step
|
|
121
|
+
* re-presents the identical prompt and so reuses the ID.
|
|
122
|
+
*
|
|
123
|
+
* The resulting ID is validated against the protocol's own 16-255
|
|
124
|
+
* visible-ASCII `Idempotency-Key` bound before it is returned, converting a
|
|
125
|
+
* violation into `EnlittConfigurationError` rather than sending an
|
|
126
|
+
* out-of-bounds header. With `idempotencyKey` bounded at the protocol's own
|
|
127
|
+
* floor by `readEnlittCallOptions()`, no reachable input violates that bound;
|
|
128
|
+
* the check stays as the one place the wire rule is enforced, so a future
|
|
129
|
+
* change to either end cannot ship an out-of-bounds header silently.
|
|
130
|
+
*/
|
|
131
|
+
export declare function resolveCallId(options: EnlittProviderOptions, params: LanguageModelV3CallOptions): string;
|
|
132
|
+
//# 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,eAAe,EACf,0BAA0B,EAC1B,sBAAsB,EACtB,2BAA2B,EAC3B,yBAAyB,EACzB,oBAAoB,EACpB,wBAAwB,EACxB,uBAAuB,EACxB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAUzD,OAAO,EAAwB,KAAK,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAIhF;;;;;;GAMG;AACH,OAAO,EAAE,qBAAqB,EAAE,CAAC;AAEjC;;;;;GAKG;AACH,MAAM,MAAM,YAAY,GAAG,OAAO,qBAAqB,GAAG,eAAe,CAAC;AAE1E;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,MAAM,CAAC,MAAM,EAAE,YAAY,EAAE,OAAO,GAAE,aAAkB,GAAG,eAAe,CAOzF;AAID;;;;;GAKG;AACH,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,CAAC,CAAC,OAAO,EAAE,mBAAmB,KAAK,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;AAEhG;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,MAAM,EAAE,WAAW,GAAG,UAAU,CAAC;IAC1C;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EACX;QAAE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;QAAC,QAAQ,CAAC,OAAO,EAAE,SAAS,sBAAsB,EAAE,CAAA;KA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