@geekapps/auth-nextjs 0.11.0 → 0.13.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.
@@ -1,10 +1,802 @@
1
+ // src/connections.ts
2
+ import { createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
3
+ import { cookies as cookies2 } from "next/headers";
4
+ import { redirect as redirect2 } from "next/navigation";
5
+
1
6
  // src/server.ts
2
7
  import { createHash, randomBytes } from "crypto";
3
8
  import { cookies, headers } from "next/headers";
4
9
  import { redirect } from "next/navigation";
5
10
  import { NextResponse } from "next/server";
6
11
  import { createRemoteJWKSet, jwtVerify } from "jose";
12
+ var GeekappsSessionExpiredError = class extends Error {
13
+ code = "session_expired";
14
+ constructor(message = "A sess\xE3o expirou ou foi revogada. Entre novamente.") {
15
+ super(message);
16
+ this.name = "GeekappsSessionExpiredError";
17
+ }
18
+ };
7
19
  var GEEKAPPS_AUTH_SERVER_URL = "https://accounts-api.geekapps.com.br";
20
+ var MAX_ACCOUNTS = 8;
21
+ function normalizeBaseUrl(url) {
22
+ return url.replace(/\/$/, "");
23
+ }
24
+ function normalizeBasePath(path = "/api/auth") {
25
+ if (!path.startsWith("/")) return `/${path}`;
26
+ return path.replace(/\/$/, "");
27
+ }
28
+ function createUrl(baseUrl, path) {
29
+ if (/^https?:\/\//.test(path)) return path;
30
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
31
+ return `${normalizeBaseUrl(baseUrl)}${normalizedPath}`;
32
+ }
33
+ function env(name) {
34
+ const value = process.env[name];
35
+ return value && value.trim().length > 0 ? value : void 0;
36
+ }
37
+ function resolveIssuer(input) {
38
+ return normalizeBaseUrl(
39
+ input.issuer ?? env("GEEKAPPS_AUTH_SERVER_ISSUER") ?? env("GEEKAPPS_AUTH_SERVER_URL") ?? // Deprecated: kept for backwards compatibility during the auth-server rename.
40
+ env("GEEKAPPS_AUTH_ISSUER") ?? env("GEEKAPPS_AUTH_API_URL") ?? GEEKAPPS_AUTH_SERVER_URL
41
+ );
42
+ }
43
+ function resolveClientId(input) {
44
+ return input.clientId ?? env("GEEKAPPS_AUTH_CLIENT_ID") ?? "";
45
+ }
46
+ function resolveClientSecret(input) {
47
+ return input.clientSecret ?? env("GEEKAPPS_AUTH_CLIENT_SECRET");
48
+ }
49
+ function applyClientCredentials(url, config) {
50
+ if (!config.clientId || !config.clientSecret) return;
51
+ url.searchParams.set("client_id", config.clientId);
52
+ url.searchParams.set("client_secret", config.clientSecret);
53
+ }
54
+ function resolveConfiguredRedirectUri(input) {
55
+ return input.redirectUri ?? env("GEEKAPPS_AUTH_REDIRECT_URI");
56
+ }
57
+ function hashClientId(clientId) {
58
+ let h = 5381;
59
+ for (let i = 0; i < clientId.length; i++) {
60
+ h = (h << 5) + h ^ clientId.charCodeAt(i) & 255;
61
+ h = h >>> 0;
62
+ }
63
+ return h.toString(16).padStart(8, "0");
64
+ }
65
+ function deriveCookiePrefix(clientId) {
66
+ if (!clientId) return "gk";
67
+ return `gk_${hashClientId(clientId)}`;
68
+ }
69
+ function requestOrigin(request) {
70
+ const configured = env("GEEKAPPS_APP_URL");
71
+ if (configured) return configured.replace(/\/$/, "");
72
+ if (request.nextUrl?.origin) return request.nextUrl.origin;
73
+ throw new Error(
74
+ "Cannot determine app origin. Set GEEKAPPS_APP_URL or ensure request.nextUrl is available."
75
+ );
76
+ }
77
+ function resolveRedirectUri(config, request) {
78
+ return config.redirectUri ?? `${requestOrigin(request)}${config.basePath}/callback`;
79
+ }
80
+ function tokenFromResponse(data) {
81
+ return {
82
+ accessToken: data.accessToken ?? data.access_token ?? data.tokens?.accessToken ?? data.tokens?.access_token ?? null,
83
+ refreshToken: data.refreshToken ?? data.refresh_token ?? data.tokens?.refreshToken ?? data.tokens?.refresh_token ?? null,
84
+ idToken: data.idToken ?? data.id_token ?? data.tokens?.idToken ?? data.tokens?.id_token ?? null,
85
+ sessionId: data.sessionId ?? data.session_id ?? data.tokens?.sessionId ?? data.tokens?.session_id ?? null
86
+ };
87
+ }
88
+ function decodeJwtPayload(token) {
89
+ try {
90
+ const parts = token.split(".");
91
+ if (parts.length < 2) return null;
92
+ const payload = parts[1];
93
+ if (!payload) return null;
94
+ return JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
95
+ } catch {
96
+ return null;
97
+ }
98
+ }
99
+ function parseAccountFromJwt(tokens) {
100
+ if (!tokens.accessToken) return null;
101
+ const jwtToParse = tokens.idToken ?? tokens.accessToken;
102
+ const payload = decodeJwtPayload(jwtToParse);
103
+ if (!payload) return null;
104
+ const sub = typeof payload.sub === "string" ? payload.sub : null;
105
+ const id = sub ?? tokens.sessionId;
106
+ if (!id) return null;
107
+ return {
108
+ id,
109
+ accessToken: tokens.accessToken,
110
+ refreshToken: tokens.refreshToken,
111
+ idToken: tokens.idToken ?? null,
112
+ sessionId: tokens.sessionId,
113
+ user: {
114
+ sub: id,
115
+ name: typeof payload.name === "string" ? payload.name : null,
116
+ email: typeof payload.email === "string" ? payload.email : null,
117
+ picture: typeof payload.picture === "string" ? payload.picture : null,
118
+ phone: typeof payload.phone_number === "string" ? payload.phone_number : null
119
+ }
120
+ };
121
+ }
122
+ function getCookieNames(prefix) {
123
+ return {
124
+ active: `${prefix}_active`,
125
+ count: `${prefix}_count`,
126
+ activeOrganizationId: `${prefix}_ao`,
127
+ tokenPub: `${prefix}_tp`,
128
+ pkceVerifier: `${prefix}_pkce`,
129
+ slotMeta: (n) => `${prefix}_m${n}`,
130
+ slotAt: (n) => `${prefix}_at${n}`,
131
+ slotRt: (n) => `${prefix}_rt${n}`
132
+ };
133
+ }
134
+ function generateCodeVerifier() {
135
+ return randomBytes(64).toString("base64url");
136
+ }
137
+ function createCodeChallenge(codeVerifier) {
138
+ return createHash("sha256").update(codeVerifier).digest("base64url");
139
+ }
140
+ function encodeMeta(account) {
141
+ const m = { id: account.id };
142
+ if (account.sessionId) m.sid = account.sessionId;
143
+ if (account.user.name) m.n = account.user.name;
144
+ if (account.user.email) m.e = account.user.email;
145
+ if (account.user.picture) m.p = account.user.picture;
146
+ return Buffer.from(JSON.stringify(m), "utf8").toString("base64url");
147
+ }
148
+ function decodeMeta(value) {
149
+ try {
150
+ const m = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
151
+ return m.id ? m : null;
152
+ } catch {
153
+ return null;
154
+ }
155
+ }
156
+ function getCookieOptions(config) {
157
+ return {
158
+ httpOnly: true,
159
+ secure: config.secureCookies ?? process.env.NODE_ENV === "production",
160
+ sameSite: "lax",
161
+ path: "/"
162
+ };
163
+ }
164
+ async function readBody(request) {
165
+ const text = await request.text();
166
+ if (!text) return void 0;
167
+ try {
168
+ return JSON.parse(text);
169
+ } catch {
170
+ return text;
171
+ }
172
+ }
173
+ function appendSearchParams(url, request) {
174
+ const target = new URL(url);
175
+ request.nextUrl.searchParams.forEach((value, key) => {
176
+ target.searchParams.set(key, value);
177
+ });
178
+ return target.toString();
179
+ }
180
+ function routeFromRequest(request, basePath) {
181
+ const pathname = request.nextUrl.pathname;
182
+ if (!pathname.startsWith(basePath)) return pathname;
183
+ const route = pathname.slice(basePath.length);
184
+ return route || "/";
185
+ }
186
+ function isJsonResponse(response) {
187
+ return response.headers.get("content-type")?.includes("application/json");
188
+ }
189
+ async function responseFromApi(response) {
190
+ if (response.status === 204) return new NextResponse(null, { status: 204 });
191
+ const body = isJsonResponse(response) ? await response.json().catch(() => null) : await response.text();
192
+ return NextResponse.json(body, { status: response.status });
193
+ }
194
+ var _remoteJWKSCache = /* @__PURE__ */ new Map();
195
+ function getRemoteJWKS(issuer) {
196
+ if (!_remoteJWKSCache.has(issuer)) {
197
+ _remoteJWKSCache.set(issuer, createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`)));
198
+ }
199
+ return _remoteJWKSCache.get(issuer);
200
+ }
201
+ async function verifyToken(token, issuer) {
202
+ try {
203
+ const { payload } = await jwtVerify(token, getRemoteJWKS(issuer), {
204
+ algorithms: ["RS256"],
205
+ issuer
206
+ });
207
+ return payload;
208
+ } catch {
209
+ return null;
210
+ }
211
+ }
212
+ function configureGeekappsAuth(input = {}) {
213
+ const clientId = resolveClientId(input);
214
+ const config = {
215
+ ...input,
216
+ issuer: resolveIssuer(input),
217
+ clientId,
218
+ clientSecret: resolveClientSecret(input),
219
+ redirectUri: resolveConfiguredRedirectUri(input),
220
+ afterSignInRedirectTo: input.afterSignInRedirectTo ?? input.redirectTo ?? "/",
221
+ basePath: normalizeBasePath(input.basePath),
222
+ cookiePrefix: deriveCookiePrefix(clientId)
223
+ };
224
+ const cn = getCookieNames(config.cookiePrefix);
225
+ async function getCount() {
226
+ const cookieStore = await cookies();
227
+ const raw = cookieStore.get(cn.count)?.value;
228
+ const n = raw ? Number.parseInt(raw, 10) : 0;
229
+ return Number.isNaN(n) ? 0 : n;
230
+ }
231
+ async function getActiveIndex() {
232
+ const cookieStore = await cookies();
233
+ const raw = cookieStore.get(cn.active)?.value;
234
+ if (!raw) return 0;
235
+ const n = Number.parseInt(raw, 10);
236
+ return Number.isNaN(n) ? 0 : n;
237
+ }
238
+ function readSlot(cookieStore, n) {
239
+ const at = cookieStore.get(cn.slotAt(n))?.value;
240
+ if (!at) return null;
241
+ const meta = decodeMeta(cookieStore.get(cn.slotMeta(n))?.value ?? "");
242
+ if (!meta) return null;
243
+ return {
244
+ id: meta.id,
245
+ accessToken: at,
246
+ refreshToken: cookieStore.get(cn.slotRt(n))?.value ?? null,
247
+ idToken: null,
248
+ // not stored in cookies; claims are in meta
249
+ sessionId: meta.sid ?? null,
250
+ user: {
251
+ sub: meta.id,
252
+ name: meta.n ?? null,
253
+ email: meta.e ?? null,
254
+ picture: meta.p ?? null
255
+ }
256
+ };
257
+ }
258
+ function writeSlot(cookieStore, n, account) {
259
+ const opts = { ...getCookieOptions(config), maxAge: 60 * 60 * 24 * 30 };
260
+ cookieStore.set(cn.slotMeta(n), encodeMeta(account), opts);
261
+ cookieStore.set(cn.slotAt(n), account.accessToken, opts);
262
+ if (account.refreshToken) cookieStore.set(cn.slotRt(n), account.refreshToken, opts);
263
+ }
264
+ function clearSlot(cookieStore, n) {
265
+ const clear = { ...getCookieOptions(config), maxAge: 0 };
266
+ cookieStore.set(cn.slotMeta(n), "", clear);
267
+ cookieStore.set(cn.slotAt(n), "", clear);
268
+ cookieStore.set(cn.slotRt(n), "", clear);
269
+ }
270
+ async function getAccountsList() {
271
+ const [cookieStore, count] = await Promise.all([cookies(), getCount()]);
272
+ const accounts = [];
273
+ for (let i = 1; i <= count; i++) {
274
+ const slot = readSlot(cookieStore, i);
275
+ if (slot) accounts.push(slot);
276
+ }
277
+ return accounts;
278
+ }
279
+ async function getActiveAccount() {
280
+ const [cookieStore, activeIdx, count] = await Promise.all([cookies(), getActiveIndex(), getCount()]);
281
+ if (count === 0) return null;
282
+ if (activeIdx >= 1 && activeIdx <= count) {
283
+ const slot = readSlot(cookieStore, activeIdx);
284
+ if (slot) return slot;
285
+ }
286
+ return readSlot(cookieStore, 1);
287
+ }
288
+ async function getAccessToken() {
289
+ try {
290
+ const hdrs = await headers();
291
+ const auth = hdrs.get("authorization");
292
+ if (auth?.startsWith("Bearer ")) return auth.slice(7);
293
+ } catch {
294
+ }
295
+ const active = await getActiveAccount();
296
+ return active?.accessToken ?? null;
297
+ }
298
+ async function getRefreshToken() {
299
+ const active = await getActiveAccount();
300
+ return active?.refreshToken ?? null;
301
+ }
302
+ async function getSession() {
303
+ const active = await getActiveAccount();
304
+ if (!active) return null;
305
+ return {
306
+ accessToken: active.accessToken,
307
+ refreshToken: active.refreshToken,
308
+ idToken: active.idToken,
309
+ sessionId: active.sessionId
310
+ };
311
+ }
312
+ async function getUser() {
313
+ const active = await getActiveAccount();
314
+ return active?.user ?? null;
315
+ }
316
+ async function getUserById(userId, applicationId) {
317
+ const qs = new URLSearchParams({ ...applicationId ? { applicationId } : {} });
318
+ try {
319
+ return await apiRequest(`/users/${userId}?${qs}`);
320
+ } catch {
321
+ return null;
322
+ }
323
+ }
324
+ async function getOrganizations() {
325
+ const cookieStore = await cookies();
326
+ const currentOrgId = cookieStore.get(cn.activeOrganizationId)?.value ?? null;
327
+ try {
328
+ const data = await apiRequest("/organizations");
329
+ const organizations = Array.isArray(data) ? data : data.organizations;
330
+ return { organizations, currentOrgId };
331
+ } catch {
332
+ return { organizations: [], currentOrgId };
333
+ }
334
+ }
335
+ function clearPublicTokenCookie(cookieStore) {
336
+ if (cookieStore.get(cn.tokenPub)?.value) {
337
+ cookieStore.set(cn.tokenPub, "", { httpOnly: false, maxAge: 0, path: "/" });
338
+ }
339
+ }
340
+ async function saveAccountToList(tokens) {
341
+ const account = parseAccountFromJwt(tokens);
342
+ if (!account) return;
343
+ const cookieStore = await cookies();
344
+ const opts = { ...getCookieOptions(config), maxAge: 60 * 60 * 24 * 30 };
345
+ const count = await getCount();
346
+ let targetSlot = 0;
347
+ for (let i = 1; i <= count; i++) {
348
+ const existing = readSlot(cookieStore, i);
349
+ if (existing?.id === account.id) {
350
+ targetSlot = i;
351
+ break;
352
+ }
353
+ }
354
+ if (targetSlot === 0) {
355
+ if (count >= MAX_ACCOUNTS) return;
356
+ targetSlot = count + 1;
357
+ cookieStore.set(cn.count, String(targetSlot), opts);
358
+ }
359
+ writeSlot(cookieStore, targetSlot, account);
360
+ cookieStore.set(cn.active, String(targetSlot), opts);
361
+ clearPublicTokenCookie(cookieStore);
362
+ }
363
+ const setSessionCookies = saveAccountToList;
364
+ async function switchAccount(accountId) {
365
+ const [cookieStore, count] = await Promise.all([cookies(), getCount()]);
366
+ const opts = { ...getCookieOptions(config), maxAge: 60 * 60 * 24 * 30 };
367
+ for (let i = 1; i <= count; i++) {
368
+ const slot = readSlot(cookieStore, i);
369
+ if (slot && (slot.id === accountId || slot.sessionId === accountId)) {
370
+ cookieStore.set(cn.active, String(i), opts);
371
+ clearPublicTokenCookie(cookieStore);
372
+ return true;
373
+ }
374
+ }
375
+ return false;
376
+ }
377
+ async function removeActiveAccount() {
378
+ const [cookieStore, activeIdx, count] = await Promise.all([cookies(), getActiveIndex(), getCount()]);
379
+ const opts = { ...getCookieOptions(config), maxAge: 60 * 60 * 24 * 30 };
380
+ const clear = { ...getCookieOptions(config), maxAge: 0 };
381
+ if (count === 0) return;
382
+ const remaining = [];
383
+ for (let i = 1; i <= count; i++) {
384
+ if (i === activeIdx) continue;
385
+ const slot = readSlot(cookieStore, i);
386
+ if (slot) remaining.push(slot);
387
+ }
388
+ for (let i = 1; i <= count; i++) {
389
+ clearSlot(cookieStore, i);
390
+ }
391
+ if (remaining.length === 0) {
392
+ cookieStore.set(cn.count, "0", clear);
393
+ cookieStore.set(cn.active, "0", clear);
394
+ await clearPublicTokenCookie(cookieStore);
395
+ return;
396
+ }
397
+ for (let i = 0; i < remaining.length; i++) {
398
+ await writeSlot(cookieStore, i + 1, remaining[i]);
399
+ }
400
+ cookieStore.set(cn.count, String(remaining.length), opts);
401
+ cookieStore.set(cn.active, "1", opts);
402
+ clearPublicTokenCookie(cookieStore);
403
+ }
404
+ async function clearAllSessionCookies() {
405
+ const [cookieStore, count] = await Promise.all([cookies(), getCount()]);
406
+ const clear = { ...getCookieOptions(config), maxAge: 0 };
407
+ for (let i = 1; i <= count; i++) {
408
+ clearSlot(cookieStore, i);
409
+ }
410
+ cookieStore.set(cn.count, "0", clear);
411
+ cookieStore.set(cn.active, "0", clear);
412
+ clearPublicTokenCookie(cookieStore);
413
+ }
414
+ async function tryRefreshTokens() {
415
+ const refreshToken = await getRefreshToken();
416
+ if (!refreshToken || !config.clientId) return null;
417
+ const basicAuth = Buffer.from(`${config.clientId}:${config.clientSecret ?? ""}`).toString("base64");
418
+ const response = await fetch(createUrl(config.issuer, "/auth/token"), {
419
+ method: "POST",
420
+ headers: {
421
+ "content-type": "application/x-www-form-urlencoded",
422
+ authorization: `Basic ${basicAuth}`
423
+ },
424
+ body: new URLSearchParams({
425
+ grant_type: "refresh_token",
426
+ refresh_token: refreshToken
427
+ }),
428
+ cache: "no-store"
429
+ });
430
+ if (!response.ok) return null;
431
+ const data = await response.json().catch(() => null);
432
+ if (!data) return null;
433
+ const tokens = tokenFromResponse(data);
434
+ if (!tokens.accessToken) return null;
435
+ await saveAccountToList(tokens);
436
+ return tokens.accessToken;
437
+ }
438
+ async function apiRequest(path, init = {}) {
439
+ const accessToken = await getAccessToken();
440
+ const requestHeaders = new Headers(init.headers);
441
+ if (accessToken) requestHeaders.set("authorization", `Bearer ${accessToken}`);
442
+ if (init.body !== void 0 && !requestHeaders.has("content-type")) {
443
+ requestHeaders.set("content-type", "application/json");
444
+ }
445
+ const url = new URL(createUrl(config.issuer, path));
446
+ applyClientCredentials(url, config);
447
+ const response = await fetch(url, {
448
+ ...init,
449
+ headers: requestHeaders,
450
+ cache: "no-store"
451
+ });
452
+ if (response.status === 401) {
453
+ const newAccessToken = await tryRefreshTokens();
454
+ if (!newAccessToken) {
455
+ await clearAllSessionCookies().catch(() => {
456
+ });
457
+ throw new GeekappsSessionExpiredError();
458
+ }
459
+ if (newAccessToken) {
460
+ const retryHeaders = new Headers(init.headers);
461
+ retryHeaders.set("authorization", `Bearer ${newAccessToken}`);
462
+ if (init.body !== void 0 && !retryHeaders.has("content-type")) {
463
+ retryHeaders.set("content-type", "application/json");
464
+ }
465
+ const retryUrl = new URL(createUrl(config.issuer, path));
466
+ applyClientCredentials(retryUrl, config);
467
+ const retryResponse = await fetch(retryUrl, {
468
+ ...init,
469
+ headers: retryHeaders,
470
+ cache: "no-store"
471
+ });
472
+ if (!retryResponse.ok) {
473
+ const error = await retryResponse.json().catch(() => null);
474
+ throw new Error(error?.error_description ?? error?.error ?? error?.message ?? `Auth API error ${retryResponse.status}`);
475
+ }
476
+ if (retryResponse.status === 204) return null;
477
+ return await retryResponse.json();
478
+ }
479
+ }
480
+ if (!response.ok) {
481
+ const error = await response.json().catch(() => null);
482
+ throw new Error(error?.error_description ?? error?.error ?? error?.message ?? `Auth API error ${response.status}`);
483
+ }
484
+ if (response.status === 204) return null;
485
+ return await response.json();
486
+ }
487
+ function createApiClient() {
488
+ return {
489
+ get: (path) => apiRequest(path),
490
+ post: (path, body) => apiRequest(path, { method: "POST", body: body === void 0 ? void 0 : JSON.stringify(body) }),
491
+ patch: (path, body) => apiRequest(path, { method: "PATCH", body: body === void 0 ? void 0 : JSON.stringify(body) }),
492
+ put: (path, body) => apiRequest(path, { method: "PUT", body: body === void 0 ? void 0 : JSON.stringify(body) }),
493
+ delete: (path) => apiRequest(path, { method: "DELETE" })
494
+ };
495
+ }
496
+ async function requireUser(options = {}) {
497
+ const accessToken = await getAccessToken();
498
+ if (!accessToken) {
499
+ redirect(options.redirectTo ?? "/");
500
+ }
501
+ return accessToken;
502
+ }
503
+ function escapeHtml(str) {
504
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
505
+ }
506
+ function sanitizeRedirectTo(value) {
507
+ const raw = value ?? "/";
508
+ if (raw.startsWith(config.basePath)) return "/";
509
+ if (raw.startsWith("/") && !raw.startsWith("//")) return raw;
510
+ return "/";
511
+ }
512
+ async function createAuthorizeRedirect(request, mode) {
513
+ const redirectTo = sanitizeRedirectTo(request.nextUrl.searchParams.get("redirectTo") ?? config.afterSignInRedirectTo);
514
+ const flowId = request.nextUrl.searchParams.get("flow_id");
515
+ const url = new URL(createUrl(config.issuer, mode === "google" ? "/auth/google" : "/authorize"));
516
+ if (!config.clientId) {
517
+ return NextResponse.json(
518
+ { error: "missing_client_id", message: "Missing GEEKAPPS_AUTH_CLIENT_ID or clientId." },
519
+ { status: 500 }
520
+ );
521
+ }
522
+ url.searchParams.set("client_id", config.clientId);
523
+ url.searchParams.set("redirect_uri", resolveRedirectUri(config, request));
524
+ url.searchParams.set("response_type", "code");
525
+ const scopes = config.scopes ?? ["openid", "profile", "email"];
526
+ if (!scopes.includes("offline_access")) scopes.push("offline_access");
527
+ url.searchParams.set("scope", scopes.join(" "));
528
+ url.searchParams.set("state", Buffer.from(JSON.stringify({ redirectTo, mode })).toString("base64url"));
529
+ if (mode === "register") url.searchParams.set("screen_hint", "signup");
530
+ if (mode === "add-account") {
531
+ url.searchParams.set("prompt", "login");
532
+ } else {
533
+ const prompt = request.nextUrl.searchParams.get("prompt");
534
+ const silentLogin = request.nextUrl.searchParams.get("silentLogin");
535
+ const resolvedPrompt = prompt ?? (silentLogin === "false" ? "login" : null);
536
+ if (resolvedPrompt) url.searchParams.set("prompt", resolvedPrompt);
537
+ }
538
+ if (flowId) url.searchParams.set("flow_id", flowId);
539
+ const codeVerifier = generateCodeVerifier();
540
+ url.searchParams.set("code_challenge", createCodeChallenge(codeVerifier));
541
+ url.searchParams.set("code_challenge_method", "S256");
542
+ const response = NextResponse.redirect(url);
543
+ const cn2 = getCookieNames(config.cookiePrefix);
544
+ response.cookies.set(cn2.pkceVerifier, codeVerifier, {
545
+ ...getCookieOptions(config),
546
+ maxAge: 60 * 10
547
+ });
548
+ return response;
549
+ }
550
+ async function exchangeCode(request) {
551
+ const code = request.nextUrl.searchParams.get("code");
552
+ const state = request.nextUrl.searchParams.get("state");
553
+ const origin = requestOrigin(request);
554
+ if (!code) {
555
+ const err = request.nextUrl.searchParams.get("error") ?? "missing_code";
556
+ const desc = request.nextUrl.searchParams.get("error_description") ?? request.nextUrl.searchParams.get("error_message") ?? "No authorization code received";
557
+ return NextResponse.redirect(new URL(`${config.basePath}/callback?error=${encodeURIComponent(err)}&error_description=${encodeURIComponent(desc)}`, origin));
558
+ }
559
+ if (!config.clientId) {
560
+ return NextResponse.redirect(new URL(`${config.basePath}/callback?error=missing_client_id&error_description=Auth+client+is+not+configured`, origin));
561
+ }
562
+ const basicAuth = Buffer.from(
563
+ `${config.clientId}:${config.clientSecret ?? ""}`
564
+ ).toString("base64");
565
+ const cn2 = getCookieNames(config.cookiePrefix);
566
+ const cookieStore = await cookies();
567
+ const codeVerifier = cookieStore.get(cn2.pkceVerifier)?.value;
568
+ cookieStore.set(cn2.pkceVerifier, "", { ...getCookieOptions(config), maxAge: 0 });
569
+ const tokenBody = new URLSearchParams({
570
+ grant_type: "authorization_code",
571
+ code,
572
+ redirect_uri: resolveRedirectUri(config, request)
573
+ });
574
+ if (codeVerifier) tokenBody.set("code_verifier", codeVerifier);
575
+ const response = await fetch(createUrl(config.issuer, "/auth/token"), {
576
+ method: "POST",
577
+ headers: {
578
+ "content-type": "application/x-www-form-urlencoded",
579
+ authorization: `Basic ${basicAuth}`
580
+ },
581
+ body: tokenBody,
582
+ cache: "no-store"
583
+ });
584
+ const data = await response.json().catch(() => ({}));
585
+ if (!response.ok) {
586
+ const error = encodeURIComponent(data.error ?? "token_exchange_failed");
587
+ const desc = encodeURIComponent(data.error_description ?? `Token exchange failed with status ${response.status}`);
588
+ return NextResponse.redirect(new URL(`${config.basePath}/callback?error=${error}&error_description=${desc}`, origin));
589
+ }
590
+ await saveAccountToList(tokenFromResponse(data));
591
+ let redirectTo = sanitizeRedirectTo(config.afterSignInRedirectTo);
592
+ if (state) {
593
+ try {
594
+ const parsed = JSON.parse(Buffer.from(state, "base64url").toString("utf8"));
595
+ redirectTo = sanitizeRedirectTo(parsed.redirectTo);
596
+ } catch {
597
+ }
598
+ }
599
+ return NextResponse.redirect(new URL(redirectTo, origin));
600
+ }
601
+ function mapLocalPathToApiPath(route) {
602
+ if (route === "/me") return "/auth/me";
603
+ if (route === "/accounts/switch") return "/auth/accounts/switch";
604
+ if (route === "/organizations/active") return "/auth/organizations/active";
605
+ if (route === "/permissions/check") return "/auth/permissions/check";
606
+ if (route === "/login/password") return "/auth/login/password";
607
+ if (route === "/register/password") return "/auth/register/password";
608
+ if (route === "/passwordless/link") return "/auth/passwordless/link";
609
+ return route;
610
+ }
611
+ async function handleAccountsLocal() {
612
+ const [accounts, activeIdx] = await Promise.all([getAccountsList(), getActiveIndex()]);
613
+ return NextResponse.json({
614
+ accounts: accounts.map((a, i) => ({
615
+ id: a.id,
616
+ sessionId: a.sessionId ?? a.id,
617
+ isActive: i + 1 === activeIdx,
618
+ user: {
619
+ id: a.user.sub,
620
+ name: a.user.name ?? null,
621
+ email: a.user.email ?? null,
622
+ imageUrl: a.user.picture ?? null,
623
+ phone: a.user.phone ?? null
624
+ }
625
+ }))
626
+ });
627
+ }
628
+ async function handleOrganizationsLocal() {
629
+ const cookieStore = await cookies();
630
+ const activeOrgId = cookieStore.get(cn.activeOrganizationId)?.value ?? null;
631
+ try {
632
+ const data = await apiRequest("/organizations");
633
+ const organizations = Array.isArray(data) ? data : data.organizations;
634
+ return NextResponse.json({ organizations, currentOrgId: activeOrgId });
635
+ } catch {
636
+ return NextResponse.json({ organizations: [], currentOrgId: activeOrgId });
637
+ }
638
+ }
639
+ async function handleSwitchAccountLocal(request) {
640
+ const body = await readBody(request);
641
+ const targetId = body && typeof body === "object" ? String(
642
+ body.accountId ?? body.sessionId ?? ""
643
+ ) : "";
644
+ if (!targetId) {
645
+ return NextResponse.json({ error: "accountId required" }, { status: 400 });
646
+ }
647
+ const switched = await switchAccount(targetId);
648
+ if (!switched) {
649
+ return NextResponse.json({ error: "Account not found" }, { status: 404 });
650
+ }
651
+ return NextResponse.json({ ok: true });
652
+ }
653
+ async function proxy(request, route) {
654
+ const accessToken = await getAccessToken();
655
+ const body = ["GET", "HEAD"].includes(request.method) ? void 0 : await readBody(request);
656
+ const url = new URL(appendSearchParams(createUrl(config.issuer, mapLocalPathToApiPath(route)), request));
657
+ applyClientCredentials(url, config);
658
+ const requestHeaders = new Headers();
659
+ if (accessToken) requestHeaders.set("authorization", `Bearer ${accessToken}`);
660
+ if (body !== void 0) requestHeaders.set("content-type", "application/json");
661
+ let response = await fetch(url, {
662
+ method: request.method,
663
+ headers: requestHeaders,
664
+ body: body === void 0 ? void 0 : typeof body === "string" ? body : JSON.stringify(body),
665
+ cache: "no-store"
666
+ });
667
+ if (response.status === 401) {
668
+ const refreshed = await tryRefreshTokens();
669
+ if (refreshed) {
670
+ requestHeaders.set("authorization", `Bearer ${refreshed}`);
671
+ response = await fetch(url, {
672
+ method: request.method,
673
+ headers: requestHeaders,
674
+ body: body === void 0 ? void 0 : typeof body === "string" ? body : JSON.stringify(body),
675
+ cache: "no-store"
676
+ });
677
+ } else {
678
+ await clearAllSessionCookies().catch(() => {
679
+ });
680
+ return NextResponse.json(
681
+ { error: "session_expired" },
682
+ { status: 401 }
683
+ );
684
+ }
685
+ }
686
+ const data = isJsonResponse(response) ? await response.json().catch(() => null) : null;
687
+ if (data) {
688
+ const tokens = tokenFromResponse(data);
689
+ if (tokens.accessToken || tokens.refreshToken || tokens.idToken || tokens.sessionId) {
690
+ await saveAccountToList(tokens);
691
+ }
692
+ return NextResponse.json(data, { status: response.status });
693
+ }
694
+ return responseFromApi(response);
695
+ }
696
+ async function handle(request) {
697
+ const route = routeFromRequest(request, config.basePath);
698
+ if (request.method === "GET" && route === "/sign-in") return createAuthorizeRedirect(request, "login");
699
+ if (request.method === "GET" && route === "/sign-up") return createAuthorizeRedirect(request, "register");
700
+ if (request.method === "GET" && route === "/add-account") return createAuthorizeRedirect(request, "add-account");
701
+ if (request.method === "GET" && route === "/login/google") return createAuthorizeRedirect(request, "google");
702
+ if (request.method === "GET" && route === "/callback") {
703
+ const error = request.nextUrl.searchParams.get("error");
704
+ if (error) {
705
+ const description = request.nextUrl.searchParams.get("error_description") ?? request.nextUrl.searchParams.get("error_message") ?? "An authentication error occurred.";
706
+ return new NextResponse(
707
+ `<!doctype html><html><head><meta charset="utf-8"><title>Authentication Error</title></head><body style="font-family:sans-serif;max-width:480px;margin:80px auto;padding:0 16px"><h2>Authentication Error</h2><p><strong>${escapeHtml(error)}</strong></p><p>${escapeHtml(description)}</p><a href="/">Go back</a></body></html>`,
708
+ { status: 400, headers: { "content-type": "text/html; charset=utf-8" } }
709
+ );
710
+ }
711
+ return exchangeCode(request);
712
+ }
713
+ if (request.method === "GET" && route === "/token") {
714
+ const accessToken = await getAccessToken();
715
+ if (!accessToken) return NextResponse.json({ error: "missing_token" }, { status: 401 });
716
+ return NextResponse.json({ accessToken });
717
+ }
718
+ if (request.method === "GET" && route === "/accounts") return handleAccountsLocal();
719
+ if (request.method === "POST" && route === "/accounts/switch") return handleSwitchAccountLocal(request);
720
+ if (request.method === "GET" && route === "/organizations") return handleOrganizationsLocal();
721
+ if (request.method === "POST" && route === "/organizations") {
722
+ const accessToken = await getAccessToken();
723
+ const body = await readBody(request);
724
+ if (body && accessToken && !body.applicationId) {
725
+ const claims = decodeJwtPayload(accessToken);
726
+ const applicationId = (typeof claims?.application_id === "string" ? claims.application_id : null) ?? (typeof claims?.client_id === "string" ? claims.client_id : null) ?? (typeof claims?.applicationId === "string" ? claims.applicationId : null);
727
+ if (applicationId) body.applicationId = applicationId;
728
+ }
729
+ const orgUrl = new URL(createUrl(config.issuer, "/organizations"));
730
+ applyClientCredentials(orgUrl, config);
731
+ const requestHeaders = new Headers();
732
+ if (accessToken) requestHeaders.set("authorization", `Bearer ${accessToken}`);
733
+ if (body !== void 0) requestHeaders.set("content-type", "application/json");
734
+ const response = await fetch(orgUrl, {
735
+ method: "POST",
736
+ headers: requestHeaders,
737
+ body: JSON.stringify(body),
738
+ cache: "no-store"
739
+ });
740
+ return responseFromApi(response);
741
+ }
742
+ if (request.method === "POST" && route === "/sign-out") {
743
+ await apiRequest("/auth/sign-out", { method: "POST" }).catch(() => null);
744
+ await removeActiveAccount();
745
+ return NextResponse.json({ ok: true });
746
+ }
747
+ if (request.method === "POST" && route === "/sign-out-all") {
748
+ await apiRequest("/auth/sign-out-all", { method: "POST" }).catch(() => null);
749
+ await clearAllSessionCookies();
750
+ return NextResponse.json({ ok: true });
751
+ }
752
+ if (request.method === "POST" && route === "/organizations/active") {
753
+ const body = await readBody(request);
754
+ const organizationId = body && typeof body === "object" && "organizationId" in body ? body.organizationId : null;
755
+ const response = NextResponse.json({ ok: true });
756
+ if (typeof organizationId === "string") {
757
+ const cookieOpts = {
758
+ httpOnly: true,
759
+ sameSite: "lax",
760
+ path: "/",
761
+ secure: process.env.NODE_ENV === "production",
762
+ maxAge: 60 * 60 * 24 * 7
763
+ };
764
+ response.cookies.set(cn.activeOrganizationId, organizationId, cookieOpts);
765
+ }
766
+ return response;
767
+ }
768
+ return proxy(request, route);
769
+ }
770
+ return {
771
+ handlers: {
772
+ GET: handle,
773
+ POST: handle,
774
+ PATCH: handle,
775
+ DELETE: handle
776
+ },
777
+ GetSession: getSession,
778
+ GetUser: getUser,
779
+ GetUserById: getUserById,
780
+ GetOrganizations: getOrganizations,
781
+ SaveSession: saveAccountToList,
782
+ GetAccessToken: getAccessToken,
783
+ GetRefreshToken: getRefreshToken,
784
+ IsAuthenticated: async () => await getAccessToken() !== null,
785
+ TryRefreshTokens: tryRefreshTokens,
786
+ RequireUser: requireUser,
787
+ CreateAuthApiClient: createApiClient,
788
+ cookiePrefix: config.cookiePrefix,
789
+ VerifyToken: (token) => verifyToken(token, config.issuer),
790
+ SignInUrl: async (redirectTo) => {
791
+ const configured = env("GEEKAPPS_APP_URL");
792
+ if (!configured) throw new Error("Cannot determine app origin. Set GEEKAPPS_APP_URL.");
793
+ const origin = configured.replace(/\/$/, "");
794
+ const url = new URL(`${origin}${config.basePath}/sign-in`);
795
+ if (redirectTo) url.searchParams.set("redirectTo", redirectTo);
796
+ return url.toString();
797
+ }
798
+ };
799
+ }
8
800
 
9
801
  // src/connections.ts
10
802
  var AppConnectionError = class extends Error {
@@ -19,16 +811,16 @@ var AppConnectionError = class extends Error {
19
811
  this.body = body;
20
812
  }
21
813
  };
22
- function env(name) {
814
+ function env2(name) {
23
815
  const value = process.env[name];
24
816
  return value && value.trim().length > 0 ? value : void 0;
25
817
  }
26
818
  function resolveConfig(config) {
27
- const issuer = (config.issuer ?? env("GEEKAPPS_AUTH_SERVER_ISSUER") ?? env("GEEKAPPS_AUTH_SERVER_URL") ?? GEEKAPPS_AUTH_SERVER_URL).replace(/\/$/, "");
819
+ const issuer = (config.issuer ?? env2("GEEKAPPS_AUTH_SERVER_ISSUER") ?? env2("GEEKAPPS_AUTH_SERVER_URL") ?? GEEKAPPS_AUTH_SERVER_URL).replace(/\/$/, "");
28
820
  return {
29
821
  issuer,
30
- clientId: config.clientId ?? env("GEEKAPPS_AUTH_CLIENT_ID") ?? "",
31
- clientSecret: config.clientSecret ?? env("GEEKAPPS_AUTH_CLIENT_SECRET") ?? ""
822
+ clientId: config.clientId ?? env2("GEEKAPPS_AUTH_CLIENT_ID") ?? "",
823
+ clientSecret: config.clientSecret ?? env2("GEEKAPPS_AUTH_CLIENT_SECRET") ?? ""
32
824
  };
33
825
  }
34
826
  async function callAppConnection(params) {
@@ -38,12 +830,22 @@ async function callAppConnection(params) {
38
830
  "App Connections: defina GEEKAPPS_AUTH_CLIENT_ID e GEEKAPPS_AUTH_CLIENT_SECRET \u2014 \xE9 com essas credenciais que o proxy identifica a app que est\xE1 chamando."
39
831
  );
40
832
  }
833
+ const userToken = params.userToken ?? await configureGeekappsAuth().GetAccessToken();
834
+ if (!userToken) {
835
+ throw new AppConnectionError(
836
+ "App Connections: n\xE3o h\xE1 usu\xE1rio logado \u2014 a conex\xE3o \xE9 do usu\xE1rio, a chamada precisa do access token dele.",
837
+ 401,
838
+ "user_token_required",
839
+ null
840
+ );
841
+ }
41
842
  const url = `${issuer}/connections/${encodeURIComponent(params.targetAppId)}/actions/${encodeURIComponent(params.actionKey)}`;
42
843
  const credentials = Buffer.from(`${clientId}:${clientSecret}`).toString("base64");
43
844
  const response = await fetch(url, {
44
845
  method: "POST",
45
846
  headers: {
46
847
  authorization: `Basic ${credentials}`,
848
+ "x-user-token": userToken,
47
849
  "content-type": "application/json"
48
850
  },
49
851
  body: JSON.stringify(params.payload === void 0 ? {} : { payload: params.payload }),
@@ -65,8 +867,8 @@ var _registry = /* @__PURE__ */ new Map();
65
867
  function registerConnections(entries) {
66
868
  for (const [name, entry] of Object.entries(entries)) _registry.set(name, entry);
67
869
  }
68
- function resolveEntry(appName) {
69
- const entry = _registry.get(appName);
870
+ function resolveEntry(appName, registry = _registry) {
871
+ const entry = registry.get(appName);
70
872
  if (!entry) {
71
873
  throw new Error(
72
874
  `App Connections: app "${appName}" desconhecida. Rode "npx geekapps-connections" para gerar o cat\xE1logo e importe o arquivo gerado uma vez no boot da app.`
@@ -74,8 +876,8 @@ function resolveEntry(appName) {
74
876
  }
75
877
  return entry;
76
878
  }
77
- function resolveActionKey(appName, actionName) {
78
- const key = resolveEntry(appName).actions[actionName];
879
+ function resolveActionKey(appName, actionName, registry = _registry) {
880
+ const key = resolveEntry(appName, registry).actions[actionName];
79
881
  if (!key) {
80
882
  throw new Error(
81
883
  `App Connections: a\xE7\xE3o "${actionName}" n\xE3o existe em "${appName}", ou n\xE3o foi liberada na aprova\xE7\xE3o da conex\xE3o. Rode "npx geekapps-connections" para atualizar o cat\xE1logo.`
@@ -83,17 +885,18 @@ function resolveActionKey(appName, actionName) {
83
885
  }
84
886
  return key;
85
887
  }
86
- function createCatalog(config) {
888
+ function createCatalog(config, registry = _registry) {
87
889
  return new Proxy(/* @__PURE__ */ Object.create(null), {
88
890
  get(_target, appName) {
89
891
  if (typeof appName !== "string") return void 0;
90
892
  return new Proxy(/* @__PURE__ */ Object.create(null), {
91
893
  get(_t, actionName) {
92
894
  if (typeof actionName !== "string") return void 0;
93
- return (payload) => callAppConnection({
94
- targetAppId: resolveEntry(appName).appId,
95
- actionKey: resolveActionKey(appName, actionName),
895
+ return (payload, options) => callAppConnection({
896
+ targetAppId: resolveEntry(appName, registry).appId,
897
+ actionKey: resolveActionKey(appName, actionName, registry),
96
898
  payload,
899
+ userToken: options?.userToken,
97
900
  config
98
901
  });
99
902
  }
@@ -104,12 +907,94 @@ function createCatalog(config) {
104
907
  function createAppConnections(config = {}) {
105
908
  return createCatalog(config);
106
909
  }
910
+ function defineAppConnections(catalog, config = {}) {
911
+ const registry = new Map(Object.entries(catalog));
912
+ return createCatalog(config, registry);
913
+ }
107
914
  var appConnections = createAppConnections();
915
+ var CONNECT_COOKIES = {
916
+ verifier: "gk_conn_pkce",
917
+ state: "gk_conn_state",
918
+ returnTo: "gk_conn_return",
919
+ redirectUri: "gk_conn_redirect"
920
+ };
921
+ async function connectApp(params) {
922
+ const { issuer, clientId } = resolveConfig(params.config ?? {});
923
+ if (!clientId) {
924
+ throw new Error("App Connections: defina GEEKAPPS_AUTH_CLIENT_ID \u2014 \xE9 o client_id desta app, a que pede a conex\xE3o.");
925
+ }
926
+ if (params.actions.length === 0) {
927
+ throw new Error("App Connections: informe ao menos uma a\xE7\xE3o em `actions`.");
928
+ }
929
+ const codeVerifier = randomBytes2(64).toString("base64url");
930
+ const state = randomBytes2(24).toString("base64url");
931
+ const store = await cookies2();
932
+ const options = { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: 600 };
933
+ store.set(CONNECT_COOKIES.verifier, codeVerifier, options);
934
+ store.set(CONNECT_COOKIES.state, state, options);
935
+ store.set(CONNECT_COOKIES.returnTo, params.returnTo ?? "/", options);
936
+ store.set(CONNECT_COOKIES.redirectUri, params.redirectUri, options);
937
+ const url = new URL(`${issuer}/authorize`);
938
+ url.searchParams.set("client_id", clientId);
939
+ url.searchParams.set("redirect_uri", params.redirectUri);
940
+ url.searchParams.set("response_type", "code");
941
+ url.searchParams.set("scope", `openid ${params.actions.join(" ")}`);
942
+ url.searchParams.set("state", state);
943
+ url.searchParams.set("code_challenge", createHash2("sha256").update(codeVerifier).digest("base64url"));
944
+ url.searchParams.set("code_challenge_method", "S256");
945
+ url.searchParams.set("target_app_id", params.targetAppId);
946
+ if (params.displayName) url.searchParams.set("connection_display_name", params.displayName);
947
+ redirect2(url.toString());
948
+ }
949
+ async function completeAppConnection(params) {
950
+ const { issuer, clientId, clientSecret } = resolveConfig(params.config ?? {});
951
+ if (!clientId || !clientSecret) {
952
+ throw new Error("App Connections: defina GEEKAPPS_AUTH_CLIENT_ID e GEEKAPPS_AUTH_CLIENT_SECRET.");
953
+ }
954
+ const store = await cookies2();
955
+ const read = (name) => store.get(name)?.value;
956
+ const expectedState = read(CONNECT_COOKIES.state);
957
+ const codeVerifier = read(CONNECT_COOKIES.verifier);
958
+ const redirectUri = read(CONNECT_COOKIES.redirectUri);
959
+ const returnTo = read(CONNECT_COOKIES.returnTo) ?? "/";
960
+ for (const name of Object.values(CONNECT_COOKIES)) store.set(name, "", { maxAge: 0, path: "/" });
961
+ if (!expectedState || !codeVerifier || !redirectUri || params.state !== expectedState) {
962
+ throw new AppConnectionError("App Connections: estado inv\xE1lido \u2014 inicie a conex\xE3o novamente.", 400, "invalid_state", null);
963
+ }
964
+ const response = await fetch(`${issuer}/oauth/token`, {
965
+ method: "POST",
966
+ headers: {
967
+ authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`,
968
+ "content-type": "application/x-www-form-urlencoded"
969
+ },
970
+ body: new URLSearchParams({
971
+ grant_type: "authorization_code",
972
+ code: params.code,
973
+ redirect_uri: redirectUri,
974
+ code_verifier: codeVerifier
975
+ }),
976
+ cache: "no-store"
977
+ });
978
+ if (!response.ok) {
979
+ const body = await response.json().catch(() => null);
980
+ const code = body && typeof body.error === "string" ? body.error : void 0;
981
+ throw new AppConnectionError(
982
+ `App Connections: n\xE3o foi poss\xEDvel concluir a conex\xE3o (${response.status}${code ? ` ${code}` : ""})`,
983
+ response.status,
984
+ code,
985
+ body
986
+ );
987
+ }
988
+ return { returnTo };
989
+ }
108
990
  export {
109
991
  AppConnectionError,
110
992
  appConnections,
111
993
  callAppConnection,
994
+ completeAppConnection,
995
+ connectApp,
112
996
  createAppConnections,
997
+ defineAppConnections,
113
998
  registerConnections
114
999
  };
115
1000
  //# sourceMappingURL=connections.js.map