@canopy-io/nextjs 0.0.0 → 0.2.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/dist/index.js CHANGED
@@ -1,11 +1,12 @@
1
1
  // src/proxy.ts
2
- import { NextResponse } from "next/server";
2
+ import { NextResponse as NextResponse2 } from "next/server";
3
3
 
4
4
  // src/config.ts
5
5
  var DEFAULT_ROUTES = {
6
6
  signIn: "/auth/sign-in",
7
7
  callback: "/auth/callback",
8
- signOut: "/auth/sign-out"
8
+ signOut: "/auth/sign-out",
9
+ direct: "/auth/direct"
9
10
  };
10
11
  var DEFAULT_SCOPES = ["openid", "profile", "email"];
11
12
  var DEFAULT_SESSION_MAX_AGE_SEC = 180 * 24 * 60 * 60;
@@ -27,38 +28,112 @@ function resolveConfig(options = {}) {
27
28
  `CANOPY_SECRET must be at least ${MIN_SECRET_LENGTH} characters; generate one with \`openssl rand -base64 32\`.`
28
29
  );
29
30
  }
30
- const apiKey = options.apiKey ?? env["CANOPY_API_KEY"];
31
+ const configuredEnvironmentId = optional(
32
+ options.environmentId ?? env["CANOPY_ENVIRONMENT_ID"]
33
+ );
34
+ if (configuredEnvironmentId !== void 0 && !ENVIRONMENT_ID.test(configuredEnvironmentId)) {
35
+ throw new CanopyConfigError(
36
+ `CANOPY_ENVIRONMENT_ID must be the Environment's id, a UUID; ${configuredEnvironmentId} is not one.`
37
+ );
38
+ }
31
39
  return {
32
40
  issuer,
33
- clientId: required(
34
- options.clientId ?? env["CANOPY_CLIENT_ID"],
35
- "CANOPY_CLIENT_ID"
36
- ),
37
- clientSecret: required(
38
- options.clientSecret ?? env["CANOPY_CLIENT_SECRET"],
39
- "CANOPY_CLIENT_SECRET"
41
+ // Canopy writes the id in lowercase, and a token's audience is compared
42
+ // exactly.
43
+ environmentId: configuredEnvironmentId?.toLowerCase(),
44
+ clientId: optional(options.clientId ?? env["CANOPY_CLIENT_ID"]),
45
+ clientSecret: optional(options.clientSecret ?? env["CANOPY_CLIENT_SECRET"]),
46
+ publishableKey: optional(
47
+ options.publishableKey ?? env["CANOPY_PUBLISHABLE_KEY"]
40
48
  ),
41
49
  secret,
42
50
  appUrl: new URL(
43
51
  required(options.appUrl ?? env["CANOPY_APP_URL"], "CANOPY_APP_URL")
44
52
  ).origin,
45
- apiKey: apiKey === "" ? void 0 : apiKey,
53
+ apiKey: optional(options.apiKey ?? env["CANOPY_API_KEY"]),
46
54
  scopes: options.scopes ?? DEFAULT_SCOPES,
47
55
  routes: { ...DEFAULT_ROUTES, ...options.routes },
48
56
  afterSignOutPath: options.afterSignOutPath ?? "/",
49
57
  sessionMaxAgeSec: options.sessionMaxAgeSec ?? DEFAULT_SESSION_MAX_AGE_SEC
50
58
  };
51
59
  }
52
- function required(value, name) {
60
+ function oidcClient(config) {
61
+ const need = "Hosted Login sign-in, its refresh and its sign-out need it.";
62
+ return {
63
+ clientId: required(config.clientId, "CANOPY_CLIENT_ID", need),
64
+ clientSecret: required(config.clientSecret, "CANOPY_CLIENT_SECRET", need)
65
+ };
66
+ }
67
+ function directKeys(config) {
68
+ const need = "The embedded sign-in form's route, and a Direct API session's refresh and sign-out, need it.";
69
+ const publishableKey = required(
70
+ config.publishableKey,
71
+ "CANOPY_PUBLISHABLE_KEY",
72
+ need
73
+ );
74
+ if (!publishableKey.startsWith(PUBLISHABLE_KEY_PREFIX)) {
75
+ throw new CanopyConfigError(
76
+ `CANOPY_PUBLISHABLE_KEY must be the Environment's publishable key (${PUBLISHABLE_KEY_PREFIX}\u2026), which the browser may see.`
77
+ );
78
+ }
79
+ return {
80
+ publishableKey,
81
+ apiKey: required(config.apiKey, "CANOPY_API_KEY", need)
82
+ };
83
+ }
84
+ function canopyOrigin(config) {
85
+ return new URL(config.issuer).origin;
86
+ }
87
+ function environmentId(config) {
88
+ const fromIssuer = environmentIdOfIssuer(config.issuer);
89
+ if (config.environmentId === void 0) {
90
+ if (fromIssuer === void 0) {
91
+ throw new CanopyConfigError(
92
+ `A Direct API session needs the Environment's id, which its access token names as its audience; ${config.issuer} names none. Set CANOPY_ENVIRONMENT_ID to it when CANOPY_ISSUER is a custom auth domain, or set CANOPY_ISSUER to https://<host>/environments/<environment_id>.`
93
+ );
94
+ }
95
+ return fromIssuer;
96
+ }
97
+ if (fromIssuer !== void 0 && fromIssuer.toLowerCase() !== config.environmentId.toLowerCase()) {
98
+ throw new CanopyConfigError(
99
+ `CANOPY_ENVIRONMENT_ID (${config.environmentId}) and CANOPY_ISSUER (${config.issuer}) name different Environments.`
100
+ );
101
+ }
102
+ return config.environmentId;
103
+ }
104
+ function environmentIdOfIssuer(issuer) {
105
+ const { pathname } = new URL(issuer);
106
+ const [first, id, ...rest] = pathname.split("/").slice(1);
107
+ if (first !== "environments" || !id || rest.length > 0 || !ENVIRONMENT_ID.test(id)) {
108
+ return void 0;
109
+ }
110
+ return id;
111
+ }
112
+ var PUBLISHABLE_KEY_PREFIX = "pk_";
113
+ var ENVIRONMENT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
114
+ function optional(value) {
115
+ const trimmed = value?.trim();
116
+ return trimmed === void 0 || trimmed === "" ? void 0 : trimmed;
117
+ }
118
+ function required(value, name, need) {
53
119
  if (value === void 0 || value.trim() === "") {
54
- throw new CanopyConfigError(`${name} is not set.`);
120
+ throw new CanopyConfigError(
121
+ need ? `${name} is not set. ${need}` : `${name} is not set.`
122
+ );
55
123
  }
56
124
  return value.trim();
57
125
  }
58
126
  function withoutTrailingSlash(value) {
59
- return value.replace(/\/+$/, "");
127
+ let end = value.length;
128
+ while (end > 0 && value[end - 1] === "/") {
129
+ end -= 1;
130
+ }
131
+ return value.slice(0, end);
60
132
  }
61
133
 
134
+ // src/direct.ts
135
+ import { NextResponse } from "next/server";
136
+
62
137
  // src/seal.ts
63
138
  var VERSION = "v1";
64
139
  var IV_BYTES = 12;
@@ -218,6 +293,7 @@ function refreshSession(config, session) {
218
293
  return pending;
219
294
  }
220
295
  async function revoke(config, refreshToken) {
296
+ const { clientId, clientSecret } = oidcClient(config);
221
297
  try {
222
298
  const { revocation_endpoint } = await discover(config);
223
299
  if (!revocation_endpoint) {
@@ -229,8 +305,8 @@ async function revoke(config, refreshToken) {
229
305
  body: new URLSearchParams({
230
306
  token: refreshToken,
231
307
  token_type_hint: "refresh_token",
232
- client_id: config.clientId,
233
- client_secret: config.clientSecret
308
+ client_id: clientId,
309
+ client_secret: clientSecret
234
310
  })
235
311
  });
236
312
  } catch {
@@ -251,6 +327,7 @@ function decodeClaims(token) {
251
327
  }
252
328
  }
253
329
  async function tokenRequest(config, params) {
330
+ const { clientId, clientSecret } = oidcClient(config);
254
331
  const { token_endpoint } = await discover(config);
255
332
  const response = await request(token_endpoint, {
256
333
  method: "POST",
@@ -260,8 +337,8 @@ async function tokenRequest(config, params) {
260
337
  },
261
338
  body: new URLSearchParams({
262
339
  ...params,
263
- client_id: config.clientId,
264
- client_secret: config.clientSecret
340
+ client_id: clientId,
341
+ client_secret: clientSecret
265
342
  })
266
343
  });
267
344
  const body = await response.json().catch(() => null);
@@ -272,6 +349,7 @@ async function tokenRequest(config, params) {
272
349
  );
273
350
  }
274
351
  return {
352
+ via: "oidc",
275
353
  at: body.access_token,
276
354
  ...body.refresh_token ? { rt: body.refresh_token } : {},
277
355
  ...body.id_token ? { it: body.id_token } : {},
@@ -299,6 +377,7 @@ async function request(url, init) {
299
377
  // src/session.ts
300
378
  var SESSION_COOKIE = "canopy_session";
301
379
  var TRANSACTION_COOKIE = "canopy_tx";
380
+ var DEVICE_COOKIE = "canopy_device";
302
381
  var CHUNK_SIZE = 3800;
303
382
  var TRANSACTION_MAX_AGE_SEC = 10 * 60;
304
383
  async function readSession(cookies2, config) {
@@ -312,7 +391,27 @@ async function readSession(cookies2, config) {
312
391
  chunks.map((chunk) => chunk.value).join(""),
313
392
  config.secret
314
393
  );
315
- return session && typeof session.at === "string" && typeof session.exp === "number" ? session : null;
394
+ return isStoredSession(session) ? session : null;
395
+ }
396
+ function isStoredSession(value) {
397
+ if (typeof value !== "object" || value === null) {
398
+ return false;
399
+ }
400
+ const session = value;
401
+ if (typeof session["at"] !== "string" || typeof session["exp"] !== "number") {
402
+ return false;
403
+ }
404
+ if (session["via"] === "oidc") {
405
+ return true;
406
+ }
407
+ return session["via"] === "direct" && typeof session["rt"] === "string" && isDirectIdentity(session["who"]);
408
+ }
409
+ function isDirectIdentity(value) {
410
+ if (typeof value !== "object" || value === null) {
411
+ return false;
412
+ }
413
+ const identity = value;
414
+ return typeof identity["id"] === "string" && identity["id"] !== "" && typeof identity["email"] === "string" && typeof identity["first_name"] === "string" && typeof identity["last_name"] === "string";
316
415
  }
317
416
  async function sessionWrites(session, existing, config) {
318
417
  const held = existing.getAll().map(({ name }) => chunkIndex(name)).filter((index) => index !== null);
@@ -346,6 +445,17 @@ async function transactionWrite(transaction, config) {
346
445
  async function readTransaction(value, config) {
347
446
  return value ? open(value, config.secret) : null;
348
447
  }
448
+ async function deviceWrite(device, config) {
449
+ return {
450
+ name: DEVICE_COOKIE,
451
+ value: await seal(device, config.secret),
452
+ maxAge: Math.max(0, device.exp - Math.floor(Date.now() / 1e3))
453
+ };
454
+ }
455
+ async function readDevice(value, config) {
456
+ const device = value ? await open(value, config.secret) : null;
457
+ return device && typeof device.token === "string" && typeof device.exp === "number" && device.exp > Math.floor(Date.now() / 1e3) ? device : null;
458
+ }
349
459
  function cookieOptions(config, maxAge) {
350
460
  return {
351
461
  httpOnly: true,
@@ -355,6 +465,15 @@ function cookieOptions(config, maxAge) {
355
465
  maxAge
356
466
  };
357
467
  }
468
+ function applyCookies(response, writes, config) {
469
+ for (const write of writes) {
470
+ response.cookies.set(
471
+ write.name,
472
+ write.value,
473
+ cookieOptions(config, write.maxAge)
474
+ );
475
+ }
476
+ }
358
477
  function chunkIndex(name) {
359
478
  const prefix = `${SESSION_COOKIE}.`;
360
479
  if (!name.startsWith(prefix)) {
@@ -364,13 +483,395 @@ function chunkIndex(name) {
364
483
  return Number.isInteger(index) && index >= 0 ? index : null;
365
484
  }
366
485
 
486
+ // src/direct.ts
487
+ var AUTH_PATH = "/v1/identity/auth";
488
+ var ROUTES = /* @__PURE__ */ new Map([
489
+ [`${AUTH_PATH}/login`, { key: true, device: true }],
490
+ [`${AUTH_PATH}/login/sso-recovery`, { key: true }],
491
+ [`${AUTH_PATH}/login/email-otp/start`, { key: true }],
492
+ [`${AUTH_PATH}/login/email-otp/verify`, { key: true, device: true }],
493
+ [`${AUTH_PATH}/login/passkey/options`, { key: true }],
494
+ [`${AUTH_PATH}/login/passkey/verify`, { key: true, device: true }],
495
+ [`${AUTH_PATH}/login/mfa-enroll/totp/verify`, { key: true }],
496
+ [`${AUTH_PATH}/login/mfa-enroll/webauthn/options`, { key: true }],
497
+ [`${AUTH_PATH}/login/mfa-enroll/webauthn/verify`, { key: true }],
498
+ [`${AUTH_PATH}/register`, { key: true }],
499
+ [`${AUTH_PATH}/mfa/challenge/totp`, { key: false }],
500
+ [`${AUTH_PATH}/mfa/challenge/recovery-code`, { key: false }],
501
+ [`${AUTH_PATH}/mfa/challenge/email-otp/send`, { key: false }],
502
+ [`${AUTH_PATH}/mfa/challenge/email-otp/verify`, { key: false }],
503
+ [`${AUTH_PATH}/mfa/challenge/webauthn/options`, { key: false }],
504
+ [`${AUTH_PATH}/mfa/challenge/webauthn/verify`, { key: false }],
505
+ [`${AUTH_PATH}/verify-email`, { key: false }],
506
+ [`${AUTH_PATH}/verify-email-code`, { key: true }],
507
+ [`${AUTH_PATH}/resend-verification`, { key: true }],
508
+ [`${AUTH_PATH}/forgot-password`, { key: true }],
509
+ [`${AUTH_PATH}/forgot-password-code`, { key: true }],
510
+ [`${AUTH_PATH}/reset-password`, { key: false }],
511
+ [`${AUTH_PATH}/reset-password-code`, { key: true }],
512
+ [`${AUTH_PATH}/sso/resolve`, { key: true }],
513
+ [`${AUTH_PATH}/sso/authenticate`, { key: true, device: true }]
514
+ ]);
515
+ var OWNED_FIELDS = ["publishable_key", "trusted_device_token"];
516
+ var CREDENTIAL_FIELDS = [
517
+ "access_token",
518
+ "refresh_token",
519
+ "trusted_device_token"
520
+ ];
521
+ var SIGNED_IN_FIELDS = [
522
+ "requires_mfa_challenge",
523
+ "mfa_enrollment_pending",
524
+ "grace_expires_at",
525
+ "recovery_codes",
526
+ "device_remembered"
527
+ ];
528
+ var MAX_BODY_BYTES = 64 * 1024;
529
+ var TIMEOUT_MS = 1e4;
530
+ async function direct(request2, config, client) {
531
+ const path = request2.nextUrl.pathname.slice(config.routes.direct.length);
532
+ const route = ROUTES.get(path);
533
+ if (!route || request2.method !== "POST") {
534
+ return refuse(404, "not_found", "There is no such route.");
535
+ }
536
+ const fetchSite = request2.headers.get("sec-fetch-site");
537
+ if (request2.headers.get("origin") !== config.appUrl || fetchSite !== null && fetchSite !== "same-origin") {
538
+ return refuse(
539
+ 403,
540
+ "forbidden_origin",
541
+ "Only this site's own pages may send this."
542
+ );
543
+ }
544
+ if (mediaType(request2.headers.get("content-type")) !== "application/json") {
545
+ return refuse(400, "invalid_request", "Send a JSON body.");
546
+ }
547
+ const sent = await jsonObjectOf(request2);
548
+ if (!sent) {
549
+ return refuse(
550
+ 400,
551
+ "invalid_request",
552
+ "Send one JSON object of at most 64 KB."
553
+ );
554
+ }
555
+ const { publishableKey, apiKey } = directKeys(config);
556
+ environmentId(config);
557
+ const body = { ...sent };
558
+ for (const field of OWNED_FIELDS) {
559
+ delete body[field];
560
+ }
561
+ if (route.key) {
562
+ body["publishable_key"] = publishableKey;
563
+ }
564
+ if (route.device) {
565
+ const device2 = await readDevice(
566
+ request2.cookies.get(DEVICE_COOKIE)?.value,
567
+ config
568
+ );
569
+ if (device2) {
570
+ body["trusted_device_token"] = device2.token;
571
+ }
572
+ }
573
+ const answer = await callCanopy(config, path, body, {
574
+ ...canopyHeaders(apiKey, client),
575
+ ...languageOf(request2)
576
+ });
577
+ if (!answer) {
578
+ return refuse(502, "connection_failed", "Canopy could not be reached.");
579
+ }
580
+ if (answer.status < 200 || answer.status >= 300) {
581
+ return reply(answer.status, refusalOf(answer.body), answer.retryAfter);
582
+ }
583
+ const data = answer.body.data;
584
+ if (!isRecord(data) || !CREDENTIAL_FIELDS.some((field) => Object.hasOwn(data, field))) {
585
+ if (carriesCredential(data)) {
586
+ return refuse(
587
+ 500,
588
+ "session_not_delivered",
589
+ "Canopy answered with a credential this server does not keep."
590
+ );
591
+ }
592
+ return reply(answer.status, data === void 0 ? {} : { data }, null);
593
+ }
594
+ const session = sessionOf(data);
595
+ if (!session) {
596
+ return refuse(
597
+ 500,
598
+ "session_not_delivered",
599
+ "Canopy did not hand the session to this server. CANOPY_API_KEY must be a secret API key of the publishable key's Environment."
600
+ );
601
+ }
602
+ const writes = await sessionWrites(
603
+ session,
604
+ request2.cookies,
605
+ config
606
+ );
607
+ const device = await rememberedDevice(data, config);
608
+ if (device) {
609
+ writes.push(device);
610
+ }
611
+ const response = reply(answer.status, { data: signedInView(data) }, null);
612
+ applyCookies(response, writes, config);
613
+ return response;
614
+ }
615
+ var refreshes2 = /* @__PURE__ */ new Map();
616
+ function refreshDirectSession(config, session, client) {
617
+ let pending = refreshes2.get(session.rt);
618
+ if (!pending) {
619
+ pending = (async () => {
620
+ const { apiKey } = directKeys(config);
621
+ const answer = await callCanopy(
622
+ config,
623
+ `${AUTH_PATH}/refresh`,
624
+ { refresh_token: session.rt },
625
+ canopyHeaders(apiKey, client)
626
+ );
627
+ if (!answer) {
628
+ throw new CanopySessionError(
629
+ "connection_failed",
630
+ "Canopy could not be reached."
631
+ );
632
+ }
633
+ const data = answer.body.data;
634
+ if (answer.status < 200 || answer.status >= 300 || !isRecord(data)) {
635
+ throw new CanopySessionError(
636
+ refusalOf(answer.body).error.code,
637
+ `Canopy's refresh answered ${answer.status}.`
638
+ );
639
+ }
640
+ const at = data["access_token"];
641
+ const rt = data["refresh_token"];
642
+ if (typeof at !== "string" || typeof rt !== "string") {
643
+ throw new CanopySessionError(
644
+ "session_not_delivered",
645
+ "Canopy's refresh carried no refresh token for this server."
646
+ );
647
+ }
648
+ return {
649
+ via: "direct",
650
+ at,
651
+ rt,
652
+ exp: expiryOf({ access_token: at, ...expiresIn(data) }),
653
+ who: session.who
654
+ };
655
+ })();
656
+ refreshes2.set(session.rt, pending);
657
+ pending.then(
658
+ () => refreshes2.delete(session.rt),
659
+ () => refreshes2.delete(session.rt)
660
+ );
661
+ }
662
+ return pending;
663
+ }
664
+ async function endDirectSession(config, session, client) {
665
+ const { apiKey } = directKeys(config);
666
+ await callCanopy(
667
+ config,
668
+ `${AUTH_PATH}/logout`,
669
+ { refresh_token: session.rt },
670
+ canopyHeaders(apiKey, client)
671
+ );
672
+ }
673
+ async function callCanopy(config, path, body, headers) {
674
+ let response;
675
+ try {
676
+ response = await fetch(`${canopyOrigin(config)}${path}`, {
677
+ method: "POST",
678
+ headers,
679
+ body: JSON.stringify(body),
680
+ redirect: "manual",
681
+ signal: AbortSignal.timeout(TIMEOUT_MS),
682
+ cache: "no-store"
683
+ });
684
+ } catch {
685
+ return null;
686
+ }
687
+ if (response.type === "opaqueredirect" || isRedirect(response.status)) {
688
+ return null;
689
+ }
690
+ const text = await response.text().catch(() => null);
691
+ if (text === null) {
692
+ return null;
693
+ }
694
+ let parsed = {};
695
+ if (text !== "") {
696
+ try {
697
+ parsed = JSON.parse(text);
698
+ } catch {
699
+ return null;
700
+ }
701
+ }
702
+ return {
703
+ status: response.status,
704
+ body: isRecord(parsed) ? parsed : {},
705
+ retryAfter: response.headers.get("retry-after")
706
+ };
707
+ }
708
+ function canopyHeaders(apiKey, client) {
709
+ return {
710
+ "Content-Type": "application/json",
711
+ "X-API-Key": apiKey,
712
+ ...client.ip ? { "X-Canopy-Client-IP": client.ip } : {},
713
+ ...client.userAgent ? { "X-Canopy-Client-User-Agent": client.userAgent } : {}
714
+ };
715
+ }
716
+ function languageOf(request2) {
717
+ const language = request2.headers.get("accept-language");
718
+ return language ? { "Accept-Language": language } : {};
719
+ }
720
+ function sessionOf(data) {
721
+ const at = data["access_token"];
722
+ const rt = data["refresh_token"];
723
+ const identity = data["identity"];
724
+ if (typeof at !== "string" || typeof rt !== "string" || !isDirectIdentity(identity)) {
725
+ return null;
726
+ }
727
+ return {
728
+ via: "direct",
729
+ at,
730
+ rt,
731
+ exp: expiryOf({ access_token: at, ...expiresIn(data) }),
732
+ who: identityOf(identity)
733
+ };
734
+ }
735
+ async function rememberedDevice(data, config) {
736
+ const token = data["trusted_device_token"];
737
+ const expiresAt = data["trusted_device_expires_at"];
738
+ if (typeof token !== "string" || typeof expiresAt !== "string") {
739
+ return null;
740
+ }
741
+ const exp = Math.floor(Date.parse(expiresAt) / 1e3);
742
+ if (!Number.isFinite(exp) || exp <= Math.floor(Date.now() / 1e3)) {
743
+ return null;
744
+ }
745
+ return deviceWrite({ token, exp }, config);
746
+ }
747
+ function signedInView(data) {
748
+ const view = {};
749
+ for (const field of SIGNED_IN_FIELDS) {
750
+ if (Object.hasOwn(data, field)) {
751
+ view[field] = data[field];
752
+ }
753
+ }
754
+ view["identity"] = identityOf(data["identity"]);
755
+ return view;
756
+ }
757
+ function identityOf(identity) {
758
+ return {
759
+ id: identity.id,
760
+ email: identity.email,
761
+ first_name: identity.first_name,
762
+ last_name: identity.last_name
763
+ };
764
+ }
765
+ function expiresIn(data) {
766
+ const value = data["expires_in"];
767
+ return typeof value === "number" ? { expires_in: value } : {};
768
+ }
769
+ function refusalOf(body) {
770
+ const error = isRecord(body) ? body["error"] : void 0;
771
+ const code = isRecord(error) ? error["code"] : void 0;
772
+ const message = isRecord(error) ? error["message"] : void 0;
773
+ return {
774
+ error: {
775
+ code: typeof code === "string" ? code : "server_error",
776
+ message: typeof message === "string" ? message : "Canopy refused."
777
+ }
778
+ };
779
+ }
780
+ function refuse(status, code, message) {
781
+ return reply(status, { error: { code, message } }, null);
782
+ }
783
+ function reply(status, body, retryAfter) {
784
+ return NextResponse.json(body, {
785
+ status,
786
+ headers: {
787
+ "Cache-Control": "no-store",
788
+ ...retryAfter && /^\d{1,6}$/.test(retryAfter) ? { "Retry-After": retryAfter } : {}
789
+ }
790
+ });
791
+ }
792
+ async function jsonObjectOf(request2) {
793
+ const declared = Number(request2.headers.get("content-length"));
794
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
795
+ return null;
796
+ }
797
+ if (!request2.body) {
798
+ return null;
799
+ }
800
+ const reader = request2.body.getReader();
801
+ const chunks = [];
802
+ let size = 0;
803
+ for (; ; ) {
804
+ const { done, value } = await reader.read();
805
+ if (done) {
806
+ break;
807
+ }
808
+ size += value.byteLength;
809
+ if (size > MAX_BODY_BYTES) {
810
+ await reader.cancel();
811
+ return null;
812
+ }
813
+ chunks.push(value);
814
+ }
815
+ const bytes = new Uint8Array(size);
816
+ let offset = 0;
817
+ for (const chunk of chunks) {
818
+ bytes.set(chunk, offset);
819
+ offset += chunk.byteLength;
820
+ }
821
+ try {
822
+ const parsed = JSON.parse(
823
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes)
824
+ );
825
+ return isRecord(parsed) ? parsed : null;
826
+ } catch {
827
+ return null;
828
+ }
829
+ }
830
+ function carriesCredential(value) {
831
+ if (Array.isArray(value)) {
832
+ return value.some(carriesCredential);
833
+ }
834
+ if (!isRecord(value)) {
835
+ return false;
836
+ }
837
+ return Object.entries(value).some(
838
+ ([field, inner]) => CREDENTIAL_FIELDS.includes(field) || carriesCredential(inner)
839
+ );
840
+ }
841
+ function mediaType(value) {
842
+ return value?.split(";")[0]?.trim().toLowerCase() ?? null;
843
+ }
844
+ function isRecord(value) {
845
+ return typeof value === "object" && value !== null && !Array.isArray(value);
846
+ }
847
+ function isRedirect(status) {
848
+ return status >= 300 && status < 400;
849
+ }
850
+
851
+ // src/return-to.ts
852
+ function safeReturnTo(value) {
853
+ if (!value || !value.startsWith("/") || value.startsWith("//") || value.startsWith("/\\")) {
854
+ return "/";
855
+ }
856
+ return value;
857
+ }
858
+
367
859
  // src/proxy.ts
368
860
  var REFRESH_LEEWAY_SEC = 60;
369
861
  function canopyProxy(options = {}) {
862
+ if (options.signInPage !== void 0 && safeReturnTo(options.signInPage) !== options.signInPage) {
863
+ throw new CanopyConfigError(
864
+ `signInPage must be a path on this site, such as "/sign-in"; "${options.signInPage}" is not one.`
865
+ );
866
+ }
370
867
  let config;
371
868
  return async (request2) => {
372
869
  config ??= resolveConfig(options);
373
870
  const { pathname } = request2.nextUrl;
871
+ const client = clientOf(request2, options.clientAddress);
872
+ if (pathname === config.routes.direct || pathname.startsWith(`${config.routes.direct}/`)) {
873
+ return direct(request2, config, client);
874
+ }
374
875
  if (pathname === config.routes.signIn) {
375
876
  return signIn(request2, config);
376
877
  }
@@ -378,9 +879,16 @@ function canopyProxy(options = {}) {
378
879
  return callback(request2, config);
379
880
  }
380
881
  if (pathname === config.routes.signOut) {
381
- return signOut(request2, config);
882
+ return signOut(request2, config, client);
382
883
  }
383
- return pass(request2, config, isProtected(pathname, options.protect));
884
+ return pass(
885
+ request2,
886
+ config,
887
+ client,
888
+ // The sign-in page itself stays open even inside a protected path,
889
+ // or a signed-out visitor would be sent to it without end.
890
+ isProtected(pathname, options.protect) && pathname !== options.signInPage ? options.signInPage ?? config.routes.signIn : null
891
+ );
384
892
  };
385
893
  }
386
894
  async function signIn(request2, config) {
@@ -395,7 +903,7 @@ async function signIn(request2, config) {
395
903
  const authorize = new URL(authorization_endpoint);
396
904
  authorize.search = new URLSearchParams({
397
905
  response_type: "code",
398
- client_id: config.clientId,
906
+ client_id: oidcClient(config).clientId,
399
907
  redirect_uri: callbackUrl(config),
400
908
  scope: config.scopes.join(" "),
401
909
  state: transaction.state,
@@ -403,8 +911,8 @@ async function signIn(request2, config) {
403
911
  code_challenge: await codeChallenge(transaction.verifier),
404
912
  code_challenge_method: "S256"
405
913
  }).toString();
406
- const response = NextResponse.redirect(authorize);
407
- apply(response, [await transactionWrite(transaction, config)], config);
914
+ const response = NextResponse2.redirect(authorize);
915
+ applyCookies(response, [await transactionWrite(transaction, config)], config);
408
916
  return response;
409
917
  }
410
918
  async function callback(request2, config) {
@@ -419,20 +927,20 @@ async function callback(request2, config) {
419
927
  maxAge: 0
420
928
  };
421
929
  if (!transaction || params.get("state") !== transaction.state) {
422
- const response2 = new NextResponse(
930
+ const response2 = new NextResponse2(
423
931
  "This sign-in has expired. Start it again.",
424
932
  {
425
933
  status: 400
426
934
  }
427
935
  );
428
- apply(response2, [cleared], config);
936
+ applyCookies(response2, [cleared], config);
429
937
  return response2;
430
938
  }
431
939
  const back = new URL(transaction.returnTo, config.appUrl);
432
940
  const code = params.get("code");
433
941
  if (!code) {
434
- const response2 = NextResponse.redirect(back);
435
- apply(response2, [cleared], config);
942
+ const response2 = NextResponse2.redirect(back);
943
+ applyCookies(response2, [cleared], config);
436
944
  return response2;
437
945
  }
438
946
  const session = await exchangeCode(config, code, transaction.verifier);
@@ -443,17 +951,26 @@ async function callback(request2, config) {
443
951
  "The ID token's nonce does not match this sign-in."
444
952
  );
445
953
  }
446
- const response = NextResponse.redirect(back);
447
- apply(
954
+ const response = NextResponse2.redirect(back);
955
+ applyCookies(
448
956
  response,
449
957
  [cleared, ...await sessionWrites(session, request2.cookies, config)],
450
958
  config
451
959
  );
452
960
  return response;
453
961
  }
454
- async function signOut(request2, config) {
962
+ async function signOut(request2, config, client) {
455
963
  const session = await readSession(request2.cookies, config);
456
964
  const landing = `${config.appUrl}${config.afterSignOutPath}`;
965
+ if (session?.via === "direct" || !session && config.clientId === void 0) {
966
+ if (session?.via === "direct") {
967
+ await endDirectSession(config, session, client);
968
+ }
969
+ const response2 = NextResponse2.redirect(landing);
970
+ applyCookies(response2, await sessionWrites(null, request2.cookies, config), config);
971
+ return response2;
972
+ }
973
+ const { clientId } = oidcClient(config);
457
974
  let destination = landing;
458
975
  if (session?.rt) {
459
976
  await revoke(config, session.rt);
@@ -464,36 +981,36 @@ async function signOut(request2, config) {
464
981
  if (end_session_endpoint) {
465
982
  const end = new URL(end_session_endpoint);
466
983
  end.search = new URLSearchParams({
467
- client_id: config.clientId,
984
+ client_id: clientId,
468
985
  post_logout_redirect_uri: landing,
469
986
  ...session?.it ? { id_token_hint: session.it } : {}
470
987
  }).toString();
471
988
  destination = end.toString();
472
989
  }
473
- const response = NextResponse.redirect(destination);
474
- apply(response, await sessionWrites(null, request2.cookies, config), config);
990
+ const response = NextResponse2.redirect(destination);
991
+ applyCookies(response, await sessionWrites(null, request2.cookies, config), config);
475
992
  return response;
476
993
  }
477
- async function pass(request2, config, protectedPath) {
994
+ async function pass(request2, config, client, signInPath) {
478
995
  let session = await readSession(request2.cookies, config);
479
996
  let writes = [];
480
997
  if (session && session.exp - nowSec() <= REFRESH_LEEWAY_SEC) {
481
- const refreshed = await tryRefresh(config, session);
998
+ const refreshed = await tryRefresh(config, session, client);
482
999
  session = refreshed;
483
1000
  writes = await sessionWrites(refreshed, request2.cookies, config);
484
1001
  }
485
- if (!session && protectedPath) {
486
- const signInUrl = new URL(config.routes.signIn, config.appUrl);
1002
+ if (!session && signInPath !== null) {
1003
+ const signInUrl = new URL(signInPath, config.appUrl);
487
1004
  signInUrl.searchParams.set(
488
1005
  "returnTo",
489
1006
  `${request2.nextUrl.pathname}${request2.nextUrl.search}`
490
1007
  );
491
- const response2 = NextResponse.redirect(signInUrl);
492
- apply(response2, writes, config);
1008
+ const response2 = NextResponse2.redirect(signInUrl);
1009
+ applyCookies(response2, writes, config);
493
1010
  return response2;
494
1011
  }
495
1012
  if (writes.length === 0) {
496
- return NextResponse.next();
1013
+ return NextResponse2.next();
497
1014
  }
498
1015
  for (const write of writes) {
499
1016
  if (write.maxAge === 0) {
@@ -502,28 +1019,32 @@ async function pass(request2, config, protectedPath) {
502
1019
  request2.cookies.set(write.name, write.value);
503
1020
  }
504
1021
  }
505
- const response = NextResponse.next({ request: { headers: request2.headers } });
506
- apply(response, writes, config);
1022
+ const response = NextResponse2.next({ request: { headers: request2.headers } });
1023
+ applyCookies(response, writes, config);
507
1024
  return response;
508
1025
  }
509
- async function tryRefresh(config, session) {
1026
+ async function tryRefresh(config, session, client) {
510
1027
  try {
511
- return await refreshSession(config, session);
1028
+ return session.via === "direct" ? await refreshDirectSession(config, session, client) : await refreshSession(config, session);
512
1029
  } catch (caught) {
1030
+ if (caught instanceof CanopyConfigError) {
1031
+ throw caught;
1032
+ }
513
1033
  if (caught instanceof CanopySessionError && caught.code === "connection_failed") {
514
1034
  return session.exp > nowSec() ? session : null;
515
1035
  }
516
1036
  return null;
517
1037
  }
518
1038
  }
519
- function apply(response, writes, config) {
520
- for (const write of writes) {
521
- response.cookies.set(
522
- write.name,
523
- write.value,
524
- cookieOptions(config, write.maxAge)
525
- );
526
- }
1039
+ function clientOf(request2, clientAddress) {
1040
+ const ip = (clientAddress ?? firstForwardedFor)(request2)?.trim();
1041
+ return {
1042
+ ip: ip === "" ? void 0 : ip,
1043
+ userAgent: request2.headers.get("user-agent") ?? void 0
1044
+ };
1045
+ }
1046
+ function firstForwardedFor(request2) {
1047
+ return request2.headers.get("x-forwarded-for")?.split(",")[0];
527
1048
  }
528
1049
  function isProtected(pathname, protect) {
529
1050
  if (!protect) {
@@ -533,16 +1054,10 @@ function isProtected(pathname, protect) {
533
1054
  return protect(pathname);
534
1055
  }
535
1056
  return protect.some((prefix) => {
536
- const base = prefix.replace(/\/+$/, "");
1057
+ const base = withoutTrailingSlash(prefix);
537
1058
  return base === "" || pathname === base || pathname.startsWith(`${base}/`);
538
1059
  });
539
1060
  }
540
- function safeReturnTo(value) {
541
- if (!value || !value.startsWith("/") || value.startsWith("//") || value.startsWith("/\\")) {
542
- return "/";
543
- }
544
- return value;
545
- }
546
1061
  function nowSec() {
547
1062
  return Math.floor(Date.now() / 1e3);
548
1063
  }
@@ -576,17 +1091,20 @@ var auth = cache(
576
1091
  if (!session) {
577
1092
  return SIGNED_OUT;
578
1093
  }
1094
+ const verifier = verifierFor(config, audienceOf(config, session));
579
1095
  let claims;
580
1096
  try {
581
- claims = await verifierFor(config).verify(session.at);
1097
+ claims = await verifier.verify(session.at);
582
1098
  } catch {
583
1099
  return SIGNED_OUT;
584
1100
  }
585
- const idClaims = session.it ? decodeClaims(session.it) : null;
1101
+ if (session.via === "direct" && session.who.id !== claims.sub) {
1102
+ return SIGNED_OUT;
1103
+ }
586
1104
  return {
587
1105
  isSignedIn: true,
588
1106
  userId: claims.sub,
589
- user: idClaims ? userOf(idClaims) : { sub: claims.sub },
1107
+ user: displayedUser(session, claims.sub),
590
1108
  claims,
591
1109
  organization: {
592
1110
  orgId: claims.org_id ?? null,
@@ -621,13 +1139,29 @@ function fromList(list, overflow, permission) {
621
1139
  }
622
1140
  return overflow ? void 0 : false;
623
1141
  }
624
- function verifierFor(config) {
625
- const key = `${config.issuer}\0${config.clientId}`;
1142
+ function audienceOf(config, session) {
1143
+ return session.via === "direct" ? environmentId(config) : oidcClient(config).clientId;
1144
+ }
1145
+ function displayedUser(session, sub) {
1146
+ if (session.via === "direct") {
1147
+ const { who } = session;
1148
+ const name = `${who.first_name} ${who.last_name}`.trim();
1149
+ return {
1150
+ sub,
1151
+ ...who.email ? { email: who.email } : {},
1152
+ ...name ? { name } : {}
1153
+ };
1154
+ }
1155
+ const idClaims = session.it ? decodeClaims(session.it) : null;
1156
+ return idClaims ? userOf(idClaims) : { sub };
1157
+ }
1158
+ function verifierFor(config, audience) {
1159
+ const key = `${config.issuer}\0${audience}`;
626
1160
  let verifier = shared.verifiers.get(key);
627
1161
  if (!verifier) {
628
1162
  verifier = new TokenVerifier({
629
1163
  issuer: config.issuer,
630
- audience: config.clientId
1164
+ audience
631
1165
  });
632
1166
  shared.verifiers.set(key, verifier);
633
1167
  }
@@ -687,12 +1221,24 @@ function clientSession(auth2) {
687
1221
  organization: { ...auth2.organization }
688
1222
  };
689
1223
  }
1224
+
1225
+ // src/sign-in-form-props.ts
1226
+ function signInFormProps(options) {
1227
+ const config = resolveConfig(options);
1228
+ environmentId(config);
1229
+ return {
1230
+ publishableKey: directKeys(config).publishableKey,
1231
+ canopyOrigin: canopyOrigin(config),
1232
+ directPath: config.routes.direct
1233
+ };
1234
+ }
690
1235
  export {
691
1236
  CanopyConfigError,
692
1237
  CanopySessionError,
693
1238
  DEFAULT_ROUTES,
694
1239
  auth,
695
1240
  canopyProxy,
696
- clientSession
1241
+ clientSession,
1242
+ signInFormProps
697
1243
  };
698
1244
  //# sourceMappingURL=index.js.map