@canopy-io/nextjs 0.0.0-stage → 0.0.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 ADDED
@@ -0,0 +1,726 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ CanopyConfigError: () => CanopyConfigError,
24
+ CanopySessionError: () => CanopySessionError,
25
+ DEFAULT_ROUTES: () => DEFAULT_ROUTES,
26
+ auth: () => auth,
27
+ canopyProxy: () => canopyProxy,
28
+ clientSession: () => clientSession
29
+ });
30
+ module.exports = __toCommonJS(index_exports);
31
+
32
+ // src/proxy.ts
33
+ var import_server = require("next/server");
34
+
35
+ // src/config.ts
36
+ var DEFAULT_ROUTES = {
37
+ signIn: "/auth/sign-in",
38
+ callback: "/auth/callback",
39
+ signOut: "/auth/sign-out"
40
+ };
41
+ var DEFAULT_SCOPES = ["openid", "profile", "email"];
42
+ var DEFAULT_SESSION_MAX_AGE_SEC = 180 * 24 * 60 * 60;
43
+ var MIN_SECRET_LENGTH = 32;
44
+ var CanopyConfigError = class extends Error {
45
+ name = "CanopyConfigError";
46
+ };
47
+ function resolveConfig(options = {}) {
48
+ const env = process.env;
49
+ const issuer = withoutTrailingSlash(
50
+ required(options.issuer ?? env["CANOPY_ISSUER"], "CANOPY_ISSUER")
51
+ );
52
+ const secret = required(
53
+ options.secret ?? env["CANOPY_SECRET"],
54
+ "CANOPY_SECRET"
55
+ );
56
+ if (secret.length < MIN_SECRET_LENGTH) {
57
+ throw new CanopyConfigError(
58
+ `CANOPY_SECRET must be at least ${MIN_SECRET_LENGTH} characters; generate one with \`openssl rand -base64 32\`.`
59
+ );
60
+ }
61
+ const apiKey = options.apiKey ?? env["CANOPY_API_KEY"];
62
+ return {
63
+ 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"
71
+ ),
72
+ secret,
73
+ appUrl: new URL(
74
+ required(options.appUrl ?? env["CANOPY_APP_URL"], "CANOPY_APP_URL")
75
+ ).origin,
76
+ apiKey: apiKey === "" ? void 0 : apiKey,
77
+ scopes: options.scopes ?? DEFAULT_SCOPES,
78
+ routes: { ...DEFAULT_ROUTES, ...options.routes },
79
+ afterSignOutPath: options.afterSignOutPath ?? "/",
80
+ sessionMaxAgeSec: options.sessionMaxAgeSec ?? DEFAULT_SESSION_MAX_AGE_SEC
81
+ };
82
+ }
83
+ function required(value, name) {
84
+ if (value === void 0 || value.trim() === "") {
85
+ throw new CanopyConfigError(`${name} is not set.`);
86
+ }
87
+ return value.trim();
88
+ }
89
+ function withoutTrailingSlash(value) {
90
+ return value.replace(/\/+$/, "");
91
+ }
92
+
93
+ // src/seal.ts
94
+ var VERSION = "v1";
95
+ var IV_BYTES = 12;
96
+ var keys = /* @__PURE__ */ new Map();
97
+ function keyFor(secret) {
98
+ let key = keys.get(secret);
99
+ if (!key) {
100
+ key = (async () => {
101
+ const material = await crypto.subtle.importKey(
102
+ "raw",
103
+ new TextEncoder().encode(secret),
104
+ "HKDF",
105
+ false,
106
+ ["deriveKey"]
107
+ );
108
+ return crypto.subtle.deriveKey(
109
+ {
110
+ name: "HKDF",
111
+ hash: "SHA-256",
112
+ salt: new Uint8Array(0),
113
+ info: new TextEncoder().encode("canopy-nextjs session cookie")
114
+ },
115
+ material,
116
+ { name: "AES-GCM", length: 256 },
117
+ false,
118
+ ["encrypt", "decrypt"]
119
+ );
120
+ })();
121
+ keys.set(secret, key);
122
+ }
123
+ return key;
124
+ }
125
+ async function seal(value, secret) {
126
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
127
+ const sealed = await crypto.subtle.encrypt(
128
+ { name: "AES-GCM", iv },
129
+ await keyFor(secret),
130
+ new TextEncoder().encode(JSON.stringify(value))
131
+ );
132
+ const bytes = new Uint8Array(IV_BYTES + sealed.byteLength);
133
+ bytes.set(iv, 0);
134
+ bytes.set(new Uint8Array(sealed), IV_BYTES);
135
+ return `${VERSION}.${toBase64Url(bytes)}`;
136
+ }
137
+ async function open(sealed, secret) {
138
+ const [version, body] = sealed.split(".");
139
+ if (version !== VERSION || !body) {
140
+ return null;
141
+ }
142
+ try {
143
+ const bytes = fromBase64Url(body);
144
+ const plain = await crypto.subtle.decrypt(
145
+ { name: "AES-GCM", iv: bytes.slice(0, IV_BYTES) },
146
+ await keyFor(secret),
147
+ bytes.slice(IV_BYTES)
148
+ );
149
+ return JSON.parse(new TextDecoder().decode(plain));
150
+ } catch {
151
+ return null;
152
+ }
153
+ }
154
+ function toBase64Url(bytes) {
155
+ let binary = "";
156
+ for (const byte of bytes) {
157
+ binary += String.fromCharCode(byte);
158
+ }
159
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
160
+ }
161
+ function fromBase64Url(value) {
162
+ const padded = value.replaceAll("-", "+").replaceAll("_", "/");
163
+ const binary = atob(padded.padEnd(Math.ceil(padded.length / 4) * 4, "="));
164
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
165
+ }
166
+
167
+ // src/oidc.ts
168
+ var CanopySessionError = class extends Error {
169
+ constructor(code, message) {
170
+ super(message);
171
+ this.code = code;
172
+ }
173
+ code;
174
+ name = "CanopySessionError";
175
+ };
176
+ var discoveries = /* @__PURE__ */ new Map();
177
+ function discover(config) {
178
+ let discovery = discoveries.get(config.issuer);
179
+ if (!discovery) {
180
+ discovery = (async () => {
181
+ const response = await request(
182
+ `${config.issuer}/.well-known/openid-configuration`,
183
+ {
184
+ headers: { accept: "application/json" }
185
+ }
186
+ );
187
+ if (!response.ok) {
188
+ throw new CanopySessionError(
189
+ "discovery_failed",
190
+ `Canopy's discovery document answered ${response.status}.`
191
+ );
192
+ }
193
+ return await response.json();
194
+ })();
195
+ discovery.catch(() => discoveries.delete(config.issuer));
196
+ discoveries.set(config.issuer, discovery);
197
+ }
198
+ return discovery;
199
+ }
200
+ function randomToken(bytes = 32) {
201
+ return toBase64Url(crypto.getRandomValues(new Uint8Array(bytes)));
202
+ }
203
+ async function codeChallenge(verifier) {
204
+ const digest = await crypto.subtle.digest(
205
+ "SHA-256",
206
+ new TextEncoder().encode(verifier)
207
+ );
208
+ return toBase64Url(new Uint8Array(digest));
209
+ }
210
+ function callbackUrl(config) {
211
+ return `${config.appUrl}${config.routes.callback}`;
212
+ }
213
+ async function exchangeCode(config, code, verifier) {
214
+ return tokenRequest(config, {
215
+ grant_type: "authorization_code",
216
+ code,
217
+ redirect_uri: callbackUrl(config),
218
+ code_verifier: verifier
219
+ });
220
+ }
221
+ var refreshes = /* @__PURE__ */ new Map();
222
+ function refreshSession(config, session) {
223
+ const refreshToken = session.rt;
224
+ if (!refreshToken) {
225
+ return Promise.reject(
226
+ new CanopySessionError(
227
+ "invalid_grant",
228
+ "The session has no refresh token."
229
+ )
230
+ );
231
+ }
232
+ let pending = refreshes.get(refreshToken);
233
+ if (!pending) {
234
+ pending = tokenRequest(config, {
235
+ grant_type: "refresh_token",
236
+ refresh_token: refreshToken
237
+ }).then((next) => ({
238
+ ...next,
239
+ // A refresh need not return a new ID token; sign-out still needs one.
240
+ ...next.it === void 0 && session.it !== void 0 ? { it: session.it } : {},
241
+ ...next.rt === void 0 ? { rt: refreshToken } : {}
242
+ }));
243
+ refreshes.set(refreshToken, pending);
244
+ pending.then(
245
+ () => refreshes.delete(refreshToken),
246
+ () => refreshes.delete(refreshToken)
247
+ );
248
+ }
249
+ return pending;
250
+ }
251
+ async function revoke(config, refreshToken) {
252
+ try {
253
+ const { revocation_endpoint } = await discover(config);
254
+ if (!revocation_endpoint) {
255
+ return;
256
+ }
257
+ await request(revocation_endpoint, {
258
+ method: "POST",
259
+ headers: { "content-type": "application/x-www-form-urlencoded" },
260
+ body: new URLSearchParams({
261
+ token: refreshToken,
262
+ token_type_hint: "refresh_token",
263
+ client_id: config.clientId,
264
+ client_secret: config.clientSecret
265
+ })
266
+ });
267
+ } catch {
268
+ }
269
+ }
270
+ function decodeClaims(token) {
271
+ const payload = token.split(".")[1];
272
+ if (!payload) {
273
+ return null;
274
+ }
275
+ try {
276
+ const padded = payload.replaceAll("-", "+").replaceAll("_", "/");
277
+ const json = atob(padded.padEnd(Math.ceil(padded.length / 4) * 4, "="));
278
+ const bytes = Uint8Array.from(json, (char) => char.charCodeAt(0));
279
+ return JSON.parse(new TextDecoder().decode(bytes));
280
+ } catch {
281
+ return null;
282
+ }
283
+ }
284
+ async function tokenRequest(config, params) {
285
+ const { token_endpoint } = await discover(config);
286
+ const response = await request(token_endpoint, {
287
+ method: "POST",
288
+ headers: {
289
+ "content-type": "application/x-www-form-urlencoded",
290
+ accept: "application/json"
291
+ },
292
+ body: new URLSearchParams({
293
+ ...params,
294
+ client_id: config.clientId,
295
+ client_secret: config.clientSecret
296
+ })
297
+ });
298
+ const body = await response.json().catch(() => null);
299
+ if (!response.ok || !body?.access_token) {
300
+ throw new CanopySessionError(
301
+ body?.error ?? "token_request_failed",
302
+ body?.error_description ?? `Canopy's token endpoint answered ${response.status}.`
303
+ );
304
+ }
305
+ return {
306
+ at: body.access_token,
307
+ ...body.refresh_token ? { rt: body.refresh_token } : {},
308
+ ...body.id_token ? { it: body.id_token } : {},
309
+ exp: expiryOf(body)
310
+ };
311
+ }
312
+ function expiryOf(body) {
313
+ const exp = decodeClaims(body.access_token)?.["exp"];
314
+ if (typeof exp === "number") {
315
+ return exp;
316
+ }
317
+ return Math.floor(Date.now() / 1e3) + (body.expires_in ?? 0);
318
+ }
319
+ async function request(url, init) {
320
+ try {
321
+ return await fetch(url, { ...init, cache: "no-store" });
322
+ } catch (caught) {
323
+ throw new CanopySessionError(
324
+ "connection_failed",
325
+ `Canopy could not be reached: ${caught instanceof Error ? caught.message : String(caught)}`
326
+ );
327
+ }
328
+ }
329
+
330
+ // src/session.ts
331
+ var SESSION_COOKIE = "canopy_session";
332
+ var TRANSACTION_COOKIE = "canopy_tx";
333
+ var CHUNK_SIZE = 3800;
334
+ var TRANSACTION_MAX_AGE_SEC = 10 * 60;
335
+ async function readSession(cookies2, config) {
336
+ const chunks = cookies2.getAll().map(({ name, value }) => ({ index: chunkIndex(name), value })).filter(
337
+ (chunk) => chunk.index !== null
338
+ ).sort((a, b) => a.index - b.index);
339
+ if (chunks.length === 0) {
340
+ return null;
341
+ }
342
+ const session = await open(
343
+ chunks.map((chunk) => chunk.value).join(""),
344
+ config.secret
345
+ );
346
+ return session && typeof session.at === "string" && typeof session.exp === "number" ? session : null;
347
+ }
348
+ async function sessionWrites(session, existing, config) {
349
+ const held = existing.getAll().map(({ name }) => chunkIndex(name)).filter((index) => index !== null);
350
+ const writes = [];
351
+ let count = 0;
352
+ if (session) {
353
+ const sealed = await seal(session, config.secret);
354
+ for (let start = 0; start < sealed.length; start += CHUNK_SIZE) {
355
+ writes.push({
356
+ name: `${SESSION_COOKIE}.${count}`,
357
+ value: sealed.slice(start, start + CHUNK_SIZE),
358
+ maxAge: config.sessionMaxAgeSec
359
+ });
360
+ count += 1;
361
+ }
362
+ }
363
+ for (const index of held) {
364
+ if (index >= count) {
365
+ writes.push({ name: `${SESSION_COOKIE}.${index}`, value: "", maxAge: 0 });
366
+ }
367
+ }
368
+ return writes;
369
+ }
370
+ async function transactionWrite(transaction, config) {
371
+ return {
372
+ name: TRANSACTION_COOKIE,
373
+ value: await seal(transaction, config.secret),
374
+ maxAge: TRANSACTION_MAX_AGE_SEC
375
+ };
376
+ }
377
+ async function readTransaction(value, config) {
378
+ return value ? open(value, config.secret) : null;
379
+ }
380
+ function cookieOptions(config, maxAge) {
381
+ return {
382
+ httpOnly: true,
383
+ sameSite: "lax",
384
+ secure: config.appUrl.startsWith("https:"),
385
+ path: "/",
386
+ maxAge
387
+ };
388
+ }
389
+ function chunkIndex(name) {
390
+ const prefix = `${SESSION_COOKIE}.`;
391
+ if (!name.startsWith(prefix)) {
392
+ return null;
393
+ }
394
+ const index = Number(name.slice(prefix.length));
395
+ return Number.isInteger(index) && index >= 0 ? index : null;
396
+ }
397
+
398
+ // src/proxy.ts
399
+ var REFRESH_LEEWAY_SEC = 60;
400
+ function canopyProxy(options = {}) {
401
+ let config;
402
+ return async (request2) => {
403
+ config ??= resolveConfig(options);
404
+ const { pathname } = request2.nextUrl;
405
+ if (pathname === config.routes.signIn) {
406
+ return signIn(request2, config);
407
+ }
408
+ if (pathname === config.routes.callback) {
409
+ return callback(request2, config);
410
+ }
411
+ if (pathname === config.routes.signOut) {
412
+ return signOut(request2, config);
413
+ }
414
+ return pass(request2, config, isProtected(pathname, options.protect));
415
+ };
416
+ }
417
+ async function signIn(request2, config) {
418
+ const returnTo = safeReturnTo(request2.nextUrl.searchParams.get("returnTo"));
419
+ const transaction = {
420
+ state: randomToken(),
421
+ verifier: randomToken(),
422
+ nonce: randomToken(),
423
+ returnTo
424
+ };
425
+ const { authorization_endpoint } = await discover(config);
426
+ const authorize = new URL(authorization_endpoint);
427
+ authorize.search = new URLSearchParams({
428
+ response_type: "code",
429
+ client_id: config.clientId,
430
+ redirect_uri: callbackUrl(config),
431
+ scope: config.scopes.join(" "),
432
+ state: transaction.state,
433
+ nonce: transaction.nonce,
434
+ code_challenge: await codeChallenge(transaction.verifier),
435
+ code_challenge_method: "S256"
436
+ }).toString();
437
+ const response = import_server.NextResponse.redirect(authorize);
438
+ apply(response, [await transactionWrite(transaction, config)], config);
439
+ return response;
440
+ }
441
+ async function callback(request2, config) {
442
+ const params = request2.nextUrl.searchParams;
443
+ const transaction = await readTransaction(
444
+ request2.cookies.get(TRANSACTION_COOKIE)?.value,
445
+ config
446
+ );
447
+ const cleared = {
448
+ name: TRANSACTION_COOKIE,
449
+ value: "",
450
+ maxAge: 0
451
+ };
452
+ if (!transaction || params.get("state") !== transaction.state) {
453
+ const response2 = new import_server.NextResponse(
454
+ "This sign-in has expired. Start it again.",
455
+ {
456
+ status: 400
457
+ }
458
+ );
459
+ apply(response2, [cleared], config);
460
+ return response2;
461
+ }
462
+ const back = new URL(transaction.returnTo, config.appUrl);
463
+ const code = params.get("code");
464
+ if (!code) {
465
+ const response2 = import_server.NextResponse.redirect(back);
466
+ apply(response2, [cleared], config);
467
+ return response2;
468
+ }
469
+ const session = await exchangeCode(config, code, transaction.verifier);
470
+ const idClaims = session.it ? decodeClaims(session.it) : null;
471
+ if (session.it && idClaims?.["nonce"] !== transaction.nonce) {
472
+ throw new CanopySessionError(
473
+ "invalid_nonce",
474
+ "The ID token's nonce does not match this sign-in."
475
+ );
476
+ }
477
+ const response = import_server.NextResponse.redirect(back);
478
+ apply(
479
+ response,
480
+ [cleared, ...await sessionWrites(session, request2.cookies, config)],
481
+ config
482
+ );
483
+ return response;
484
+ }
485
+ async function signOut(request2, config) {
486
+ const session = await readSession(request2.cookies, config);
487
+ const landing = `${config.appUrl}${config.afterSignOutPath}`;
488
+ let destination = landing;
489
+ if (session?.rt) {
490
+ await revoke(config, session.rt);
491
+ }
492
+ const { end_session_endpoint } = await discover(config).catch(() => ({
493
+ end_session_endpoint: void 0
494
+ }));
495
+ if (end_session_endpoint) {
496
+ const end = new URL(end_session_endpoint);
497
+ end.search = new URLSearchParams({
498
+ client_id: config.clientId,
499
+ post_logout_redirect_uri: landing,
500
+ ...session?.it ? { id_token_hint: session.it } : {}
501
+ }).toString();
502
+ destination = end.toString();
503
+ }
504
+ const response = import_server.NextResponse.redirect(destination);
505
+ apply(response, await sessionWrites(null, request2.cookies, config), config);
506
+ return response;
507
+ }
508
+ async function pass(request2, config, protectedPath) {
509
+ let session = await readSession(request2.cookies, config);
510
+ let writes = [];
511
+ if (session && session.exp - nowSec() <= REFRESH_LEEWAY_SEC) {
512
+ const refreshed = await tryRefresh(config, session);
513
+ session = refreshed;
514
+ writes = await sessionWrites(refreshed, request2.cookies, config);
515
+ }
516
+ if (!session && protectedPath) {
517
+ const signInUrl = new URL(config.routes.signIn, config.appUrl);
518
+ signInUrl.searchParams.set(
519
+ "returnTo",
520
+ `${request2.nextUrl.pathname}${request2.nextUrl.search}`
521
+ );
522
+ const response2 = import_server.NextResponse.redirect(signInUrl);
523
+ apply(response2, writes, config);
524
+ return response2;
525
+ }
526
+ if (writes.length === 0) {
527
+ return import_server.NextResponse.next();
528
+ }
529
+ for (const write of writes) {
530
+ if (write.maxAge === 0) {
531
+ request2.cookies.delete(write.name);
532
+ } else {
533
+ request2.cookies.set(write.name, write.value);
534
+ }
535
+ }
536
+ const response = import_server.NextResponse.next({ request: { headers: request2.headers } });
537
+ apply(response, writes, config);
538
+ return response;
539
+ }
540
+ async function tryRefresh(config, session) {
541
+ try {
542
+ return await refreshSession(config, session);
543
+ } catch (caught) {
544
+ if (caught instanceof CanopySessionError && caught.code === "connection_failed") {
545
+ return session.exp > nowSec() ? session : null;
546
+ }
547
+ return null;
548
+ }
549
+ }
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
+ }
558
+ }
559
+ function isProtected(pathname, protect) {
560
+ if (!protect) {
561
+ return false;
562
+ }
563
+ if (typeof protect === "function") {
564
+ return protect(pathname);
565
+ }
566
+ return protect.some((prefix) => {
567
+ const base = prefix.replace(/\/+$/, "");
568
+ return base === "" || pathname === base || pathname.startsWith(`${base}/`);
569
+ });
570
+ }
571
+ function safeReturnTo(value) {
572
+ if (!value || !value.startsWith("/") || value.startsWith("//") || value.startsWith("/\\")) {
573
+ return "/";
574
+ }
575
+ return value;
576
+ }
577
+ function nowSec() {
578
+ return Math.floor(Date.now() / 1e3);
579
+ }
580
+
581
+ // src/auth.ts
582
+ var import_node = require("@canopy-io/node");
583
+ var import_headers = require("next/headers");
584
+ var import_react = require("react");
585
+ var SIGNED_OUT = {
586
+ isSignedIn: false,
587
+ userId: null,
588
+ user: null,
589
+ claims: null,
590
+ organization: { orgId: null, orgRoles: [], orgScope: null },
591
+ accessToken: null,
592
+ can: () => Promise.resolve(false)
593
+ };
594
+ var SHARED_KEY = /* @__PURE__ */ Symbol.for("@canopy-io/nextjs.shared");
595
+ var shared = globalThis[SHARED_KEY] ??= {
596
+ verifiers: /* @__PURE__ */ new Map(),
597
+ authorizers: /* @__PURE__ */ new Map()
598
+ };
599
+ var auth = (0, import_react.cache)(
600
+ async (options) => {
601
+ const config = resolveConfig(options);
602
+ const session = await readSession(await (0, import_headers.cookies)(), config);
603
+ if (!session) {
604
+ return SIGNED_OUT;
605
+ }
606
+ let claims;
607
+ try {
608
+ claims = await verifierFor(config).verify(session.at);
609
+ } catch {
610
+ return SIGNED_OUT;
611
+ }
612
+ const idClaims = session.it ? decodeClaims(session.it) : null;
613
+ return {
614
+ isSignedIn: true,
615
+ userId: claims.sub,
616
+ user: idClaims ? userOf(idClaims) : { sub: claims.sub },
617
+ claims,
618
+ organization: {
619
+ orgId: claims.org_id ?? null,
620
+ orgRoles: claims.org_roles ?? [],
621
+ orgScope: claims.org_scope === "all" ? "all" : null
622
+ },
623
+ accessToken: session.at,
624
+ can: (permission, checkOptions = {}) => can(config, claims, permission, checkOptions.nodeId)
625
+ };
626
+ }
627
+ );
628
+ async function can(config, claims, permission, nodeId) {
629
+ const fromToken = nodeId === void 0 ? fromList(claims.permissions, claims.permissions_overflow, permission) : nodeId === claims.org_id ? fromList(
630
+ claims["org_permissions"],
631
+ claims["org_permissions_overflow"],
632
+ permission
633
+ ) : void 0;
634
+ if (fromToken !== void 0) {
635
+ return fromToken;
636
+ }
637
+ const decision = await authorizerFor(config).evaluate(
638
+ nodeId === void 0 ? { identity_id: claims.sub, permission, scope: "app_wide" } : { identity_id: claims.sub, permission, node_id: nodeId }
639
+ );
640
+ return decision.allowed;
641
+ }
642
+ function fromList(list, overflow, permission) {
643
+ if (!Array.isArray(list)) {
644
+ return void 0;
645
+ }
646
+ if (list.includes(permission)) {
647
+ return true;
648
+ }
649
+ return overflow ? void 0 : false;
650
+ }
651
+ function verifierFor(config) {
652
+ const key = `${config.issuer}\0${config.clientId}`;
653
+ let verifier = shared.verifiers.get(key);
654
+ if (!verifier) {
655
+ verifier = new import_node.TokenVerifier({
656
+ issuer: config.issuer,
657
+ audience: config.clientId
658
+ });
659
+ shared.verifiers.set(key, verifier);
660
+ }
661
+ return verifier;
662
+ }
663
+ function authorizerFor(config) {
664
+ if (!config.apiKey) {
665
+ throw new CanopyConfigError(
666
+ "CANOPY_API_KEY is not set. A permission check the access token cannot answer (one at a node) reads the identity's grants with a secret API key."
667
+ );
668
+ }
669
+ let authorizer = shared.authorizers.get(config.apiKey);
670
+ if (!authorizer) {
671
+ authorizer = new import_node.LocalAuthorizer(
672
+ new import_node.CanopyClient({ apiKey: config.apiKey })
673
+ );
674
+ shared.authorizers.set(config.apiKey, authorizer);
675
+ }
676
+ return authorizer;
677
+ }
678
+ var ID_TOKEN_PROTOCOL_CLAIMS = /* @__PURE__ */ new Set([
679
+ "iss",
680
+ "aud",
681
+ "exp",
682
+ "iat",
683
+ "nbf",
684
+ "nonce",
685
+ "auth_time",
686
+ "at_hash",
687
+ "c_hash",
688
+ "sid",
689
+ "azp",
690
+ "jti"
691
+ ]);
692
+ function userOf(idClaims) {
693
+ const user = {};
694
+ for (const [claim, value] of Object.entries(idClaims)) {
695
+ if (!ID_TOKEN_PROTOCOL_CLAIMS.has(claim)) {
696
+ user[claim] = value;
697
+ }
698
+ }
699
+ return user;
700
+ }
701
+
702
+ // src/client-session.ts
703
+ function clientSession(auth2) {
704
+ const { user } = auth2;
705
+ return {
706
+ isSignedIn: auth2.isSignedIn,
707
+ userId: auth2.userId,
708
+ user: user ? {
709
+ sub: user.sub,
710
+ ...typeof user.name === "string" ? { name: user.name } : {},
711
+ ...typeof user.email === "string" ? { email: user.email } : {},
712
+ ...typeof user.picture === "string" ? { picture: user.picture } : {}
713
+ } : null,
714
+ organization: { ...auth2.organization }
715
+ };
716
+ }
717
+ // Annotate the CommonJS export names for ESM import in node:
718
+ 0 && (module.exports = {
719
+ CanopyConfigError,
720
+ CanopySessionError,
721
+ DEFAULT_ROUTES,
722
+ auth,
723
+ canopyProxy,
724
+ clientSession
725
+ });
726
+ //# sourceMappingURL=index.cjs.map