@geekapps/auth-nextjs 0.13.0 → 0.14.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,114 +0,0 @@
1
- /**
2
- * App Connections — chamar ações de negócio de OUTRA Application.
3
- *
4
- * Uma conexão liga um USUÁRIO desta app (X) a uma app alvo (Y). Ele a aprova
5
- * uma vez no consent, escolhendo as ações liberadas e a organização dentro do
6
- * Y sob a qual elas rodam. A chamada vai com o access token desse usuário (o
7
- * da sessão, por padrão): é ele que diz ao proxy qual conexão usar.
8
- *
9
- * Nada aqui fala com a API do Y diretamente: tudo passa pelo proxy do
10
- * auth-server, que valida a conexão e injeta a credencial. Esta app nunca vê
11
- * essa credencial — é esse o ponto do proxy.
12
- *
13
- * O catálogo tipado (`GeekappsConnections`) vem do arquivo gerado por
14
- * `npx geekapps-connections`.
15
- */
16
- /** Opções por chamada. Sem `userToken`, usa o access token do usuário logado na sessão. */
17
- type ConnectionCallOptions = {
18
- userToken?: string;
19
- };
20
- type AppConnectionsConfig = {
21
- issuer?: string;
22
- /** client_id/secret desta app (a consumidora, X). */
23
- clientId?: string;
24
- clientSecret?: string;
25
- };
26
- /**
27
- * Preenchida por declaration merging no arquivo gerado
28
- * (`geekapps-connections.d.ts`). Vazia aqui de propósito: o SDK não sabe
29
- * quais apps existem — quem sabe é o auth-server, no momento da geração.
30
- */
31
- interface GeekappsConnections {
32
- }
33
- /** Erro de uma chamada de proxy — carrega o status HTTP para dar pra tratar. */
34
- declare class AppConnectionError extends Error {
35
- readonly status: number;
36
- readonly code: string | undefined;
37
- readonly body: unknown;
38
- constructor(message: string, status: number, code: string | undefined, body: unknown);
39
- }
40
- /**
41
- * A chamada crua do proxy, para quando não há catálogo gerado. `targetAppId` é
42
- * o client_id da app alvo e `actionKey` é a AppAction.key — o mesmo valor que
43
- * aparece como scope no consent.
44
- */
45
- declare function callAppConnection<T = unknown>(params: {
46
- targetAppId: string;
47
- actionKey: string;
48
- payload?: unknown;
49
- /** Access token do usuário dono da conexão. Padrão: o do usuário logado. */
50
- userToken?: string;
51
- config?: AppConnectionsConfig;
52
- }): Promise<T>;
53
- /**
54
- * Registry preenchido pelo arquivo gerado via `registerConnections()`. Mapeia
55
- * o nome amigável da app (`billing`) para o client_id real, e o nome da ação
56
- * (`createCharge`) para a AppAction.key (`billing.charges.create`).
57
- */
58
- type ConnectionRegistryEntry = {
59
- appId: string;
60
- actions: Record<string, string>;
61
- };
62
- /** Chamado pelo arquivo gerado. Não edite à mão — ele é reescrito a cada geração. */
63
- declare function registerConnections(entries: Record<string, ConnectionRegistryEntry>): void;
64
- type AppConnectionsClient = GeekappsConnections;
65
- /** Cliente com config explícita — para quem não usa as env vars padrão. */
66
- declare function createAppConnections(config?: AppConnectionsConfig): AppConnectionsClient;
67
- /** Catálogo gerado por `npx geekapps-connections` (`geekappsConnectionsCatalog`). */
68
- type ConnectionsCatalog = Record<string, ConnectionRegistryEntry | {
69
- readonly appId: string;
70
- readonly actions: Readonly<Record<string, string>>;
71
- }>;
72
- /**
73
- * Liga o catálogo gerado ao cliente, sem registry global:
74
- *
75
- * import { geekappsConnectionsCatalog, type GeekappsConnections } from "./geekapps-connections";
76
- * export const connections = defineAppConnections<GeekappsConnections>(geekappsConnectionsCatalog);
77
- * await connections.billing.chargesCreate({ ... });
78
- */
79
- declare function defineAppConnections<T>(catalog: ConnectionsCatalog, config?: AppConnectionsConfig): T;
80
- /** Cliente padrão, lendo GEEKAPPS_AUTH_CLIENT_ID / _SECRET do ambiente. */
81
- declare const appConnections: AppConnectionsClient;
82
- type ConnectAppParams = {
83
- /** client_id da app ALVO (a que expõe as ações). */
84
- targetAppId: string;
85
- /** AppAction.key das ações pedidas — as mesmas que aparecem no consent. */
86
- actions: string[];
87
- /** URL desta app que recebe o retorno do consent (rota que chama `completeAppConnection`). Precisa estar nos redirect URIs desta app. */
88
- redirectUri: string;
89
- /** Para onde `completeAppConnection` manda o usuário depois (padrão "/"). */
90
- returnTo?: string;
91
- /** Nome desta app exibido no consent. */
92
- displayName?: string;
93
- config?: AppConnectionsConfig;
94
- };
95
- /**
96
- * Inicia a conexão desta app com `targetAppId`: guarda PKCE/state em cookies
97
- * httpOnly e redireciona para o consent. Chame de um Server Action ou Route
98
- * Handler — não retorna (o `redirect` do Next interrompe a execução).
99
- */
100
- declare function connectApp(params: ConnectAppParams): Promise<never>;
101
- /**
102
- * Fecha o fluxo de `connectApp`. Chame no callback com o `code` e o `state`
103
- * da query; devolve o `returnTo` para você redirecionar. Lança
104
- * AppConnectionError se o state não bater ou o auth-server recusar.
105
- */
106
- declare function completeAppConnection(params: {
107
- code: string;
108
- state: string;
109
- config?: AppConnectionsConfig;
110
- }): Promise<{
111
- returnTo: string;
112
- }>;
113
-
114
- export { AppConnectionError, type AppConnectionsClient, type AppConnectionsConfig, type ConnectAppParams, type ConnectionCallOptions, type ConnectionsCatalog, type GeekappsConnections, appConnections, callAppConnection, completeAppConnection, connectApp, createAppConnections, defineAppConnections, registerConnections };
@@ -1,22 +0,0 @@
1
- import { NextRequest, NextResponse } from 'next/server';
2
-
3
- type AuthMiddlewareConfig = {
4
- issuer?: string;
5
- basePath?: string;
6
- /**
7
- * @deprecated cookiePrefix is now auto-derived from GEEKAPPS_AUTH_CLIENT_ID.
8
- * This field is kept for backwards compatibility but is ignored.
9
- */
10
- cookiePrefix?: string;
11
- secureCookies?: boolean;
12
- /** Base URL of this app (e.g. "https://meuapp.com"). Overrides the GEEKAPPS_APP_URL env var. */
13
- appUrl?: string;
14
- /**
15
- * When true, unauthenticated requests are redirected to sign-in.
16
- * Defaults to false — the app controls its own auth-gating.
17
- */
18
- forceLoginOnUnauthenticated?: boolean;
19
- };
20
- declare function createAuthMiddleware(input?: AuthMiddlewareConfig): (request: NextRequest) => Promise<NextResponse>;
21
-
22
- export { type AuthMiddlewareConfig, createAuthMiddleware };
package/dist/server.d.ts DELETED
@@ -1,138 +0,0 @@
1
- import { NextRequest, NextResponse } from 'next/server';
2
- import { JWTPayload } from 'jose';
3
-
4
- /**
5
- * A sessão não vale mais: expirou, foi revogada no painel ou o refresh token
6
- * foi invalidado. Os cookies já foram limpos quando este erro é lançado, então
7
- * o tratamento normal é redirecionar para o login.
8
- */
9
- declare class GeekappsSessionExpiredError extends Error {
10
- readonly code: "session_expired";
11
- constructor(message?: string);
12
- }
13
- /**
14
- * Fixed URL of the Geekapps Auth Server (OIDC issuer + API). This never
15
- * changes per-environment, so it is hardcoded rather than read from env.
16
- */
17
- declare const GEEKAPPS_AUTH_SERVER_URL = "https://accounts-api.geekapps.com.br";
18
- type GeekappsAuthConfig = {
19
- /**
20
- * Auth Server (OIDC) issuer URL. Defaults to GEEKAPPS_AUTH_SERVER_URL and
21
- * should not need overriding in normal use.
22
- *
23
- * Deprecated (still supported as a fallback): GEEKAPPS_AUTH_SERVER_ISSUER,
24
- * GEEKAPPS_AUTH_ISSUER, GEEKAPPS_AUTH_SERVER_URL env, GEEKAPPS_AUTH_API_URL
25
- */
26
- issuer?: string;
27
- /**
28
- * OAuth client id. Optional when GEEKAPPS_AUTH_CLIENT_ID is defined.
29
- */
30
- clientId?: string;
31
- /**
32
- * OAuth client secret for confidential clients. Optional when
33
- * GEEKAPPS_AUTH_CLIENT_SECRET is defined.
34
- */
35
- clientSecret?: string;
36
- /**
37
- * Callback URL. Optional when GEEKAPPS_AUTH_REDIRECT_URI is defined.
38
- * If omitted, it is inferred from the current request origin + basePath/callback.
39
- */
40
- redirectUri?: string;
41
- scopes?: string[];
42
- basePath?: string;
43
- /**
44
- * @deprecated cookiePrefix is now auto-derived from clientId.
45
- * This field is kept for backwards compatibility but is ignored.
46
- */
47
- cookiePrefix?: string;
48
- secureCookies?: boolean;
49
- /**
50
- * Friendly alias used by apps. Same as afterSignInRedirectTo.
51
- */
52
- redirectTo?: string;
53
- afterSignInRedirectTo?: string;
54
- afterSignOutRedirectTo?: string;
55
- };
56
- type SessionTokens = {
57
- accessToken: string | null;
58
- refreshToken: string | null;
59
- idToken: string | null;
60
- sessionId: string | null;
61
- };
62
- type StoredAccount = {
63
- /** Stable identifier — `sub` from id_token or fallback to sessionId. */
64
- id: string;
65
- accessToken: string;
66
- refreshToken: string | null;
67
- idToken: string | null;
68
- sessionId: string | null;
69
- user: {
70
- sub: string;
71
- name?: string | null;
72
- email?: string | null;
73
- picture?: string | null;
74
- phone?: string | null;
75
- };
76
- };
77
- type ServerAuthApiClient = {
78
- get: <T>(path: string) => Promise<T>;
79
- post: <T>(path: string, body?: unknown) => Promise<T>;
80
- patch: <T>(path: string, body?: unknown) => Promise<T>;
81
- put: <T>(path: string, body?: unknown) => Promise<T>;
82
- delete: <T>(path: string) => Promise<T>;
83
- };
84
- type ServiceAccountConfig = {
85
- issuer?: string;
86
- clientId?: string;
87
- clientSecret?: string;
88
- };
89
- /**
90
- * Returns a service account access token.
91
- * The issuer is always the Geekapps Auth Server (GEEKAPPS_AUTH_SERVER_URL) —
92
- * it does not need to be configured. Reads GEEKAPPS_SERVICE_ACCOUNT_CLIENT_ID,
93
- * GEEKAPPS_SERVICE_ACCOUNT_CLIENT_SECRET by default.
94
- * Any field can be overridden via the optional config argument.
95
- * Tokens are cached per client and auto-renewed before expiry (~7 min TTL).
96
- */
97
- declare function getServiceAccountToken(override?: ServiceAccountConfig): Promise<string | null>;
98
- declare function verifyToken(token: string, issuer: string): Promise<JWTPayload | null>;
99
- declare function configureGeekappsAuth(input?: GeekappsAuthConfig): {
100
- handlers: {
101
- GET: (request: NextRequest) => Promise<NextResponse<any>>;
102
- POST: (request: NextRequest) => Promise<NextResponse<any>>;
103
- PATCH: (request: NextRequest) => Promise<NextResponse<any>>;
104
- DELETE: (request: NextRequest) => Promise<NextResponse<any>>;
105
- };
106
- GetSession: () => Promise<SessionTokens | null>;
107
- GetUser: () => Promise<StoredAccount["user"] | null>;
108
- GetUserById: (userId: string, applicationId?: string) => Promise<unknown | null>;
109
- GetOrganizations: () => Promise<{
110
- organizations: unknown[];
111
- currentOrgId: string | null;
112
- }>;
113
- SaveSession: (tokens: SessionTokens) => Promise<void>;
114
- GetAccessToken: () => Promise<string | null>;
115
- GetRefreshToken: () => Promise<string | null>;
116
- IsAuthenticated: () => Promise<boolean>;
117
- TryRefreshTokens: () => Promise<string | null>;
118
- RequireUser: (options?: {
119
- redirectTo?: string;
120
- }) => Promise<string>;
121
- CreateAuthApiClient: () => ServerAuthApiClient;
122
- cookiePrefix: string;
123
- VerifyToken: (token: string) => Promise<JWTPayload | null>;
124
- SignInUrl: (redirectTo?: string) => Promise<string>;
125
- };
126
- declare function handlers(options?: GeekappsAuthConfig): {
127
- GET: (request: NextRequest) => Promise<NextResponse<any>>;
128
- POST: (request: NextRequest) => Promise<NextResponse<any>>;
129
- PATCH: (request: NextRequest) => Promise<NextResponse<any>>;
130
- DELETE: (request: NextRequest) => Promise<NextResponse<any>>;
131
- };
132
- /**
133
- * Returns true if the current request has a valid access token in cookies.
134
- * Safe to call in Server Components, Server Actions, and Route Handlers.
135
- */
136
- declare function isAuthenticated(options?: GeekappsAuthConfig): Promise<boolean>;
137
-
138
- export { GEEKAPPS_AUTH_SERVER_URL, type GeekappsAuthConfig, GeekappsSessionExpiredError, type ServerAuthApiClient, type SessionTokens, type StoredAccount, configureGeekappsAuth, getServiceAccountToken, handlers, isAuthenticated, verifyToken };