@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.cjs CHANGED
@@ -25,18 +25,20 @@ __export(index_exports, {
25
25
  DEFAULT_ROUTES: () => DEFAULT_ROUTES,
26
26
  auth: () => auth,
27
27
  canopyProxy: () => canopyProxy,
28
- clientSession: () => clientSession
28
+ clientSession: () => clientSession,
29
+ signInFormProps: () => signInFormProps
29
30
  });
30
31
  module.exports = __toCommonJS(index_exports);
31
32
 
32
33
  // src/proxy.ts
33
- var import_server = require("next/server");
34
+ var import_server2 = require("next/server");
34
35
 
35
36
  // src/config.ts
36
37
  var DEFAULT_ROUTES = {
37
38
  signIn: "/auth/sign-in",
38
39
  callback: "/auth/callback",
39
- signOut: "/auth/sign-out"
40
+ signOut: "/auth/sign-out",
41
+ direct: "/auth/direct"
40
42
  };
41
43
  var DEFAULT_SCOPES = ["openid", "profile", "email"];
42
44
  var DEFAULT_SESSION_MAX_AGE_SEC = 180 * 24 * 60 * 60;
@@ -58,31 +60,98 @@ function resolveConfig(options = {}) {
58
60
  `CANOPY_SECRET must be at least ${MIN_SECRET_LENGTH} characters; generate one with \`openssl rand -base64 32\`.`
59
61
  );
60
62
  }
61
- const apiKey = options.apiKey ?? env["CANOPY_API_KEY"];
63
+ const configuredEnvironmentId = optional(
64
+ options.environmentId ?? env["CANOPY_ENVIRONMENT_ID"]
65
+ );
66
+ if (configuredEnvironmentId !== void 0 && !ENVIRONMENT_ID.test(configuredEnvironmentId)) {
67
+ throw new CanopyConfigError(
68
+ `CANOPY_ENVIRONMENT_ID must be the Environment's id, a UUID; ${configuredEnvironmentId} is not one.`
69
+ );
70
+ }
62
71
  return {
63
72
  issuer,
64
- clientId: required(
65
- options.clientId ?? env["CANOPY_CLIENT_ID"],
66
- "CANOPY_CLIENT_ID"
67
- ),
68
- clientSecret: required(
69
- options.clientSecret ?? env["CANOPY_CLIENT_SECRET"],
70
- "CANOPY_CLIENT_SECRET"
73
+ // Canopy writes the id in lowercase, and a token's audience is compared
74
+ // exactly.
75
+ environmentId: configuredEnvironmentId?.toLowerCase(),
76
+ clientId: optional(options.clientId ?? env["CANOPY_CLIENT_ID"]),
77
+ clientSecret: optional(options.clientSecret ?? env["CANOPY_CLIENT_SECRET"]),
78
+ publishableKey: optional(
79
+ options.publishableKey ?? env["CANOPY_PUBLISHABLE_KEY"]
71
80
  ),
72
81
  secret,
73
82
  appUrl: new URL(
74
83
  required(options.appUrl ?? env["CANOPY_APP_URL"], "CANOPY_APP_URL")
75
84
  ).origin,
76
- apiKey: apiKey === "" ? void 0 : apiKey,
85
+ apiKey: optional(options.apiKey ?? env["CANOPY_API_KEY"]),
77
86
  scopes: options.scopes ?? DEFAULT_SCOPES,
78
87
  routes: { ...DEFAULT_ROUTES, ...options.routes },
79
88
  afterSignOutPath: options.afterSignOutPath ?? "/",
80
89
  sessionMaxAgeSec: options.sessionMaxAgeSec ?? DEFAULT_SESSION_MAX_AGE_SEC
81
90
  };
82
91
  }
83
- function required(value, name) {
92
+ function oidcClient(config) {
93
+ const need = "Hosted Login sign-in, its refresh and its sign-out need it.";
94
+ return {
95
+ clientId: required(config.clientId, "CANOPY_CLIENT_ID", need),
96
+ clientSecret: required(config.clientSecret, "CANOPY_CLIENT_SECRET", need)
97
+ };
98
+ }
99
+ function directKeys(config) {
100
+ const need = "The embedded sign-in form's route, and a Direct API session's refresh and sign-out, need it.";
101
+ const publishableKey = required(
102
+ config.publishableKey,
103
+ "CANOPY_PUBLISHABLE_KEY",
104
+ need
105
+ );
106
+ if (!publishableKey.startsWith(PUBLISHABLE_KEY_PREFIX)) {
107
+ throw new CanopyConfigError(
108
+ `CANOPY_PUBLISHABLE_KEY must be the Environment's publishable key (${PUBLISHABLE_KEY_PREFIX}\u2026), which the browser may see.`
109
+ );
110
+ }
111
+ return {
112
+ publishableKey,
113
+ apiKey: required(config.apiKey, "CANOPY_API_KEY", need)
114
+ };
115
+ }
116
+ function canopyOrigin(config) {
117
+ return new URL(config.issuer).origin;
118
+ }
119
+ function environmentId(config) {
120
+ const fromIssuer = environmentIdOfIssuer(config.issuer);
121
+ if (config.environmentId === void 0) {
122
+ if (fromIssuer === void 0) {
123
+ throw new CanopyConfigError(
124
+ `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>.`
125
+ );
126
+ }
127
+ return fromIssuer;
128
+ }
129
+ if (fromIssuer !== void 0 && fromIssuer.toLowerCase() !== config.environmentId.toLowerCase()) {
130
+ throw new CanopyConfigError(
131
+ `CANOPY_ENVIRONMENT_ID (${config.environmentId}) and CANOPY_ISSUER (${config.issuer}) name different Environments.`
132
+ );
133
+ }
134
+ return config.environmentId;
135
+ }
136
+ function environmentIdOfIssuer(issuer) {
137
+ const { pathname } = new URL(issuer);
138
+ const [first, id, ...rest] = pathname.split("/").slice(1);
139
+ if (first !== "environments" || !id || rest.length > 0 || !ENVIRONMENT_ID.test(id)) {
140
+ return void 0;
141
+ }
142
+ return id;
143
+ }
144
+ var PUBLISHABLE_KEY_PREFIX = "pk_";
145
+ var ENVIRONMENT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
146
+ function optional(value) {
147
+ const trimmed = value?.trim();
148
+ return trimmed === void 0 || trimmed === "" ? void 0 : trimmed;
149
+ }
150
+ function required(value, name, need) {
84
151
  if (value === void 0 || value.trim() === "") {
85
- throw new CanopyConfigError(`${name} is not set.`);
152
+ throw new CanopyConfigError(
153
+ need ? `${name} is not set. ${need}` : `${name} is not set.`
154
+ );
86
155
  }
87
156
  return value.trim();
88
157
  }
@@ -94,6 +163,9 @@ function withoutTrailingSlash(value) {
94
163
  return value.slice(0, end);
95
164
  }
96
165
 
166
+ // src/direct.ts
167
+ var import_server = require("next/server");
168
+
97
169
  // src/seal.ts
98
170
  var VERSION = "v1";
99
171
  var IV_BYTES = 12;
@@ -253,6 +325,7 @@ function refreshSession(config, session) {
253
325
  return pending;
254
326
  }
255
327
  async function revoke(config, refreshToken) {
328
+ const { clientId, clientSecret } = oidcClient(config);
256
329
  try {
257
330
  const { revocation_endpoint } = await discover(config);
258
331
  if (!revocation_endpoint) {
@@ -264,8 +337,8 @@ async function revoke(config, refreshToken) {
264
337
  body: new URLSearchParams({
265
338
  token: refreshToken,
266
339
  token_type_hint: "refresh_token",
267
- client_id: config.clientId,
268
- client_secret: config.clientSecret
340
+ client_id: clientId,
341
+ client_secret: clientSecret
269
342
  })
270
343
  });
271
344
  } catch {
@@ -286,6 +359,7 @@ function decodeClaims(token) {
286
359
  }
287
360
  }
288
361
  async function tokenRequest(config, params) {
362
+ const { clientId, clientSecret } = oidcClient(config);
289
363
  const { token_endpoint } = await discover(config);
290
364
  const response = await request(token_endpoint, {
291
365
  method: "POST",
@@ -295,8 +369,8 @@ async function tokenRequest(config, params) {
295
369
  },
296
370
  body: new URLSearchParams({
297
371
  ...params,
298
- client_id: config.clientId,
299
- client_secret: config.clientSecret
372
+ client_id: clientId,
373
+ client_secret: clientSecret
300
374
  })
301
375
  });
302
376
  const body = await response.json().catch(() => null);
@@ -307,6 +381,7 @@ async function tokenRequest(config, params) {
307
381
  );
308
382
  }
309
383
  return {
384
+ via: "oidc",
310
385
  at: body.access_token,
311
386
  ...body.refresh_token ? { rt: body.refresh_token } : {},
312
387
  ...body.id_token ? { it: body.id_token } : {},
@@ -334,6 +409,7 @@ async function request(url, init) {
334
409
  // src/session.ts
335
410
  var SESSION_COOKIE = "canopy_session";
336
411
  var TRANSACTION_COOKIE = "canopy_tx";
412
+ var DEVICE_COOKIE = "canopy_device";
337
413
  var CHUNK_SIZE = 3800;
338
414
  var TRANSACTION_MAX_AGE_SEC = 10 * 60;
339
415
  async function readSession(cookies2, config) {
@@ -347,7 +423,27 @@ async function readSession(cookies2, config) {
347
423
  chunks.map((chunk) => chunk.value).join(""),
348
424
  config.secret
349
425
  );
350
- return session && typeof session.at === "string" && typeof session.exp === "number" ? session : null;
426
+ return isStoredSession(session) ? session : null;
427
+ }
428
+ function isStoredSession(value) {
429
+ if (typeof value !== "object" || value === null) {
430
+ return false;
431
+ }
432
+ const session = value;
433
+ if (typeof session["at"] !== "string" || typeof session["exp"] !== "number") {
434
+ return false;
435
+ }
436
+ if (session["via"] === "oidc") {
437
+ return true;
438
+ }
439
+ return session["via"] === "direct" && typeof session["rt"] === "string" && isDirectIdentity(session["who"]);
440
+ }
441
+ function isDirectIdentity(value) {
442
+ if (typeof value !== "object" || value === null) {
443
+ return false;
444
+ }
445
+ const identity = value;
446
+ return typeof identity["id"] === "string" && identity["id"] !== "" && typeof identity["email"] === "string" && typeof identity["first_name"] === "string" && typeof identity["last_name"] === "string";
351
447
  }
352
448
  async function sessionWrites(session, existing, config) {
353
449
  const held = existing.getAll().map(({ name }) => chunkIndex(name)).filter((index) => index !== null);
@@ -381,6 +477,17 @@ async function transactionWrite(transaction, config) {
381
477
  async function readTransaction(value, config) {
382
478
  return value ? open(value, config.secret) : null;
383
479
  }
480
+ async function deviceWrite(device, config) {
481
+ return {
482
+ name: DEVICE_COOKIE,
483
+ value: await seal(device, config.secret),
484
+ maxAge: Math.max(0, device.exp - Math.floor(Date.now() / 1e3))
485
+ };
486
+ }
487
+ async function readDevice(value, config) {
488
+ const device = value ? await open(value, config.secret) : null;
489
+ return device && typeof device.token === "string" && typeof device.exp === "number" && device.exp > Math.floor(Date.now() / 1e3) ? device : null;
490
+ }
384
491
  function cookieOptions(config, maxAge) {
385
492
  return {
386
493
  httpOnly: true,
@@ -390,6 +497,15 @@ function cookieOptions(config, maxAge) {
390
497
  maxAge
391
498
  };
392
499
  }
500
+ function applyCookies(response, writes, config) {
501
+ for (const write of writes) {
502
+ response.cookies.set(
503
+ write.name,
504
+ write.value,
505
+ cookieOptions(config, write.maxAge)
506
+ );
507
+ }
508
+ }
393
509
  function chunkIndex(name) {
394
510
  const prefix = `${SESSION_COOKIE}.`;
395
511
  if (!name.startsWith(prefix)) {
@@ -399,13 +515,395 @@ function chunkIndex(name) {
399
515
  return Number.isInteger(index) && index >= 0 ? index : null;
400
516
  }
401
517
 
518
+ // src/direct.ts
519
+ var AUTH_PATH = "/v1/identity/auth";
520
+ var ROUTES = /* @__PURE__ */ new Map([
521
+ [`${AUTH_PATH}/login`, { key: true, device: true }],
522
+ [`${AUTH_PATH}/login/sso-recovery`, { key: true }],
523
+ [`${AUTH_PATH}/login/email-otp/start`, { key: true }],
524
+ [`${AUTH_PATH}/login/email-otp/verify`, { key: true, device: true }],
525
+ [`${AUTH_PATH}/login/passkey/options`, { key: true }],
526
+ [`${AUTH_PATH}/login/passkey/verify`, { key: true, device: true }],
527
+ [`${AUTH_PATH}/login/mfa-enroll/totp/verify`, { key: true }],
528
+ [`${AUTH_PATH}/login/mfa-enroll/webauthn/options`, { key: true }],
529
+ [`${AUTH_PATH}/login/mfa-enroll/webauthn/verify`, { key: true }],
530
+ [`${AUTH_PATH}/register`, { key: true }],
531
+ [`${AUTH_PATH}/mfa/challenge/totp`, { key: false }],
532
+ [`${AUTH_PATH}/mfa/challenge/recovery-code`, { key: false }],
533
+ [`${AUTH_PATH}/mfa/challenge/email-otp/send`, { key: false }],
534
+ [`${AUTH_PATH}/mfa/challenge/email-otp/verify`, { key: false }],
535
+ [`${AUTH_PATH}/mfa/challenge/webauthn/options`, { key: false }],
536
+ [`${AUTH_PATH}/mfa/challenge/webauthn/verify`, { key: false }],
537
+ [`${AUTH_PATH}/verify-email`, { key: false }],
538
+ [`${AUTH_PATH}/verify-email-code`, { key: true }],
539
+ [`${AUTH_PATH}/resend-verification`, { key: true }],
540
+ [`${AUTH_PATH}/forgot-password`, { key: true }],
541
+ [`${AUTH_PATH}/forgot-password-code`, { key: true }],
542
+ [`${AUTH_PATH}/reset-password`, { key: false }],
543
+ [`${AUTH_PATH}/reset-password-code`, { key: true }],
544
+ [`${AUTH_PATH}/sso/resolve`, { key: true }],
545
+ [`${AUTH_PATH}/sso/authenticate`, { key: true, device: true }]
546
+ ]);
547
+ var OWNED_FIELDS = ["publishable_key", "trusted_device_token"];
548
+ var CREDENTIAL_FIELDS = [
549
+ "access_token",
550
+ "refresh_token",
551
+ "trusted_device_token"
552
+ ];
553
+ var SIGNED_IN_FIELDS = [
554
+ "requires_mfa_challenge",
555
+ "mfa_enrollment_pending",
556
+ "grace_expires_at",
557
+ "recovery_codes",
558
+ "device_remembered"
559
+ ];
560
+ var MAX_BODY_BYTES = 64 * 1024;
561
+ var TIMEOUT_MS = 1e4;
562
+ async function direct(request2, config, client) {
563
+ const path = request2.nextUrl.pathname.slice(config.routes.direct.length);
564
+ const route = ROUTES.get(path);
565
+ if (!route || request2.method !== "POST") {
566
+ return refuse(404, "not_found", "There is no such route.");
567
+ }
568
+ const fetchSite = request2.headers.get("sec-fetch-site");
569
+ if (request2.headers.get("origin") !== config.appUrl || fetchSite !== null && fetchSite !== "same-origin") {
570
+ return refuse(
571
+ 403,
572
+ "forbidden_origin",
573
+ "Only this site's own pages may send this."
574
+ );
575
+ }
576
+ if (mediaType(request2.headers.get("content-type")) !== "application/json") {
577
+ return refuse(400, "invalid_request", "Send a JSON body.");
578
+ }
579
+ const sent = await jsonObjectOf(request2);
580
+ if (!sent) {
581
+ return refuse(
582
+ 400,
583
+ "invalid_request",
584
+ "Send one JSON object of at most 64 KB."
585
+ );
586
+ }
587
+ const { publishableKey, apiKey } = directKeys(config);
588
+ environmentId(config);
589
+ const body = { ...sent };
590
+ for (const field of OWNED_FIELDS) {
591
+ delete body[field];
592
+ }
593
+ if (route.key) {
594
+ body["publishable_key"] = publishableKey;
595
+ }
596
+ if (route.device) {
597
+ const device2 = await readDevice(
598
+ request2.cookies.get(DEVICE_COOKIE)?.value,
599
+ config
600
+ );
601
+ if (device2) {
602
+ body["trusted_device_token"] = device2.token;
603
+ }
604
+ }
605
+ const answer = await callCanopy(config, path, body, {
606
+ ...canopyHeaders(apiKey, client),
607
+ ...languageOf(request2)
608
+ });
609
+ if (!answer) {
610
+ return refuse(502, "connection_failed", "Canopy could not be reached.");
611
+ }
612
+ if (answer.status < 200 || answer.status >= 300) {
613
+ return reply(answer.status, refusalOf(answer.body), answer.retryAfter);
614
+ }
615
+ const data = answer.body.data;
616
+ if (!isRecord(data) || !CREDENTIAL_FIELDS.some((field) => Object.hasOwn(data, field))) {
617
+ if (carriesCredential(data)) {
618
+ return refuse(
619
+ 500,
620
+ "session_not_delivered",
621
+ "Canopy answered with a credential this server does not keep."
622
+ );
623
+ }
624
+ return reply(answer.status, data === void 0 ? {} : { data }, null);
625
+ }
626
+ const session = sessionOf(data);
627
+ if (!session) {
628
+ return refuse(
629
+ 500,
630
+ "session_not_delivered",
631
+ "Canopy did not hand the session to this server. CANOPY_API_KEY must be a secret API key of the publishable key's Environment."
632
+ );
633
+ }
634
+ const writes = await sessionWrites(
635
+ session,
636
+ request2.cookies,
637
+ config
638
+ );
639
+ const device = await rememberedDevice(data, config);
640
+ if (device) {
641
+ writes.push(device);
642
+ }
643
+ const response = reply(answer.status, { data: signedInView(data) }, null);
644
+ applyCookies(response, writes, config);
645
+ return response;
646
+ }
647
+ var refreshes2 = /* @__PURE__ */ new Map();
648
+ function refreshDirectSession(config, session, client) {
649
+ let pending = refreshes2.get(session.rt);
650
+ if (!pending) {
651
+ pending = (async () => {
652
+ const { apiKey } = directKeys(config);
653
+ const answer = await callCanopy(
654
+ config,
655
+ `${AUTH_PATH}/refresh`,
656
+ { refresh_token: session.rt },
657
+ canopyHeaders(apiKey, client)
658
+ );
659
+ if (!answer) {
660
+ throw new CanopySessionError(
661
+ "connection_failed",
662
+ "Canopy could not be reached."
663
+ );
664
+ }
665
+ const data = answer.body.data;
666
+ if (answer.status < 200 || answer.status >= 300 || !isRecord(data)) {
667
+ throw new CanopySessionError(
668
+ refusalOf(answer.body).error.code,
669
+ `Canopy's refresh answered ${answer.status}.`
670
+ );
671
+ }
672
+ const at = data["access_token"];
673
+ const rt = data["refresh_token"];
674
+ if (typeof at !== "string" || typeof rt !== "string") {
675
+ throw new CanopySessionError(
676
+ "session_not_delivered",
677
+ "Canopy's refresh carried no refresh token for this server."
678
+ );
679
+ }
680
+ return {
681
+ via: "direct",
682
+ at,
683
+ rt,
684
+ exp: expiryOf({ access_token: at, ...expiresIn(data) }),
685
+ who: session.who
686
+ };
687
+ })();
688
+ refreshes2.set(session.rt, pending);
689
+ pending.then(
690
+ () => refreshes2.delete(session.rt),
691
+ () => refreshes2.delete(session.rt)
692
+ );
693
+ }
694
+ return pending;
695
+ }
696
+ async function endDirectSession(config, session, client) {
697
+ const { apiKey } = directKeys(config);
698
+ await callCanopy(
699
+ config,
700
+ `${AUTH_PATH}/logout`,
701
+ { refresh_token: session.rt },
702
+ canopyHeaders(apiKey, client)
703
+ );
704
+ }
705
+ async function callCanopy(config, path, body, headers) {
706
+ let response;
707
+ try {
708
+ response = await fetch(`${canopyOrigin(config)}${path}`, {
709
+ method: "POST",
710
+ headers,
711
+ body: JSON.stringify(body),
712
+ redirect: "manual",
713
+ signal: AbortSignal.timeout(TIMEOUT_MS),
714
+ cache: "no-store"
715
+ });
716
+ } catch {
717
+ return null;
718
+ }
719
+ if (response.type === "opaqueredirect" || isRedirect(response.status)) {
720
+ return null;
721
+ }
722
+ const text = await response.text().catch(() => null);
723
+ if (text === null) {
724
+ return null;
725
+ }
726
+ let parsed = {};
727
+ if (text !== "") {
728
+ try {
729
+ parsed = JSON.parse(text);
730
+ } catch {
731
+ return null;
732
+ }
733
+ }
734
+ return {
735
+ status: response.status,
736
+ body: isRecord(parsed) ? parsed : {},
737
+ retryAfter: response.headers.get("retry-after")
738
+ };
739
+ }
740
+ function canopyHeaders(apiKey, client) {
741
+ return {
742
+ "Content-Type": "application/json",
743
+ "X-API-Key": apiKey,
744
+ ...client.ip ? { "X-Canopy-Client-IP": client.ip } : {},
745
+ ...client.userAgent ? { "X-Canopy-Client-User-Agent": client.userAgent } : {}
746
+ };
747
+ }
748
+ function languageOf(request2) {
749
+ const language = request2.headers.get("accept-language");
750
+ return language ? { "Accept-Language": language } : {};
751
+ }
752
+ function sessionOf(data) {
753
+ const at = data["access_token"];
754
+ const rt = data["refresh_token"];
755
+ const identity = data["identity"];
756
+ if (typeof at !== "string" || typeof rt !== "string" || !isDirectIdentity(identity)) {
757
+ return null;
758
+ }
759
+ return {
760
+ via: "direct",
761
+ at,
762
+ rt,
763
+ exp: expiryOf({ access_token: at, ...expiresIn(data) }),
764
+ who: identityOf(identity)
765
+ };
766
+ }
767
+ async function rememberedDevice(data, config) {
768
+ const token = data["trusted_device_token"];
769
+ const expiresAt = data["trusted_device_expires_at"];
770
+ if (typeof token !== "string" || typeof expiresAt !== "string") {
771
+ return null;
772
+ }
773
+ const exp = Math.floor(Date.parse(expiresAt) / 1e3);
774
+ if (!Number.isFinite(exp) || exp <= Math.floor(Date.now() / 1e3)) {
775
+ return null;
776
+ }
777
+ return deviceWrite({ token, exp }, config);
778
+ }
779
+ function signedInView(data) {
780
+ const view = {};
781
+ for (const field of SIGNED_IN_FIELDS) {
782
+ if (Object.hasOwn(data, field)) {
783
+ view[field] = data[field];
784
+ }
785
+ }
786
+ view["identity"] = identityOf(data["identity"]);
787
+ return view;
788
+ }
789
+ function identityOf(identity) {
790
+ return {
791
+ id: identity.id,
792
+ email: identity.email,
793
+ first_name: identity.first_name,
794
+ last_name: identity.last_name
795
+ };
796
+ }
797
+ function expiresIn(data) {
798
+ const value = data["expires_in"];
799
+ return typeof value === "number" ? { expires_in: value } : {};
800
+ }
801
+ function refusalOf(body) {
802
+ const error = isRecord(body) ? body["error"] : void 0;
803
+ const code = isRecord(error) ? error["code"] : void 0;
804
+ const message = isRecord(error) ? error["message"] : void 0;
805
+ return {
806
+ error: {
807
+ code: typeof code === "string" ? code : "server_error",
808
+ message: typeof message === "string" ? message : "Canopy refused."
809
+ }
810
+ };
811
+ }
812
+ function refuse(status, code, message) {
813
+ return reply(status, { error: { code, message } }, null);
814
+ }
815
+ function reply(status, body, retryAfter) {
816
+ return import_server.NextResponse.json(body, {
817
+ status,
818
+ headers: {
819
+ "Cache-Control": "no-store",
820
+ ...retryAfter && /^\d{1,6}$/.test(retryAfter) ? { "Retry-After": retryAfter } : {}
821
+ }
822
+ });
823
+ }
824
+ async function jsonObjectOf(request2) {
825
+ const declared = Number(request2.headers.get("content-length"));
826
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
827
+ return null;
828
+ }
829
+ if (!request2.body) {
830
+ return null;
831
+ }
832
+ const reader = request2.body.getReader();
833
+ const chunks = [];
834
+ let size = 0;
835
+ for (; ; ) {
836
+ const { done, value } = await reader.read();
837
+ if (done) {
838
+ break;
839
+ }
840
+ size += value.byteLength;
841
+ if (size > MAX_BODY_BYTES) {
842
+ await reader.cancel();
843
+ return null;
844
+ }
845
+ chunks.push(value);
846
+ }
847
+ const bytes = new Uint8Array(size);
848
+ let offset = 0;
849
+ for (const chunk of chunks) {
850
+ bytes.set(chunk, offset);
851
+ offset += chunk.byteLength;
852
+ }
853
+ try {
854
+ const parsed = JSON.parse(
855
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes)
856
+ );
857
+ return isRecord(parsed) ? parsed : null;
858
+ } catch {
859
+ return null;
860
+ }
861
+ }
862
+ function carriesCredential(value) {
863
+ if (Array.isArray(value)) {
864
+ return value.some(carriesCredential);
865
+ }
866
+ if (!isRecord(value)) {
867
+ return false;
868
+ }
869
+ return Object.entries(value).some(
870
+ ([field, inner]) => CREDENTIAL_FIELDS.includes(field) || carriesCredential(inner)
871
+ );
872
+ }
873
+ function mediaType(value) {
874
+ return value?.split(";")[0]?.trim().toLowerCase() ?? null;
875
+ }
876
+ function isRecord(value) {
877
+ return typeof value === "object" && value !== null && !Array.isArray(value);
878
+ }
879
+ function isRedirect(status) {
880
+ return status >= 300 && status < 400;
881
+ }
882
+
883
+ // src/return-to.ts
884
+ function safeReturnTo(value) {
885
+ if (!value || !value.startsWith("/") || value.startsWith("//") || value.startsWith("/\\")) {
886
+ return "/";
887
+ }
888
+ return value;
889
+ }
890
+
402
891
  // src/proxy.ts
403
892
  var REFRESH_LEEWAY_SEC = 60;
404
893
  function canopyProxy(options = {}) {
894
+ if (options.signInPage !== void 0 && safeReturnTo(options.signInPage) !== options.signInPage) {
895
+ throw new CanopyConfigError(
896
+ `signInPage must be a path on this site, such as "/sign-in"; "${options.signInPage}" is not one.`
897
+ );
898
+ }
405
899
  let config;
406
900
  return async (request2) => {
407
901
  config ??= resolveConfig(options);
408
902
  const { pathname } = request2.nextUrl;
903
+ const client = clientOf(request2, options.clientAddress);
904
+ if (pathname === config.routes.direct || pathname.startsWith(`${config.routes.direct}/`)) {
905
+ return direct(request2, config, client);
906
+ }
409
907
  if (pathname === config.routes.signIn) {
410
908
  return signIn(request2, config);
411
909
  }
@@ -413,9 +911,16 @@ function canopyProxy(options = {}) {
413
911
  return callback(request2, config);
414
912
  }
415
913
  if (pathname === config.routes.signOut) {
416
- return signOut(request2, config);
914
+ return signOut(request2, config, client);
417
915
  }
418
- return pass(request2, config, isProtected(pathname, options.protect));
916
+ return pass(
917
+ request2,
918
+ config,
919
+ client,
920
+ // The sign-in page itself stays open even inside a protected path,
921
+ // or a signed-out visitor would be sent to it without end.
922
+ isProtected(pathname, options.protect) && pathname !== options.signInPage ? options.signInPage ?? config.routes.signIn : null
923
+ );
419
924
  };
420
925
  }
421
926
  async function signIn(request2, config) {
@@ -430,7 +935,7 @@ async function signIn(request2, config) {
430
935
  const authorize = new URL(authorization_endpoint);
431
936
  authorize.search = new URLSearchParams({
432
937
  response_type: "code",
433
- client_id: config.clientId,
938
+ client_id: oidcClient(config).clientId,
434
939
  redirect_uri: callbackUrl(config),
435
940
  scope: config.scopes.join(" "),
436
941
  state: transaction.state,
@@ -438,8 +943,8 @@ async function signIn(request2, config) {
438
943
  code_challenge: await codeChallenge(transaction.verifier),
439
944
  code_challenge_method: "S256"
440
945
  }).toString();
441
- const response = import_server.NextResponse.redirect(authorize);
442
- apply(response, [await transactionWrite(transaction, config)], config);
946
+ const response = import_server2.NextResponse.redirect(authorize);
947
+ applyCookies(response, [await transactionWrite(transaction, config)], config);
443
948
  return response;
444
949
  }
445
950
  async function callback(request2, config) {
@@ -454,20 +959,20 @@ async function callback(request2, config) {
454
959
  maxAge: 0
455
960
  };
456
961
  if (!transaction || params.get("state") !== transaction.state) {
457
- const response2 = new import_server.NextResponse(
962
+ const response2 = new import_server2.NextResponse(
458
963
  "This sign-in has expired. Start it again.",
459
964
  {
460
965
  status: 400
461
966
  }
462
967
  );
463
- apply(response2, [cleared], config);
968
+ applyCookies(response2, [cleared], config);
464
969
  return response2;
465
970
  }
466
971
  const back = new URL(transaction.returnTo, config.appUrl);
467
972
  const code = params.get("code");
468
973
  if (!code) {
469
- const response2 = import_server.NextResponse.redirect(back);
470
- apply(response2, [cleared], config);
974
+ const response2 = import_server2.NextResponse.redirect(back);
975
+ applyCookies(response2, [cleared], config);
471
976
  return response2;
472
977
  }
473
978
  const session = await exchangeCode(config, code, transaction.verifier);
@@ -478,17 +983,26 @@ async function callback(request2, config) {
478
983
  "The ID token's nonce does not match this sign-in."
479
984
  );
480
985
  }
481
- const response = import_server.NextResponse.redirect(back);
482
- apply(
986
+ const response = import_server2.NextResponse.redirect(back);
987
+ applyCookies(
483
988
  response,
484
989
  [cleared, ...await sessionWrites(session, request2.cookies, config)],
485
990
  config
486
991
  );
487
992
  return response;
488
993
  }
489
- async function signOut(request2, config) {
994
+ async function signOut(request2, config, client) {
490
995
  const session = await readSession(request2.cookies, config);
491
996
  const landing = `${config.appUrl}${config.afterSignOutPath}`;
997
+ if (session?.via === "direct" || !session && config.clientId === void 0) {
998
+ if (session?.via === "direct") {
999
+ await endDirectSession(config, session, client);
1000
+ }
1001
+ const response2 = import_server2.NextResponse.redirect(landing);
1002
+ applyCookies(response2, await sessionWrites(null, request2.cookies, config), config);
1003
+ return response2;
1004
+ }
1005
+ const { clientId } = oidcClient(config);
492
1006
  let destination = landing;
493
1007
  if (session?.rt) {
494
1008
  await revoke(config, session.rt);
@@ -499,36 +1013,36 @@ async function signOut(request2, config) {
499
1013
  if (end_session_endpoint) {
500
1014
  const end = new URL(end_session_endpoint);
501
1015
  end.search = new URLSearchParams({
502
- client_id: config.clientId,
1016
+ client_id: clientId,
503
1017
  post_logout_redirect_uri: landing,
504
1018
  ...session?.it ? { id_token_hint: session.it } : {}
505
1019
  }).toString();
506
1020
  destination = end.toString();
507
1021
  }
508
- const response = import_server.NextResponse.redirect(destination);
509
- apply(response, await sessionWrites(null, request2.cookies, config), config);
1022
+ const response = import_server2.NextResponse.redirect(destination);
1023
+ applyCookies(response, await sessionWrites(null, request2.cookies, config), config);
510
1024
  return response;
511
1025
  }
512
- async function pass(request2, config, protectedPath) {
1026
+ async function pass(request2, config, client, signInPath) {
513
1027
  let session = await readSession(request2.cookies, config);
514
1028
  let writes = [];
515
1029
  if (session && session.exp - nowSec() <= REFRESH_LEEWAY_SEC) {
516
- const refreshed = await tryRefresh(config, session);
1030
+ const refreshed = await tryRefresh(config, session, client);
517
1031
  session = refreshed;
518
1032
  writes = await sessionWrites(refreshed, request2.cookies, config);
519
1033
  }
520
- if (!session && protectedPath) {
521
- const signInUrl = new URL(config.routes.signIn, config.appUrl);
1034
+ if (!session && signInPath !== null) {
1035
+ const signInUrl = new URL(signInPath, config.appUrl);
522
1036
  signInUrl.searchParams.set(
523
1037
  "returnTo",
524
1038
  `${request2.nextUrl.pathname}${request2.nextUrl.search}`
525
1039
  );
526
- const response2 = import_server.NextResponse.redirect(signInUrl);
527
- apply(response2, writes, config);
1040
+ const response2 = import_server2.NextResponse.redirect(signInUrl);
1041
+ applyCookies(response2, writes, config);
528
1042
  return response2;
529
1043
  }
530
1044
  if (writes.length === 0) {
531
- return import_server.NextResponse.next();
1045
+ return import_server2.NextResponse.next();
532
1046
  }
533
1047
  for (const write of writes) {
534
1048
  if (write.maxAge === 0) {
@@ -537,28 +1051,32 @@ async function pass(request2, config, protectedPath) {
537
1051
  request2.cookies.set(write.name, write.value);
538
1052
  }
539
1053
  }
540
- const response = import_server.NextResponse.next({ request: { headers: request2.headers } });
541
- apply(response, writes, config);
1054
+ const response = import_server2.NextResponse.next({ request: { headers: request2.headers } });
1055
+ applyCookies(response, writes, config);
542
1056
  return response;
543
1057
  }
544
- async function tryRefresh(config, session) {
1058
+ async function tryRefresh(config, session, client) {
545
1059
  try {
546
- return await refreshSession(config, session);
1060
+ return session.via === "direct" ? await refreshDirectSession(config, session, client) : await refreshSession(config, session);
547
1061
  } catch (caught) {
1062
+ if (caught instanceof CanopyConfigError) {
1063
+ throw caught;
1064
+ }
548
1065
  if (caught instanceof CanopySessionError && caught.code === "connection_failed") {
549
1066
  return session.exp > nowSec() ? session : null;
550
1067
  }
551
1068
  return null;
552
1069
  }
553
1070
  }
554
- function apply(response, writes, config) {
555
- for (const write of writes) {
556
- response.cookies.set(
557
- write.name,
558
- write.value,
559
- cookieOptions(config, write.maxAge)
560
- );
561
- }
1071
+ function clientOf(request2, clientAddress) {
1072
+ const ip = (clientAddress ?? firstForwardedFor)(request2)?.trim();
1073
+ return {
1074
+ ip: ip === "" ? void 0 : ip,
1075
+ userAgent: request2.headers.get("user-agent") ?? void 0
1076
+ };
1077
+ }
1078
+ function firstForwardedFor(request2) {
1079
+ return request2.headers.get("x-forwarded-for")?.split(",")[0];
562
1080
  }
563
1081
  function isProtected(pathname, protect) {
564
1082
  if (!protect) {
@@ -572,12 +1090,6 @@ function isProtected(pathname, protect) {
572
1090
  return base === "" || pathname === base || pathname.startsWith(`${base}/`);
573
1091
  });
574
1092
  }
575
- function safeReturnTo(value) {
576
- if (!value || !value.startsWith("/") || value.startsWith("//") || value.startsWith("/\\")) {
577
- return "/";
578
- }
579
- return value;
580
- }
581
1093
  function nowSec() {
582
1094
  return Math.floor(Date.now() / 1e3);
583
1095
  }
@@ -607,17 +1119,20 @@ var auth = (0, import_react.cache)(
607
1119
  if (!session) {
608
1120
  return SIGNED_OUT;
609
1121
  }
1122
+ const verifier = verifierFor(config, audienceOf(config, session));
610
1123
  let claims;
611
1124
  try {
612
- claims = await verifierFor(config).verify(session.at);
1125
+ claims = await verifier.verify(session.at);
613
1126
  } catch {
614
1127
  return SIGNED_OUT;
615
1128
  }
616
- const idClaims = session.it ? decodeClaims(session.it) : null;
1129
+ if (session.via === "direct" && session.who.id !== claims.sub) {
1130
+ return SIGNED_OUT;
1131
+ }
617
1132
  return {
618
1133
  isSignedIn: true,
619
1134
  userId: claims.sub,
620
- user: idClaims ? userOf(idClaims) : { sub: claims.sub },
1135
+ user: displayedUser(session, claims.sub),
621
1136
  claims,
622
1137
  organization: {
623
1138
  orgId: claims.org_id ?? null,
@@ -652,13 +1167,29 @@ function fromList(list, overflow, permission) {
652
1167
  }
653
1168
  return overflow ? void 0 : false;
654
1169
  }
655
- function verifierFor(config) {
656
- const key = `${config.issuer}\0${config.clientId}`;
1170
+ function audienceOf(config, session) {
1171
+ return session.via === "direct" ? environmentId(config) : oidcClient(config).clientId;
1172
+ }
1173
+ function displayedUser(session, sub) {
1174
+ if (session.via === "direct") {
1175
+ const { who } = session;
1176
+ const name = `${who.first_name} ${who.last_name}`.trim();
1177
+ return {
1178
+ sub,
1179
+ ...who.email ? { email: who.email } : {},
1180
+ ...name ? { name } : {}
1181
+ };
1182
+ }
1183
+ const idClaims = session.it ? decodeClaims(session.it) : null;
1184
+ return idClaims ? userOf(idClaims) : { sub };
1185
+ }
1186
+ function verifierFor(config, audience) {
1187
+ const key = `${config.issuer}\0${audience}`;
657
1188
  let verifier = shared.verifiers.get(key);
658
1189
  if (!verifier) {
659
1190
  verifier = new import_node.TokenVerifier({
660
1191
  issuer: config.issuer,
661
- audience: config.clientId
1192
+ audience
662
1193
  });
663
1194
  shared.verifiers.set(key, verifier);
664
1195
  }
@@ -718,6 +1249,17 @@ function clientSession(auth2) {
718
1249
  organization: { ...auth2.organization }
719
1250
  };
720
1251
  }
1252
+
1253
+ // src/sign-in-form-props.ts
1254
+ function signInFormProps(options) {
1255
+ const config = resolveConfig(options);
1256
+ environmentId(config);
1257
+ return {
1258
+ publishableKey: directKeys(config).publishableKey,
1259
+ canopyOrigin: canopyOrigin(config),
1260
+ directPath: config.routes.direct
1261
+ };
1262
+ }
721
1263
  // Annotate the CommonJS export names for ESM import in node:
722
1264
  0 && (module.exports = {
723
1265
  CanopyConfigError,
@@ -725,6 +1267,7 @@ function clientSession(auth2) {
725
1267
  DEFAULT_ROUTES,
726
1268
  auth,
727
1269
  canopyProxy,
728
- clientSession
1270
+ clientSession,
1271
+ signInFormProps
729
1272
  });
730
1273
  //# sourceMappingURL=index.cjs.map