@canopy-io/nextjs 0.1.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,31 +28,98 @@ 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
  }
@@ -63,6 +131,9 @@ function withoutTrailingSlash(value) {
63
131
  return value.slice(0, end);
64
132
  }
65
133
 
134
+ // src/direct.ts
135
+ import { NextResponse } from "next/server";
136
+
66
137
  // src/seal.ts
67
138
  var VERSION = "v1";
68
139
  var IV_BYTES = 12;
@@ -222,6 +293,7 @@ function refreshSession(config, session) {
222
293
  return pending;
223
294
  }
224
295
  async function revoke(config, refreshToken) {
296
+ const { clientId, clientSecret } = oidcClient(config);
225
297
  try {
226
298
  const { revocation_endpoint } = await discover(config);
227
299
  if (!revocation_endpoint) {
@@ -233,8 +305,8 @@ async function revoke(config, refreshToken) {
233
305
  body: new URLSearchParams({
234
306
  token: refreshToken,
235
307
  token_type_hint: "refresh_token",
236
- client_id: config.clientId,
237
- client_secret: config.clientSecret
308
+ client_id: clientId,
309
+ client_secret: clientSecret
238
310
  })
239
311
  });
240
312
  } catch {
@@ -255,6 +327,7 @@ function decodeClaims(token) {
255
327
  }
256
328
  }
257
329
  async function tokenRequest(config, params) {
330
+ const { clientId, clientSecret } = oidcClient(config);
258
331
  const { token_endpoint } = await discover(config);
259
332
  const response = await request(token_endpoint, {
260
333
  method: "POST",
@@ -264,8 +337,8 @@ async function tokenRequest(config, params) {
264
337
  },
265
338
  body: new URLSearchParams({
266
339
  ...params,
267
- client_id: config.clientId,
268
- client_secret: config.clientSecret
340
+ client_id: clientId,
341
+ client_secret: clientSecret
269
342
  })
270
343
  });
271
344
  const body = await response.json().catch(() => null);
@@ -276,6 +349,7 @@ async function tokenRequest(config, params) {
276
349
  );
277
350
  }
278
351
  return {
352
+ via: "oidc",
279
353
  at: body.access_token,
280
354
  ...body.refresh_token ? { rt: body.refresh_token } : {},
281
355
  ...body.id_token ? { it: body.id_token } : {},
@@ -303,6 +377,7 @@ async function request(url, init) {
303
377
  // src/session.ts
304
378
  var SESSION_COOKIE = "canopy_session";
305
379
  var TRANSACTION_COOKIE = "canopy_tx";
380
+ var DEVICE_COOKIE = "canopy_device";
306
381
  var CHUNK_SIZE = 3800;
307
382
  var TRANSACTION_MAX_AGE_SEC = 10 * 60;
308
383
  async function readSession(cookies2, config) {
@@ -316,7 +391,27 @@ async function readSession(cookies2, config) {
316
391
  chunks.map((chunk) => chunk.value).join(""),
317
392
  config.secret
318
393
  );
319
- 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";
320
415
  }
321
416
  async function sessionWrites(session, existing, config) {
322
417
  const held = existing.getAll().map(({ name }) => chunkIndex(name)).filter((index) => index !== null);
@@ -350,6 +445,17 @@ async function transactionWrite(transaction, config) {
350
445
  async function readTransaction(value, config) {
351
446
  return value ? open(value, config.secret) : null;
352
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
+ }
353
459
  function cookieOptions(config, maxAge) {
354
460
  return {
355
461
  httpOnly: true,
@@ -359,6 +465,15 @@ function cookieOptions(config, maxAge) {
359
465
  maxAge
360
466
  };
361
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
+ }
362
477
  function chunkIndex(name) {
363
478
  const prefix = `${SESSION_COOKIE}.`;
364
479
  if (!name.startsWith(prefix)) {
@@ -368,13 +483,395 @@ function chunkIndex(name) {
368
483
  return Number.isInteger(index) && index >= 0 ? index : null;
369
484
  }
370
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
+
371
859
  // src/proxy.ts
372
860
  var REFRESH_LEEWAY_SEC = 60;
373
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
+ }
374
867
  let config;
375
868
  return async (request2) => {
376
869
  config ??= resolveConfig(options);
377
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
+ }
378
875
  if (pathname === config.routes.signIn) {
379
876
  return signIn(request2, config);
380
877
  }
@@ -382,9 +879,16 @@ function canopyProxy(options = {}) {
382
879
  return callback(request2, config);
383
880
  }
384
881
  if (pathname === config.routes.signOut) {
385
- return signOut(request2, config);
882
+ return signOut(request2, config, client);
386
883
  }
387
- 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
+ );
388
892
  };
389
893
  }
390
894
  async function signIn(request2, config) {
@@ -399,7 +903,7 @@ async function signIn(request2, config) {
399
903
  const authorize = new URL(authorization_endpoint);
400
904
  authorize.search = new URLSearchParams({
401
905
  response_type: "code",
402
- client_id: config.clientId,
906
+ client_id: oidcClient(config).clientId,
403
907
  redirect_uri: callbackUrl(config),
404
908
  scope: config.scopes.join(" "),
405
909
  state: transaction.state,
@@ -407,8 +911,8 @@ async function signIn(request2, config) {
407
911
  code_challenge: await codeChallenge(transaction.verifier),
408
912
  code_challenge_method: "S256"
409
913
  }).toString();
410
- const response = NextResponse.redirect(authorize);
411
- apply(response, [await transactionWrite(transaction, config)], config);
914
+ const response = NextResponse2.redirect(authorize);
915
+ applyCookies(response, [await transactionWrite(transaction, config)], config);
412
916
  return response;
413
917
  }
414
918
  async function callback(request2, config) {
@@ -423,20 +927,20 @@ async function callback(request2, config) {
423
927
  maxAge: 0
424
928
  };
425
929
  if (!transaction || params.get("state") !== transaction.state) {
426
- const response2 = new NextResponse(
930
+ const response2 = new NextResponse2(
427
931
  "This sign-in has expired. Start it again.",
428
932
  {
429
933
  status: 400
430
934
  }
431
935
  );
432
- apply(response2, [cleared], config);
936
+ applyCookies(response2, [cleared], config);
433
937
  return response2;
434
938
  }
435
939
  const back = new URL(transaction.returnTo, config.appUrl);
436
940
  const code = params.get("code");
437
941
  if (!code) {
438
- const response2 = NextResponse.redirect(back);
439
- apply(response2, [cleared], config);
942
+ const response2 = NextResponse2.redirect(back);
943
+ applyCookies(response2, [cleared], config);
440
944
  return response2;
441
945
  }
442
946
  const session = await exchangeCode(config, code, transaction.verifier);
@@ -447,17 +951,26 @@ async function callback(request2, config) {
447
951
  "The ID token's nonce does not match this sign-in."
448
952
  );
449
953
  }
450
- const response = NextResponse.redirect(back);
451
- apply(
954
+ const response = NextResponse2.redirect(back);
955
+ applyCookies(
452
956
  response,
453
957
  [cleared, ...await sessionWrites(session, request2.cookies, config)],
454
958
  config
455
959
  );
456
960
  return response;
457
961
  }
458
- async function signOut(request2, config) {
962
+ async function signOut(request2, config, client) {
459
963
  const session = await readSession(request2.cookies, config);
460
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);
461
974
  let destination = landing;
462
975
  if (session?.rt) {
463
976
  await revoke(config, session.rt);
@@ -468,36 +981,36 @@ async function signOut(request2, config) {
468
981
  if (end_session_endpoint) {
469
982
  const end = new URL(end_session_endpoint);
470
983
  end.search = new URLSearchParams({
471
- client_id: config.clientId,
984
+ client_id: clientId,
472
985
  post_logout_redirect_uri: landing,
473
986
  ...session?.it ? { id_token_hint: session.it } : {}
474
987
  }).toString();
475
988
  destination = end.toString();
476
989
  }
477
- const response = NextResponse.redirect(destination);
478
- 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);
479
992
  return response;
480
993
  }
481
- async function pass(request2, config, protectedPath) {
994
+ async function pass(request2, config, client, signInPath) {
482
995
  let session = await readSession(request2.cookies, config);
483
996
  let writes = [];
484
997
  if (session && session.exp - nowSec() <= REFRESH_LEEWAY_SEC) {
485
- const refreshed = await tryRefresh(config, session);
998
+ const refreshed = await tryRefresh(config, session, client);
486
999
  session = refreshed;
487
1000
  writes = await sessionWrites(refreshed, request2.cookies, config);
488
1001
  }
489
- if (!session && protectedPath) {
490
- const signInUrl = new URL(config.routes.signIn, config.appUrl);
1002
+ if (!session && signInPath !== null) {
1003
+ const signInUrl = new URL(signInPath, config.appUrl);
491
1004
  signInUrl.searchParams.set(
492
1005
  "returnTo",
493
1006
  `${request2.nextUrl.pathname}${request2.nextUrl.search}`
494
1007
  );
495
- const response2 = NextResponse.redirect(signInUrl);
496
- apply(response2, writes, config);
1008
+ const response2 = NextResponse2.redirect(signInUrl);
1009
+ applyCookies(response2, writes, config);
497
1010
  return response2;
498
1011
  }
499
1012
  if (writes.length === 0) {
500
- return NextResponse.next();
1013
+ return NextResponse2.next();
501
1014
  }
502
1015
  for (const write of writes) {
503
1016
  if (write.maxAge === 0) {
@@ -506,28 +1019,32 @@ async function pass(request2, config, protectedPath) {
506
1019
  request2.cookies.set(write.name, write.value);
507
1020
  }
508
1021
  }
509
- const response = NextResponse.next({ request: { headers: request2.headers } });
510
- apply(response, writes, config);
1022
+ const response = NextResponse2.next({ request: { headers: request2.headers } });
1023
+ applyCookies(response, writes, config);
511
1024
  return response;
512
1025
  }
513
- async function tryRefresh(config, session) {
1026
+ async function tryRefresh(config, session, client) {
514
1027
  try {
515
- return await refreshSession(config, session);
1028
+ return session.via === "direct" ? await refreshDirectSession(config, session, client) : await refreshSession(config, session);
516
1029
  } catch (caught) {
1030
+ if (caught instanceof CanopyConfigError) {
1031
+ throw caught;
1032
+ }
517
1033
  if (caught instanceof CanopySessionError && caught.code === "connection_failed") {
518
1034
  return session.exp > nowSec() ? session : null;
519
1035
  }
520
1036
  return null;
521
1037
  }
522
1038
  }
523
- function apply(response, writes, config) {
524
- for (const write of writes) {
525
- response.cookies.set(
526
- write.name,
527
- write.value,
528
- cookieOptions(config, write.maxAge)
529
- );
530
- }
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];
531
1048
  }
532
1049
  function isProtected(pathname, protect) {
533
1050
  if (!protect) {
@@ -541,12 +1058,6 @@ function isProtected(pathname, protect) {
541
1058
  return base === "" || pathname === base || pathname.startsWith(`${base}/`);
542
1059
  });
543
1060
  }
544
- function safeReturnTo(value) {
545
- if (!value || !value.startsWith("/") || value.startsWith("//") || value.startsWith("/\\")) {
546
- return "/";
547
- }
548
- return value;
549
- }
550
1061
  function nowSec() {
551
1062
  return Math.floor(Date.now() / 1e3);
552
1063
  }
@@ -580,17 +1091,20 @@ var auth = cache(
580
1091
  if (!session) {
581
1092
  return SIGNED_OUT;
582
1093
  }
1094
+ const verifier = verifierFor(config, audienceOf(config, session));
583
1095
  let claims;
584
1096
  try {
585
- claims = await verifierFor(config).verify(session.at);
1097
+ claims = await verifier.verify(session.at);
586
1098
  } catch {
587
1099
  return SIGNED_OUT;
588
1100
  }
589
- const idClaims = session.it ? decodeClaims(session.it) : null;
1101
+ if (session.via === "direct" && session.who.id !== claims.sub) {
1102
+ return SIGNED_OUT;
1103
+ }
590
1104
  return {
591
1105
  isSignedIn: true,
592
1106
  userId: claims.sub,
593
- user: idClaims ? userOf(idClaims) : { sub: claims.sub },
1107
+ user: displayedUser(session, claims.sub),
594
1108
  claims,
595
1109
  organization: {
596
1110
  orgId: claims.org_id ?? null,
@@ -625,13 +1139,29 @@ function fromList(list, overflow, permission) {
625
1139
  }
626
1140
  return overflow ? void 0 : false;
627
1141
  }
628
- function verifierFor(config) {
629
- 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}`;
630
1160
  let verifier = shared.verifiers.get(key);
631
1161
  if (!verifier) {
632
1162
  verifier = new TokenVerifier({
633
1163
  issuer: config.issuer,
634
- audience: config.clientId
1164
+ audience
635
1165
  });
636
1166
  shared.verifiers.set(key, verifier);
637
1167
  }
@@ -691,12 +1221,24 @@ function clientSession(auth2) {
691
1221
  organization: { ...auth2.organization }
692
1222
  };
693
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
+ }
694
1235
  export {
695
1236
  CanopyConfigError,
696
1237
  CanopySessionError,
697
1238
  DEFAULT_ROUTES,
698
1239
  auth,
699
1240
  canopyProxy,
700
- clientSession
1241
+ clientSession,
1242
+ signInFormProps
701
1243
  };
702
1244
  //# sourceMappingURL=index.js.map