@enlitt/sdk 0.1.0 → 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.
Files changed (72) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +3 -1
  3. package/dist/{chunk-C76K6HLL.cjs → chunk-2BGWYTJM.cjs} +240 -49
  4. package/dist/chunk-2BGWYTJM.cjs.map +1 -0
  5. package/dist/{chunk-VNVMEU34.js → chunk-NI6WH5FI.js} +3 -3
  6. package/dist/{chunk-VNVMEU34.js.map → chunk-NI6WH5FI.js.map} +1 -1
  7. package/dist/{chunk-6DPBYLA5.js → chunk-O6ASIA3X.js} +19 -8
  8. package/dist/chunk-O6ASIA3X.js.map +1 -0
  9. package/dist/{chunk-26SW63P5.cjs → chunk-PPOUNWNA.cjs} +19 -7
  10. package/dist/chunk-PPOUNWNA.cjs.map +1 -0
  11. package/dist/{chunk-SFI4RLNN.js → chunk-UVZMKGIL.js} +198 -7
  12. package/dist/chunk-UVZMKGIL.js.map +1 -0
  13. package/dist/{chunk-G4DTTV5E.cjs → chunk-YPA4R65T.cjs} +7 -7
  14. package/dist/{chunk-G4DTTV5E.cjs.map → chunk-YPA4R65T.cjs.map} +1 -1
  15. package/dist/core/errors.d.cts +13 -5
  16. package/dist/core/errors.d.ts +13 -5
  17. package/dist/core/errors.d.ts.map +1 -1
  18. package/dist/core/index.d.cts +1 -1
  19. package/dist/core/index.d.ts +1 -1
  20. package/dist/core/index.d.ts.map +1 -1
  21. package/dist/core/session.d.cts +15 -0
  22. package/dist/core/session.d.ts +15 -0
  23. package/dist/core/session.d.ts.map +1 -1
  24. package/dist/core/transport.d.cts +1 -1
  25. package/dist/core/transport.d.ts +1 -1
  26. package/dist/core.cjs +22 -18
  27. package/dist/core.js +2 -2
  28. package/dist/openai/client.d.cts +25 -1
  29. package/dist/openai/client.d.ts +25 -1
  30. package/dist/openai/client.d.ts.map +1 -1
  31. package/dist/openai/index.d.cts +1 -0
  32. package/dist/openai/index.d.ts +1 -0
  33. package/dist/openai/index.d.ts.map +1 -1
  34. package/dist/openai/media.d.cts +108 -0
  35. package/dist/openai/media.d.ts +109 -0
  36. package/dist/openai/media.d.ts.map +1 -0
  37. package/dist/openai.cjs +191 -47
  38. package/dist/openai.cjs.map +1 -1
  39. package/dist/openai.js +145 -1
  40. package/dist/openai.js.map +1 -1
  41. package/dist/server/callback.d.cts +2 -1
  42. package/dist/server/callback.d.ts +2 -1
  43. package/dist/server/callback.d.ts.map +1 -1
  44. package/dist/server/client-sign-in.d.cts +77 -0
  45. package/dist/server/client-sign-in.d.ts +78 -0
  46. package/dist/server/client-sign-in.d.ts.map +1 -0
  47. package/dist/server/index.d.cts +2 -1
  48. package/dist/server/index.d.ts +2 -1
  49. package/dist/server/index.d.ts.map +1 -1
  50. package/dist/server.cjs +555 -29
  51. package/dist/server.cjs.map +1 -1
  52. package/dist/server.js +529 -9
  53. package/dist/server.js.map +1 -1
  54. package/dist/vercel/index.d.cts +4 -2
  55. package/dist/vercel/index.d.ts +4 -2
  56. package/dist/vercel/index.d.ts.map +1 -1
  57. package/dist/vercel/language-model.d.cts +17 -2
  58. package/dist/vercel/language-model.d.ts +17 -2
  59. package/dist/vercel/language-model.d.ts.map +1 -1
  60. package/dist/vercel/premium-language-model.d.cts +30 -1
  61. package/dist/vercel/premium-language-model.d.ts +30 -1
  62. package/dist/vercel/premium-language-model.d.ts.map +1 -1
  63. package/dist/vercel/premium-media-model.d.cts +101 -0
  64. package/dist/vercel/premium-media-model.d.ts +102 -0
  65. package/dist/vercel/premium-media-model.d.ts.map +1 -0
  66. package/dist/vercel.cjs +5 -5
  67. package/dist/vercel.js +2 -2
  68. package/package.json +12 -2
  69. package/dist/chunk-26SW63P5.cjs.map +0 -1
  70. package/dist/chunk-6DPBYLA5.js.map +0 -1
  71. package/dist/chunk-C76K6HLL.cjs.map +0 -1
  72. package/dist/chunk-SFI4RLNN.js.map +0 -1
package/dist/server.js CHANGED
@@ -1,9 +1,10 @@
1
- export { usage } from './chunk-VNVMEU34.js';
2
- export { ENLITT_STANDARD_MODEL, enlitt, perToken } from './chunk-SFI4RLNN.js';
1
+ export { usage } from './chunk-NI6WH5FI.js';
2
+ export { ENLITT_STANDARD_MODEL, enlitt, perToken } from './chunk-UVZMKGIL.js';
3
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';
4
+ import { resolveBusinessAuthorizationHeader, ENLITT_SESSION_COOKIE_NAME, ENLITT_SESSION_HEADER_NAME, EnlittConfigurationError } from './chunk-O6ASIA3X.js';
5
+ export { ENLITT_SESSION_COOKIE_NAME, ENLITT_SESSION_HEADER_NAME, EnlittAuthenticationError, EnlittAuthorizationError, EnlittConfigurationError, EnlittError, EnlittInsufficientCreditsError, EnlittLimitExceededError, EnlittLoginRequiredError, EnlittRateLimitError, EnlittSubscriptionInactiveError, enlittSession, enlittSessionMiddleware, getEnlittSession, runWithEnlittSession, withPremiumCharge } from './chunk-O6ASIA3X.js';
6
6
  import { ENLITT_VERSION_HEADER, ENLITT_API_VERSION, validateAuthorizationExchangeResponse } from '@enlitt/protocol';
7
+ import { randomBytes, randomInt, timingSafeEqual, createHash } from 'crypto';
7
8
 
8
9
  var DEFAULT_ENLITT_ORIGIN = "https://enlitt.com";
9
10
  var AUTHORIZE_PATH = "/auth/oauth2/authorize";
@@ -226,12 +227,13 @@ function createCallbackHandler(config) {
226
227
  const record = await resolved.stateStore.consume(state);
227
228
  if (record === null) return signedOut();
228
229
  if (record.expiresAt <= Date.now()) return signedOut();
229
- if (params.get("error") !== null) return signedOut();
230
+ const destination = safeReturnPath(record.returnTo, resolved.appOrigin) ?? resolved.defaultReturnTo;
231
+ const signedOutToDestination = () => redirectTo(new URL(destination, resolved.appOrigin).toString());
232
+ if (params.get("error") !== null) return signedOutToDestination();
230
233
  const code = params.get("code");
231
- if (code === null || code.length === 0) return signedOut();
234
+ if (code === null || code.length === 0) return signedOutToDestination();
232
235
  const exchanged = await exchangeCode(resolved, code);
233
- if (exchanged === null) return signedOut();
234
- const destination = safeReturnPath(record.returnTo, resolved.appOrigin) ?? resolved.defaultReturnTo;
236
+ if (exchanged === null) return signedOutToDestination();
235
237
  const response = redirectTo(new URL(destination, resolved.appOrigin).toString());
236
238
  await resolved.onSignIn?.({ subject: exchanged.subject }, response);
237
239
  response.headers.append("set-cookie", sessionCookie(resolved.cookieName, exchanged.sessionToken, exchanged.expiresInSeconds));
@@ -269,7 +271,525 @@ function createLogoutHandler(config) {
269
271
  );
270
272
  };
271
273
  }
274
+ var HANDOFF_TTL_MS = 10 * 60 * 1e3;
275
+ var PAIRING_TTL_MS = 10 * 60 * 1e3;
276
+ var CODE_TTL_MS = 5 * 60 * 1e3;
277
+ var PAIRING_INTERVAL_SECONDS = 5;
278
+ var USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXZ";
279
+ var USER_CODE_LENGTH = 8;
280
+ var CSRF_COOKIE_NAME = "enlitt_pair_csrf";
281
+ var STATE_PATTERN = /^[A-Za-z0-9._~-]{1,128}$/;
282
+ var CODE_VERIFIER_PATTERN = /^[A-Za-z0-9._~-]{43,128}$/;
283
+ var CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
284
+ var RANDOM_ID_PATTERN = /^[A-Za-z0-9_-]{43}$/;
285
+ var FORBIDDEN_SCHEMES = /* @__PURE__ */ new Set(["http", "javascript", "data", "file", "vbscript"]);
286
+ var MAX_LOGOUT_TOKEN_LENGTH = 4096;
287
+ function createMemoryClientSignInStore(options = {}) {
288
+ const now = options.now ?? Date.now;
289
+ const entries = /* @__PURE__ */ new Map();
290
+ function live(key) {
291
+ const entry = entries.get(key);
292
+ if (entry !== void 0 && entry.expiresAt <= now()) {
293
+ entries.delete(key);
294
+ return void 0;
295
+ }
296
+ return entry;
297
+ }
298
+ return {
299
+ set(key, value, ttlMs) {
300
+ if (entries.size > 1e3) {
301
+ for (const existing of [...entries.keys()]) live(existing);
302
+ }
303
+ entries.set(key, { value, expiresAt: now() + ttlMs });
304
+ },
305
+ get(key) {
306
+ return live(key)?.value ?? null;
307
+ },
308
+ consume(key) {
309
+ const entry = live(key);
310
+ entries.delete(key);
311
+ return entry?.value ?? null;
312
+ }
313
+ };
314
+ }
315
+ function randomId() {
316
+ return randomBytes(32).toString("base64url");
317
+ }
318
+ function challengeOf(verifier) {
319
+ return createHash("sha256").update(verifier, "ascii").digest("base64url");
320
+ }
321
+ function safeEqual(left, right) {
322
+ const a = Buffer.from(left);
323
+ const b = Buffer.from(right);
324
+ return a.length === b.length && timingSafeEqual(a, b);
325
+ }
326
+ function randomUserCode() {
327
+ let code = "";
328
+ for (let i = 0; i < USER_CODE_LENGTH; i += 1) {
329
+ code += USER_CODE_ALPHABET[randomInt(USER_CODE_ALPHABET.length)];
330
+ }
331
+ return code;
332
+ }
333
+ function formatUserCode(code) {
334
+ return `${code.slice(0, 4)}-${code.slice(4)}`;
335
+ }
336
+ function normalizeUserCode(input) {
337
+ return input.toUpperCase().replace(/[^A-Z]/g, "");
338
+ }
339
+ function escapeHtml(value) {
340
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
341
+ }
342
+ function parseRecord(text) {
343
+ if (text === null) return null;
344
+ try {
345
+ const parsed = JSON.parse(text);
346
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
347
+ } catch {
348
+ return null;
349
+ }
350
+ }
351
+ function readHandoff(text) {
352
+ const record = parseRecord(text);
353
+ if (record === null || typeof record.codeChallenge !== "string") return null;
354
+ const target = record.target;
355
+ if (typeof target !== "object" || target === null) return null;
356
+ if (target.mode === "loopback" && typeof target.port === "number") {
357
+ return record;
358
+ }
359
+ if (target.mode === "redirect" && typeof target.redirectUri === "string") {
360
+ return record;
361
+ }
362
+ if (target.mode === "pairing" && typeof target.pairingId === "string") {
363
+ return record;
364
+ }
365
+ return null;
366
+ }
367
+ function readCode(text) {
368
+ const record = parseRecord(text);
369
+ if (record === null || typeof record.sessionToken !== "string" || typeof record.codeChallenge !== "string") {
370
+ return null;
371
+ }
372
+ return { sessionToken: record.sessionToken, codeChallenge: record.codeChallenge };
373
+ }
374
+ function readPairing(text) {
375
+ const record = parseRecord(text);
376
+ if (record === null || record.status !== "pending" && record.status !== "ready" && record.status !== "denied" || typeof record.codeChallenge !== "string" || typeof record.userCode !== "string" || typeof record.expiresAt !== "number") {
377
+ return null;
378
+ }
379
+ return record;
380
+ }
381
+ function readCookie2(request, name) {
382
+ const header = request.headers.get("cookie");
383
+ if (header === null) return null;
384
+ for (const part of header.split(";")) {
385
+ const separator = part.indexOf("=");
386
+ if (separator === -1 || part.slice(0, separator).trim() !== name) continue;
387
+ const raw = part.slice(separator + 1).trim();
388
+ try {
389
+ return decodeURIComponent(raw);
390
+ } catch {
391
+ return raw;
392
+ }
393
+ }
394
+ return null;
395
+ }
396
+ var PAGE_HEADERS = {
397
+ "Content-Type": "text/html; charset=utf-8",
398
+ "Cache-Control": "no-store",
399
+ "X-Frame-Options": "DENY",
400
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'",
401
+ "Referrer-Policy": "no-referrer"
402
+ };
403
+ function htmlPage(status, title, body, extraHeaders = new Headers()) {
404
+ const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title><style>body{font-family:system-ui,sans-serif;max-width:32rem;margin:3rem auto;padding:0 1rem;line-height:1.5}button,input{font:inherit;padding:.5rem 1rem;margin:.25rem 0}.code{font-size:2rem;letter-spacing:.2em;font-weight:600}</style></head><body>${body}</body></html>`;
405
+ const headers = new Headers(extraHeaders);
406
+ for (const [name, value] of Object.entries(PAGE_HEADERS)) headers.set(name, value);
407
+ return new Response(html, { status, headers });
408
+ }
409
+ function invalidRequestPage() {
410
+ return htmlPage(
411
+ 400,
412
+ "Sign-in unavailable",
413
+ "<p>This sign-in request is not valid. Go back to the app and try again.</p>"
414
+ );
415
+ }
416
+ function expiredPage() {
417
+ return htmlPage(
418
+ 400,
419
+ "Sign-in expired",
420
+ "<p>This sign-in link has expired. Go back to the app and try again.</p>"
421
+ );
422
+ }
423
+ function jsonResponse(status, body) {
424
+ return new Response(JSON.stringify(body), {
425
+ status,
426
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
427
+ });
428
+ }
429
+ function tokenError(error) {
430
+ return jsonResponse(400, { error });
431
+ }
432
+ async function readJsonObject(request) {
433
+ const contentType = request.headers.get("content-type") ?? "";
434
+ if (!contentType.toLowerCase().startsWith("application/json")) return null;
435
+ try {
436
+ const parsed = await request.json();
437
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
438
+ } catch {
439
+ return null;
440
+ }
441
+ }
442
+ function hasExactKeys(object, keys) {
443
+ const actual = Object.keys(object);
444
+ return actual.length === keys.length && keys.every((key) => Object.prototype.hasOwnProperty.call(object, key));
445
+ }
446
+ function checkReturnUrl(entry) {
447
+ const refuse = () => {
448
+ throw new EnlittConfigurationError(
449
+ `createClientSignInHandler(): returnUrls entry ${JSON.stringify(entry)} must be an absolute https: URL or a private-use reverse-DNS scheme (for example com.example.game://auth), without a fragment.`
450
+ );
451
+ };
452
+ if (typeof entry !== "string" || entry.includes("#")) return refuse();
453
+ try {
454
+ new URL(entry);
455
+ } catch {
456
+ return refuse();
457
+ }
458
+ const colon = entry.indexOf(":");
459
+ const scheme = entry.slice(0, colon);
460
+ if (scheme === "https") return;
461
+ if (!/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/.test(scheme) || FORBIDDEN_SCHEMES.has(scheme)) {
462
+ return refuse();
463
+ }
464
+ }
465
+ function checkConfig(config) {
466
+ const { basePath } = config;
467
+ if (typeof basePath !== "string" || !basePath.startsWith("/") || basePath.endsWith("/") || basePath.includes("?") || basePath.includes("#")) {
468
+ throw new EnlittConfigurationError(
469
+ "createClientSignInHandler(): basePath must start with '/', must not end with '/', and must not contain '?' or '#'."
470
+ );
471
+ }
472
+ for (const entry of config.returnUrls ?? []) checkReturnUrl(entry);
473
+ const loopback = config.loopback ?? true;
474
+ if (!loopback && (config.returnUrls ?? []).length === 0 && config.pairing !== true) {
475
+ throw new EnlittConfigurationError(
476
+ "createClientSignInHandler(): enable at least one of loopback, returnUrls, or pairing."
477
+ );
478
+ }
479
+ if (typeof config.appName !== "string" || config.appName.length < 1 || config.appName.length > 60) {
480
+ throw new EnlittConfigurationError(
481
+ "createClientSignInHandler(): appName must be 1-60 characters."
482
+ );
483
+ }
484
+ }
485
+ function createClientSignInHandler(config) {
486
+ checkConfig(config);
487
+ const { store, basePath, appName } = config;
488
+ const loopbackEnabled = config.loopback ?? true;
489
+ const returnUrls = config.returnUrls ?? [];
490
+ const pairingEnabled = config.pairing === true;
491
+ const appOrigin = new URL(config.callback.appOrigin).origin;
492
+ const cookieName = config.callback.cookieName ?? ENLITT_SESSION_COOKIE_NAME;
493
+ const loginStart = createLoginStartHandler(config.callback);
494
+ const logoutHandler = createLogoutHandler(config.callback);
495
+ const clearSessionCookie = `${cookieName}=; Max-Age=0; Path=/; HttpOnly; Secure; SameSite=Lax`;
496
+ function redirectClearingCookie(location) {
497
+ const headers = new Headers({
498
+ Location: location,
499
+ "Cache-Control": "no-store",
500
+ "Referrer-Policy": "no-referrer"
501
+ });
502
+ headers.append("Set-Cookie", clearSessionCookie);
503
+ return new Response(null, { status: 303, headers });
504
+ }
505
+ async function beginLogin(handoff) {
506
+ const id = randomId();
507
+ await store.set(`h:${id}`, JSON.stringify(handoff), HANDOFF_TTL_MS);
508
+ const returnTo = `${basePath}/complete?${new URLSearchParams({ h: id }).toString()}`;
509
+ const internal = new Request(
510
+ `${appOrigin}${basePath}/start?${new URLSearchParams({ return_to: returnTo }).toString()}`,
511
+ { method: "GET" }
512
+ );
513
+ const response = await loginStart(internal);
514
+ const headers = new Headers(response.headers);
515
+ headers.append("Set-Cookie", clearSessionCookie);
516
+ return new Response(response.body, {
517
+ status: response.status,
518
+ statusText: response.statusText,
519
+ headers
520
+ });
521
+ }
522
+ async function start(url) {
523
+ const params = url.searchParams;
524
+ const names = [...params.keys()];
525
+ if (new Set(names).size !== names.length) return invalidRequestPage();
526
+ const mode = params.get("mode");
527
+ const allowed = ["mode", "state", "code_challenge", "code_challenge_method"];
528
+ if (mode === "loopback" && loopbackEnabled) allowed.push("port");
529
+ else if (mode === "redirect" && returnUrls.length > 0) allowed.push("redirect_uri");
530
+ else return invalidRequestPage();
531
+ if (names.length !== allowed.length || !names.every((name) => allowed.includes(name))) {
532
+ return invalidRequestPage();
533
+ }
534
+ const state = params.get("state") ?? "";
535
+ const codeChallenge = params.get("code_challenge") ?? "";
536
+ if (!STATE_PATTERN.test(state)) return invalidRequestPage();
537
+ if (!CODE_CHALLENGE_PATTERN.test(codeChallenge)) return invalidRequestPage();
538
+ if (params.get("code_challenge_method") !== "S256") return invalidRequestPage();
539
+ let target;
540
+ if (mode === "loopback") {
541
+ const rawPort = params.get("port") ?? "";
542
+ const port = Number(rawPort);
543
+ if (!/^[0-9]{4,5}$/.test(rawPort) || String(port) !== rawPort || port < 1024 || port > 65535) {
544
+ return invalidRequestPage();
545
+ }
546
+ target = { mode: "loopback", port };
547
+ } else {
548
+ const redirectUri = params.get("redirect_uri") ?? "";
549
+ if (!returnUrls.includes(redirectUri)) return invalidRequestPage();
550
+ target = { mode: "redirect", redirectUri };
551
+ }
552
+ return beginLogin({ target, state, codeChallenge });
553
+ }
554
+ function redirectToTarget(base, query) {
555
+ const target = new URL(base);
556
+ for (const [name, value] of Object.entries(query)) target.searchParams.append(name, value);
557
+ return redirectClearingCookie(target.toString());
558
+ }
559
+ async function complete(request, url) {
560
+ const id = url.searchParams.get("h") ?? "";
561
+ const handoff = readHandoff(await store.consume(`h:${id}`));
562
+ if (handoff === null) return expiredPage();
563
+ const sessionToken = readCookie2(request, cookieName);
564
+ const hasSession = sessionToken !== null && sessionToken !== "";
565
+ const { target } = handoff;
566
+ if (target.mode === "pairing") {
567
+ const key = `p:${target.pairingId}`;
568
+ const pairing2 = readPairing(await store.get(key));
569
+ const remaining = pairing2 === null ? 0 : pairing2.expiresAt - Date.now();
570
+ if (pairing2 === null || remaining <= 0) return expiredPage();
571
+ const updated = hasSession ? { ...pairing2, status: "ready", sessionToken } : { ...pairing2, status: "denied" };
572
+ await store.set(key, JSON.stringify(updated), remaining);
573
+ const headers = new Headers();
574
+ headers.append("Set-Cookie", clearSessionCookie);
575
+ return hasSession ? htmlPage(
576
+ 200,
577
+ "Signed in",
578
+ "<p>Signed in. You can go back to your other device.</p>",
579
+ headers
580
+ ) : htmlPage(
581
+ 200,
582
+ "Sign-in cancelled",
583
+ "<p>Sign-in cancelled. You can close this page.</p>",
584
+ headers
585
+ );
586
+ }
587
+ const base = target.mode === "loopback" ? `http://127.0.0.1:${target.port}/callback` : target.redirectUri;
588
+ const state = handoff.state ?? "";
589
+ if (!hasSession) return redirectToTarget(base, { error: "access_denied", state });
590
+ const code = randomId();
591
+ const record = { sessionToken, codeChallenge: handoff.codeChallenge };
592
+ await store.set(`c:${code}`, JSON.stringify(record), CODE_TTL_MS);
593
+ return redirectToTarget(base, { code, state });
594
+ }
595
+ async function pairing(request) {
596
+ const body = await readJsonObject(request);
597
+ if (body === null || !hasExactKeys(body, ["code_challenge", "code_challenge_method"]) || typeof body.code_challenge !== "string" || !CODE_CHALLENGE_PATTERN.test(body.code_challenge) || body.code_challenge_method !== "S256") {
598
+ return tokenError("invalid_request");
599
+ }
600
+ let userCode = randomUserCode();
601
+ while (await store.get(`u:${userCode}`) !== null) userCode = randomUserCode();
602
+ const pairingId = randomId();
603
+ const record = {
604
+ status: "pending",
605
+ codeChallenge: body.code_challenge,
606
+ userCode,
607
+ expiresAt: Date.now() + PAIRING_TTL_MS
608
+ };
609
+ await store.set(`p:${pairingId}`, JSON.stringify(record), PAIRING_TTL_MS);
610
+ await store.set(`u:${userCode}`, pairingId, PAIRING_TTL_MS);
611
+ return jsonResponse(200, {
612
+ pairing_id: pairingId,
613
+ user_code: userCode,
614
+ verification_uri: `${appOrigin}${basePath}/pair`,
615
+ expires_in: PAIRING_TTL_MS / 1e3,
616
+ interval: PAIRING_INTERVAL_SECONDS
617
+ });
618
+ }
619
+ function csrfCookieHeaders(csrf) {
620
+ const headers = new Headers();
621
+ headers.append(
622
+ "Set-Cookie",
623
+ `${CSRF_COOKIE_NAME}=${csrf}; HttpOnly; Secure; SameSite=Strict; Path=${basePath}`
624
+ );
625
+ return headers;
626
+ }
627
+ function entryFormPage(csrf, message) {
628
+ const notice = message === void 0 ? "" : `<p role="alert">${escapeHtml(message)}</p>`;
629
+ return htmlPage(
630
+ 200,
631
+ `Sign in to ${appName}`,
632
+ `<h1>Sign in to ${escapeHtml(appName)}</h1>${notice}<form method="post" action="${escapeHtml(basePath)}/pair"><input type="hidden" name="csrf" value="${escapeHtml(csrf)}"><label>Code shown on your other device<br><input name="user_code" autocomplete="off" autocapitalize="characters" required></label><br><button type="submit">Next</button></form>`,
633
+ csrfCookieHeaders(csrf)
634
+ );
635
+ }
636
+ function confirmationPage(csrf, userCode) {
637
+ const shown = escapeHtml(formatUserCode(userCode));
638
+ return htmlPage(
639
+ 200,
640
+ `Sign in to ${appName}`,
641
+ `<h1>Sign in to ${escapeHtml(appName)} on another device?</h1><p class="code">${shown}</p><p>Sign in to ${escapeHtml(appName)} on another device? Only continue if this code is on a screen in front of you right now. If someone sent you this code, do not continue \u2014 they are trying to use your account.</p><form method="post" action="${escapeHtml(basePath)}/pair"><input type="hidden" name="csrf" value="${escapeHtml(csrf)}"><input type="hidden" name="user_code" value="${escapeHtml(userCode)}"><button type="submit" name="action" value="confirm">Continue</button> <button type="submit" name="action" value="cancel">Cancel</button></form>`,
642
+ csrfCookieHeaders(csrf)
643
+ );
644
+ }
645
+ async function pendingPairingFor(userCode) {
646
+ if (userCode.length !== USER_CODE_LENGTH) return null;
647
+ const id = await store.get(`u:${userCode}`);
648
+ if (id === null) return null;
649
+ const record = readPairing(await store.get(`p:${id}`));
650
+ if (record?.status !== "pending" || record.expiresAt <= Date.now()) return null;
651
+ return { id, record };
652
+ }
653
+ async function pair(request) {
654
+ if (request.method === "GET") return entryFormPage(randomId());
655
+ const origin = request.headers.get("origin");
656
+ if (origin !== null && origin !== appOrigin) return forbidden();
657
+ const cookieCsrf = readCookie2(request, CSRF_COOKIE_NAME);
658
+ const form = new URLSearchParams(await request.text());
659
+ const csrf = form.get("csrf");
660
+ if (cookieCsrf === null || csrf === null || cookieCsrf === "" || !safeEqual(cookieCsrf, csrf)) {
661
+ return forbidden();
662
+ }
663
+ const userCode = normalizeUserCode(form.get("user_code") ?? "");
664
+ const action = form.get("action");
665
+ const found = await pendingPairingFor(userCode);
666
+ if (found === null) return entryFormPage(csrf, "That code is not valid or has expired.");
667
+ if (action === "cancel") {
668
+ const remaining = found.record.expiresAt - Date.now();
669
+ await store.set(
670
+ `p:${found.id}`,
671
+ JSON.stringify({ ...found.record, status: "denied" }),
672
+ remaining
673
+ );
674
+ return htmlPage(
675
+ 200,
676
+ "Sign-in cancelled",
677
+ "<p>Sign-in cancelled. You can close this page.</p>"
678
+ );
679
+ }
680
+ if (action === "confirm") {
681
+ return beginLogin({
682
+ target: { mode: "pairing", pairingId: found.id },
683
+ codeChallenge: found.record.codeChallenge
684
+ });
685
+ }
686
+ return confirmationPage(csrf, userCode);
687
+ }
688
+ function forbidden() {
689
+ return htmlPage(
690
+ 403,
691
+ "Forbidden",
692
+ "<p>This request could not be verified. Go back and try again.</p>"
693
+ );
694
+ }
695
+ async function token(request) {
696
+ const body = await readJsonObject(request);
697
+ if (body === null) return tokenError("invalid_request");
698
+ const verifier = body.code_verifier;
699
+ if (body.grant_type === "code") {
700
+ if (!hasExactKeys(body, ["grant_type", "code", "code_verifier"]))
701
+ return tokenError("invalid_request");
702
+ if (typeof body.code !== "string" || typeof verifier !== "string")
703
+ return tokenError("invalid_request");
704
+ return redeemCode(body.code, verifier);
705
+ }
706
+ if (body.grant_type === "pairing") {
707
+ if (!hasExactKeys(body, ["grant_type", "pairing_id", "code_verifier"]))
708
+ return tokenError("invalid_request");
709
+ if (typeof body.pairing_id !== "string" || typeof verifier !== "string")
710
+ return tokenError("invalid_request");
711
+ return redeemPairing(body.pairing_id, verifier);
712
+ }
713
+ return tokenError("invalid_request");
714
+ }
715
+ function verifierMatches(verifier, challenge) {
716
+ return CODE_VERIFIER_PATTERN.test(verifier) && safeEqual(challengeOf(verifier), challenge);
717
+ }
718
+ async function redeemCode(code, verifier) {
719
+ if (!RANDOM_ID_PATTERN.test(code)) return tokenError("invalid_grant");
720
+ const record = readCode(await store.consume(`c:${code}`));
721
+ if (record === null || !verifierMatches(verifier, record.codeChallenge))
722
+ return tokenError("invalid_grant");
723
+ return jsonResponse(200, { session_token: record.sessionToken });
724
+ }
725
+ async function redeemPairing(pairingId, verifier) {
726
+ if (!RANDOM_ID_PATTERN.test(pairingId)) return tokenError("invalid_grant");
727
+ const key = `p:${pairingId}`;
728
+ const current = readPairing(await store.get(key));
729
+ if (current === null) return tokenError("invalid_grant");
730
+ if (current.status === "pending" && current.expiresAt > Date.now())
731
+ return tokenError("authorization_pending");
732
+ const record = readPairing(await store.consume(key));
733
+ if (record === null) return tokenError("invalid_grant");
734
+ await store.consume(`u:${record.userCode}`);
735
+ if (record.expiresAt <= Date.now() && record.status === "pending")
736
+ return tokenError("expired_token");
737
+ if (record.status === "denied") return tokenError("access_denied");
738
+ if (record.status !== "ready" || record.sessionToken === void 0)
739
+ return tokenError("invalid_grant");
740
+ if (!verifierMatches(verifier, record.codeChallenge)) return tokenError("invalid_grant");
741
+ return jsonResponse(200, { session_token: record.sessionToken });
742
+ }
743
+ async function logout(request) {
744
+ const sessionToken = request.headers.get(ENLITT_SESSION_HEADER_NAME);
745
+ if (sessionToken !== null && sessionToken !== "" && sessionToken.length <= MAX_LOGOUT_TOKEN_LENGTH) {
746
+ try {
747
+ await logoutHandler(
748
+ new Request(`${appOrigin}${basePath}/logout`, {
749
+ method: "POST",
750
+ headers: { cookie: `${cookieName}=${encodeURIComponent(sessionToken)}` }
751
+ })
752
+ );
753
+ } catch {
754
+ }
755
+ }
756
+ return new Response(null, { status: 204, headers: { "Cache-Control": "no-store" } });
757
+ }
758
+ function methodNotAllowed(allow) {
759
+ return new Response(null, {
760
+ status: 405,
761
+ headers: { Allow: allow, "Cache-Control": "no-store" }
762
+ });
763
+ }
764
+ function notFound() {
765
+ return new Response("Not found", { status: 404, headers: { "Cache-Control": "no-store" } });
766
+ }
767
+ return async function handleClientSignIn(request) {
768
+ const url = new URL(request.url);
769
+ if (!url.pathname.startsWith(`${basePath}/`)) return notFound();
770
+ const route = url.pathname.slice(basePath.length);
771
+ const method = request.method.toUpperCase();
772
+ switch (route) {
773
+ case "/start":
774
+ return method === "GET" ? start(url) : methodNotAllowed("GET");
775
+ case "/complete":
776
+ return method === "GET" ? complete(request, url) : methodNotAllowed("GET");
777
+ case "/token":
778
+ return method === "POST" ? token(request) : methodNotAllowed("POST");
779
+ case "/logout":
780
+ return method === "POST" ? logout(request) : methodNotAllowed("POST");
781
+ case "/pairing":
782
+ if (!pairingEnabled) return notFound();
783
+ return method === "POST" ? pairing(request) : methodNotAllowed("POST");
784
+ case "/pair":
785
+ if (!pairingEnabled) return notFound();
786
+ return method === "GET" || method === "POST" ? pair(request) : methodNotAllowed("GET, POST");
787
+ default:
788
+ return notFound();
789
+ }
790
+ };
791
+ }
272
792
 
273
- export { createCallbackHandler, createLoginStartHandler, createLogoutHandler };
793
+ export { createCallbackHandler, createClientSignInHandler, createLoginStartHandler, createLogoutHandler, createMemoryClientSignInStore };
274
794
  //# sourceMappingURL=server.js.map
275
795
  //# sourceMappingURL=server.js.map