@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.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,38 +60,112 @@ 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
  }
89
158
  function withoutTrailingSlash(value) {
90
- return value.replace(/\/+$/, "");
159
+ let end = value.length;
160
+ while (end > 0 && value[end - 1] === "/") {
161
+ end -= 1;
162
+ }
163
+ return value.slice(0, end);
91
164
  }
92
165
 
166
+ // src/direct.ts
167
+ var import_server = require("next/server");
168
+
93
169
  // src/seal.ts
94
170
  var VERSION = "v1";
95
171
  var IV_BYTES = 12;
@@ -249,6 +325,7 @@ function refreshSession(config, session) {
249
325
  return pending;
250
326
  }
251
327
  async function revoke(config, refreshToken) {
328
+ const { clientId, clientSecret } = oidcClient(config);
252
329
  try {
253
330
  const { revocation_endpoint } = await discover(config);
254
331
  if (!revocation_endpoint) {
@@ -260,8 +337,8 @@ async function revoke(config, refreshToken) {
260
337
  body: new URLSearchParams({
261
338
  token: refreshToken,
262
339
  token_type_hint: "refresh_token",
263
- client_id: config.clientId,
264
- client_secret: config.clientSecret
340
+ client_id: clientId,
341
+ client_secret: clientSecret
265
342
  })
266
343
  });
267
344
  } catch {
@@ -282,6 +359,7 @@ function decodeClaims(token) {
282
359
  }
283
360
  }
284
361
  async function tokenRequest(config, params) {
362
+ const { clientId, clientSecret } = oidcClient(config);
285
363
  const { token_endpoint } = await discover(config);
286
364
  const response = await request(token_endpoint, {
287
365
  method: "POST",
@@ -291,8 +369,8 @@ async function tokenRequest(config, params) {
291
369
  },
292
370
  body: new URLSearchParams({
293
371
  ...params,
294
- client_id: config.clientId,
295
- client_secret: config.clientSecret
372
+ client_id: clientId,
373
+ client_secret: clientSecret
296
374
  })
297
375
  });
298
376
  const body = await response.json().catch(() => null);
@@ -303,6 +381,7 @@ async function tokenRequest(config, params) {
303
381
  );
304
382
  }
305
383
  return {
384
+ via: "oidc",
306
385
  at: body.access_token,
307
386
  ...body.refresh_token ? { rt: body.refresh_token } : {},
308
387
  ...body.id_token ? { it: body.id_token } : {},
@@ -330,6 +409,7 @@ async function request(url, init) {
330
409
  // src/session.ts
331
410
  var SESSION_COOKIE = "canopy_session";
332
411
  var TRANSACTION_COOKIE = "canopy_tx";
412
+ var DEVICE_COOKIE = "canopy_device";
333
413
  var CHUNK_SIZE = 3800;
334
414
  var TRANSACTION_MAX_AGE_SEC = 10 * 60;
335
415
  async function readSession(cookies2, config) {
@@ -343,7 +423,27 @@ async function readSession(cookies2, config) {
343
423
  chunks.map((chunk) => chunk.value).join(""),
344
424
  config.secret
345
425
  );
346
- 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";
347
447
  }
348
448
  async function sessionWrites(session, existing, config) {
349
449
  const held = existing.getAll().map(({ name }) => chunkIndex(name)).filter((index) => index !== null);
@@ -377,6 +477,17 @@ async function transactionWrite(transaction, config) {
377
477
  async function readTransaction(value, config) {
378
478
  return value ? open(value, config.secret) : null;
379
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
+ }
380
491
  function cookieOptions(config, maxAge) {
381
492
  return {
382
493
  httpOnly: true,
@@ -386,6 +497,15 @@ function cookieOptions(config, maxAge) {
386
497
  maxAge
387
498
  };
388
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
+ }
389
509
  function chunkIndex(name) {
390
510
  const prefix = `${SESSION_COOKIE}.`;
391
511
  if (!name.startsWith(prefix)) {
@@ -395,13 +515,395 @@ function chunkIndex(name) {
395
515
  return Number.isInteger(index) && index >= 0 ? index : null;
396
516
  }
397
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
+
398
891
  // src/proxy.ts
399
892
  var REFRESH_LEEWAY_SEC = 60;
400
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
+ }
401
899
  let config;
402
900
  return async (request2) => {
403
901
  config ??= resolveConfig(options);
404
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
+ }
405
907
  if (pathname === config.routes.signIn) {
406
908
  return signIn(request2, config);
407
909
  }
@@ -409,9 +911,16 @@ function canopyProxy(options = {}) {
409
911
  return callback(request2, config);
410
912
  }
411
913
  if (pathname === config.routes.signOut) {
412
- return signOut(request2, config);
914
+ return signOut(request2, config, client);
413
915
  }
414
- 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
+ );
415
924
  };
416
925
  }
417
926
  async function signIn(request2, config) {
@@ -426,7 +935,7 @@ async function signIn(request2, config) {
426
935
  const authorize = new URL(authorization_endpoint);
427
936
  authorize.search = new URLSearchParams({
428
937
  response_type: "code",
429
- client_id: config.clientId,
938
+ client_id: oidcClient(config).clientId,
430
939
  redirect_uri: callbackUrl(config),
431
940
  scope: config.scopes.join(" "),
432
941
  state: transaction.state,
@@ -434,8 +943,8 @@ async function signIn(request2, config) {
434
943
  code_challenge: await codeChallenge(transaction.verifier),
435
944
  code_challenge_method: "S256"
436
945
  }).toString();
437
- const response = import_server.NextResponse.redirect(authorize);
438
- apply(response, [await transactionWrite(transaction, config)], config);
946
+ const response = import_server2.NextResponse.redirect(authorize);
947
+ applyCookies(response, [await transactionWrite(transaction, config)], config);
439
948
  return response;
440
949
  }
441
950
  async function callback(request2, config) {
@@ -450,20 +959,20 @@ async function callback(request2, config) {
450
959
  maxAge: 0
451
960
  };
452
961
  if (!transaction || params.get("state") !== transaction.state) {
453
- const response2 = new import_server.NextResponse(
962
+ const response2 = new import_server2.NextResponse(
454
963
  "This sign-in has expired. Start it again.",
455
964
  {
456
965
  status: 400
457
966
  }
458
967
  );
459
- apply(response2, [cleared], config);
968
+ applyCookies(response2, [cleared], config);
460
969
  return response2;
461
970
  }
462
971
  const back = new URL(transaction.returnTo, config.appUrl);
463
972
  const code = params.get("code");
464
973
  if (!code) {
465
- const response2 = import_server.NextResponse.redirect(back);
466
- apply(response2, [cleared], config);
974
+ const response2 = import_server2.NextResponse.redirect(back);
975
+ applyCookies(response2, [cleared], config);
467
976
  return response2;
468
977
  }
469
978
  const session = await exchangeCode(config, code, transaction.verifier);
@@ -474,17 +983,26 @@ async function callback(request2, config) {
474
983
  "The ID token's nonce does not match this sign-in."
475
984
  );
476
985
  }
477
- const response = import_server.NextResponse.redirect(back);
478
- apply(
986
+ const response = import_server2.NextResponse.redirect(back);
987
+ applyCookies(
479
988
  response,
480
989
  [cleared, ...await sessionWrites(session, request2.cookies, config)],
481
990
  config
482
991
  );
483
992
  return response;
484
993
  }
485
- async function signOut(request2, config) {
994
+ async function signOut(request2, config, client) {
486
995
  const session = await readSession(request2.cookies, config);
487
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);
488
1006
  let destination = landing;
489
1007
  if (session?.rt) {
490
1008
  await revoke(config, session.rt);
@@ -495,36 +1013,36 @@ async function signOut(request2, config) {
495
1013
  if (end_session_endpoint) {
496
1014
  const end = new URL(end_session_endpoint);
497
1015
  end.search = new URLSearchParams({
498
- client_id: config.clientId,
1016
+ client_id: clientId,
499
1017
  post_logout_redirect_uri: landing,
500
1018
  ...session?.it ? { id_token_hint: session.it } : {}
501
1019
  }).toString();
502
1020
  destination = end.toString();
503
1021
  }
504
- const response = import_server.NextResponse.redirect(destination);
505
- 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);
506
1024
  return response;
507
1025
  }
508
- async function pass(request2, config, protectedPath) {
1026
+ async function pass(request2, config, client, signInPath) {
509
1027
  let session = await readSession(request2.cookies, config);
510
1028
  let writes = [];
511
1029
  if (session && session.exp - nowSec() <= REFRESH_LEEWAY_SEC) {
512
- const refreshed = await tryRefresh(config, session);
1030
+ const refreshed = await tryRefresh(config, session, client);
513
1031
  session = refreshed;
514
1032
  writes = await sessionWrites(refreshed, request2.cookies, config);
515
1033
  }
516
- if (!session && protectedPath) {
517
- const signInUrl = new URL(config.routes.signIn, config.appUrl);
1034
+ if (!session && signInPath !== null) {
1035
+ const signInUrl = new URL(signInPath, config.appUrl);
518
1036
  signInUrl.searchParams.set(
519
1037
  "returnTo",
520
1038
  `${request2.nextUrl.pathname}${request2.nextUrl.search}`
521
1039
  );
522
- const response2 = import_server.NextResponse.redirect(signInUrl);
523
- apply(response2, writes, config);
1040
+ const response2 = import_server2.NextResponse.redirect(signInUrl);
1041
+ applyCookies(response2, writes, config);
524
1042
  return response2;
525
1043
  }
526
1044
  if (writes.length === 0) {
527
- return import_server.NextResponse.next();
1045
+ return import_server2.NextResponse.next();
528
1046
  }
529
1047
  for (const write of writes) {
530
1048
  if (write.maxAge === 0) {
@@ -533,28 +1051,32 @@ async function pass(request2, config, protectedPath) {
533
1051
  request2.cookies.set(write.name, write.value);
534
1052
  }
535
1053
  }
536
- const response = import_server.NextResponse.next({ request: { headers: request2.headers } });
537
- apply(response, writes, config);
1054
+ const response = import_server2.NextResponse.next({ request: { headers: request2.headers } });
1055
+ applyCookies(response, writes, config);
538
1056
  return response;
539
1057
  }
540
- async function tryRefresh(config, session) {
1058
+ async function tryRefresh(config, session, client) {
541
1059
  try {
542
- return await refreshSession(config, session);
1060
+ return session.via === "direct" ? await refreshDirectSession(config, session, client) : await refreshSession(config, session);
543
1061
  } catch (caught) {
1062
+ if (caught instanceof CanopyConfigError) {
1063
+ throw caught;
1064
+ }
544
1065
  if (caught instanceof CanopySessionError && caught.code === "connection_failed") {
545
1066
  return session.exp > nowSec() ? session : null;
546
1067
  }
547
1068
  return null;
548
1069
  }
549
1070
  }
550
- function apply(response, writes, config) {
551
- for (const write of writes) {
552
- response.cookies.set(
553
- write.name,
554
- write.value,
555
- cookieOptions(config, write.maxAge)
556
- );
557
- }
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];
558
1080
  }
559
1081
  function isProtected(pathname, protect) {
560
1082
  if (!protect) {
@@ -564,16 +1086,10 @@ function isProtected(pathname, protect) {
564
1086
  return protect(pathname);
565
1087
  }
566
1088
  return protect.some((prefix) => {
567
- const base = prefix.replace(/\/+$/, "");
1089
+ const base = withoutTrailingSlash(prefix);
568
1090
  return base === "" || pathname === base || pathname.startsWith(`${base}/`);
569
1091
  });
570
1092
  }
571
- function safeReturnTo(value) {
572
- if (!value || !value.startsWith("/") || value.startsWith("//") || value.startsWith("/\\")) {
573
- return "/";
574
- }
575
- return value;
576
- }
577
1093
  function nowSec() {
578
1094
  return Math.floor(Date.now() / 1e3);
579
1095
  }
@@ -603,17 +1119,20 @@ var auth = (0, import_react.cache)(
603
1119
  if (!session) {
604
1120
  return SIGNED_OUT;
605
1121
  }
1122
+ const verifier = verifierFor(config, audienceOf(config, session));
606
1123
  let claims;
607
1124
  try {
608
- claims = await verifierFor(config).verify(session.at);
1125
+ claims = await verifier.verify(session.at);
609
1126
  } catch {
610
1127
  return SIGNED_OUT;
611
1128
  }
612
- const idClaims = session.it ? decodeClaims(session.it) : null;
1129
+ if (session.via === "direct" && session.who.id !== claims.sub) {
1130
+ return SIGNED_OUT;
1131
+ }
613
1132
  return {
614
1133
  isSignedIn: true,
615
1134
  userId: claims.sub,
616
- user: idClaims ? userOf(idClaims) : { sub: claims.sub },
1135
+ user: displayedUser(session, claims.sub),
617
1136
  claims,
618
1137
  organization: {
619
1138
  orgId: claims.org_id ?? null,
@@ -648,13 +1167,29 @@ function fromList(list, overflow, permission) {
648
1167
  }
649
1168
  return overflow ? void 0 : false;
650
1169
  }
651
- function verifierFor(config) {
652
- 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}`;
653
1188
  let verifier = shared.verifiers.get(key);
654
1189
  if (!verifier) {
655
1190
  verifier = new import_node.TokenVerifier({
656
1191
  issuer: config.issuer,
657
- audience: config.clientId
1192
+ audience
658
1193
  });
659
1194
  shared.verifiers.set(key, verifier);
660
1195
  }
@@ -714,6 +1249,17 @@ function clientSession(auth2) {
714
1249
  organization: { ...auth2.organization }
715
1250
  };
716
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
+ }
717
1263
  // Annotate the CommonJS export names for ESM import in node:
718
1264
  0 && (module.exports = {
719
1265
  CanopyConfigError,
@@ -721,6 +1267,7 @@ function clientSession(auth2) {
721
1267
  DEFAULT_ROUTES,
722
1268
  auth,
723
1269
  canopyProxy,
724
- clientSession
1270
+ clientSession,
1271
+ signInFormProps
725
1272
  });
726
1273
  //# sourceMappingURL=index.cjs.map