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