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