@incorta/auth 1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Incorta
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,61 @@
1
+ # @incorta/auth
2
+
3
+ Authenticate Incorta users in any Node.js app via Incorta's built-in OAuth
4
+ 2.0/OIDC authorization server. See the repository root README for the full
5
+ guide; this is the API surface.
6
+
7
+ ## Entry points
8
+
9
+ | Import | What's in it |
10
+ | ----------------------- | ------------------------------------------------------------------- |
11
+ | `@incorta/auth` | `createIncortaAuth`, `registerClient`, types (`IncortaUser`, `AuthSession`, …) |
12
+ | `@incorta/auth/react` | `IncortaAuthProvider`, `useAuth`, `useUser`, `SignedIn`, `SignedOut`, `Protect`, `RedirectToLogin` |
13
+ | `@incorta/auth/express` | `incortaAuth(auth)` middleware, `requireAuth(auth, options?)` |
14
+ | `@incorta/auth/node` | `toNodeHandler(auth)`, `toWebRequest`, `sendWebResponse`, `getNodeSession` |
15
+
16
+ ## `createIncortaAuth(config?)`
17
+
18
+ Returns `{ handler, getSession, config }`:
19
+
20
+ - `handler(request: Request): Promise<Response>` — serves, under
21
+ `config.basePath` (default `/auth`):
22
+ - `GET /login?redirect_to=` — 302 into the Incorta authorize flow (or straight
23
+ back when already signed in). Sets a sealed state+nonce cookie (10 min).
24
+ - `GET /callback` — validates state, exchanges the code
25
+ (`client_secret_basic`), verifies the ID token against the tenant JWKS
26
+ (issuer, audience, nonce), seals the session cookie, 302 to the original page.
27
+ Failures 302 to `{redirect_to}?incorta_auth_error={code}`.
28
+ - `GET /session` — `{ user, session }` or `{ user: null }`. Refreshes the
29
+ access token (rotating refresh token) when <60s from expiry; slides the
30
+ session cookie past its half-life.
31
+ - `GET|POST /logout` — clears the session cookie (GET also redirects).
32
+ - `GET /token` — the raw Incorta access token; only with
33
+ `exposeAccessToken: true`, otherwise 404.
34
+ - `getSession(request): Promise<AuthSession | null>` — read-only session lookup
35
+ for server code (`user`, `accessToken`, `accessTokenExpiresAt`, `expiresAt`).
36
+
37
+ Config falls back to `INCORTA_URL`, `INCORTA_TENANT`, `INCORTA_CLIENT_ID`,
38
+ `INCORTA_CLIENT_SECRET`, `INCORTA_AUTH_SECRET`, `INCORTA_APP_URL`.
39
+
40
+ ## Session model
41
+
42
+ The cookie is an encrypted JWT (JWE `dir`/`A256GCM`, key derived from
43
+ `secret`), HttpOnly, `SameSite=Lax`, `Secure` on HTTPS. Payload: verified user
44
+ claims (`sub`, `name`, `email`, `roles`, `tenant`) + the Incorta access/refresh
45
+ tokens. Nothing is stored server-side.
46
+
47
+ ## CLI
48
+
49
+ ```bash
50
+ incorta-auth register --url http://localhost:8080/incorta --tenant demo \
51
+ --name "My App" --redirect https://myapp.example.com/auth/callback [--json]
52
+ ```
53
+
54
+ Registers the OAuth client via RFC 7591 dynamic registration and prints the
55
+ `.env` entries.
56
+
57
+ ## Testing
58
+
59
+ `pnpm test` runs the suite against an in-process replica of Incorta's OAuth
60
+ endpoints (`test/mock-incorta.ts`) — full login/callback/refresh/logout flows
61
+ over real HTTP sockets, no Incorta needed.
@@ -0,0 +1,62 @@
1
+ // src/node.ts
2
+ async function toWebRequest(req) {
3
+ const proto = req.headers["x-forwarded-proto"]?.split(",")[0]?.trim() ?? (req.socket.encrypted ? "https" : "http");
4
+ const host = req.headers.host ?? "localhost";
5
+ const path = req.originalUrl ?? req.url ?? "/";
6
+ const url = `${proto}://${host}${path}`;
7
+ const headers = new Headers();
8
+ for (let i = 0; i < req.rawHeaders.length; i += 2) {
9
+ headers.append(req.rawHeaders[i], req.rawHeaders[i + 1]);
10
+ }
11
+ const method = req.method ?? "GET";
12
+ let body;
13
+ if (method !== "GET" && method !== "HEAD") {
14
+ const chunks = [];
15
+ for await (const chunk of req) {
16
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
17
+ }
18
+ if (chunks.length) {
19
+ const bytes = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
20
+ let offset = 0;
21
+ for (const chunk of chunks) {
22
+ bytes.set(chunk, offset);
23
+ offset += chunk.length;
24
+ }
25
+ body = bytes;
26
+ }
27
+ }
28
+ return new Request(url, { method, headers, body });
29
+ }
30
+ async function sendWebResponse(res, response) {
31
+ res.statusCode = response.status;
32
+ response.headers.forEach((value, name) => {
33
+ if (name.toLowerCase() === "set-cookie") return;
34
+ res.setHeader(name, value);
35
+ });
36
+ const setCookies = response.headers.getSetCookie();
37
+ if (setCookies.length) res.setHeader("set-cookie", setCookies);
38
+ if (response.body) {
39
+ const buffer = Buffer.from(await response.arrayBuffer());
40
+ res.end(buffer);
41
+ } else {
42
+ res.end();
43
+ }
44
+ }
45
+ function toNodeHandler(auth) {
46
+ return async (req, res) => {
47
+ const request = await toWebRequest(req);
48
+ const response = await auth.handler(request);
49
+ await sendWebResponse(res, response);
50
+ };
51
+ }
52
+ async function getNodeSession(auth, req) {
53
+ return auth.getSession(await toWebRequest(req));
54
+ }
55
+
56
+ export {
57
+ toWebRequest,
58
+ sendWebResponse,
59
+ toNodeHandler,
60
+ getNodeSession
61
+ };
62
+ //# sourceMappingURL=chunk-LNPECE7W.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/node.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { IncortaAuth } from \"./index.js\";\n\nexport type { IncortaAuth } from \"./index.js\";\n\n/**\n * Builds a web-standard `Request` from a Node request. Buffers the body (the\n * auth routes are GET/POST-without-body, so this stays tiny).\n */\nexport async function toWebRequest(req: IncomingMessage): Promise<Request> {\n const proto =\n (req.headers[\"x-forwarded-proto\"] as string | undefined)?.split(\",\")[0]?.trim() ??\n ((req.socket as { encrypted?: boolean }).encrypted ? \"https\" : \"http\");\n const host = req.headers.host ?? \"localhost\";\n // Express rewrites req.url when routers are mounted — originalUrl keeps the full path.\n const path = (req as { originalUrl?: string }).originalUrl ?? req.url ?? \"/\";\n const url = `${proto}://${host}${path}`;\n\n const headers = new Headers();\n for (let i = 0; i < req.rawHeaders.length; i += 2) {\n headers.append(req.rawHeaders[i], req.rawHeaders[i + 1]);\n }\n\n const method = req.method ?? \"GET\";\n let body: BodyInit | undefined;\n if (method !== \"GET\" && method !== \"HEAD\") {\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n if (chunks.length) {\n const bytes = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n body = bytes;\n }\n }\n\n return new Request(url, { method, headers, body });\n}\n\nexport async function sendWebResponse(\n res: ServerResponse,\n response: Response,\n): Promise<void> {\n res.statusCode = response.status;\n response.headers.forEach((value, name) => {\n if (name.toLowerCase() === \"set-cookie\") return; // handled below, needs the un-joined list\n res.setHeader(name, value);\n });\n const setCookies = response.headers.getSetCookie();\n if (setCookies.length) res.setHeader(\"set-cookie\", setCookies);\n\n if (response.body) {\n const buffer = Buffer.from(await response.arrayBuffer());\n res.end(buffer);\n } else {\n res.end();\n }\n}\n\n/**\n * Adapts the auth handler to a plain Node `(req, res)` listener:\n *\n * ```ts\n * import http from \"node:http\";\n * const authListener = toNodeHandler(auth);\n * http.createServer((req, res) => {\n * if (req.url?.startsWith(\"/auth\")) return authListener(req, res);\n * // ... your app\n * });\n * ```\n */\nexport function toNodeHandler(auth: IncortaAuth) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const request = await toWebRequest(req);\n const response = await auth.handler(request);\n await sendWebResponse(res, response);\n };\n}\n\n/** Reads the current session from a Node request (returns null when signed out). */\nexport async function getNodeSession(auth: IncortaAuth, req: IncomingMessage) {\n return auth.getSession(await toWebRequest(req));\n}\n"],"mappings":";AASA,eAAsB,aAAa,KAAwC;AACzE,QAAM,QACH,IAAI,QAAQ,mBAAmB,GAA0B,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,MAC5E,IAAI,OAAmC,YAAY,UAAU;AACjE,QAAM,OAAO,IAAI,QAAQ,QAAQ;AAEjC,QAAM,OAAQ,IAAiC,eAAe,IAAI,OAAO;AACzE,QAAM,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,IAAI;AAErC,QAAM,UAAU,IAAI,QAAQ;AAC5B,WAAS,IAAI,GAAG,IAAI,IAAI,WAAW,QAAQ,KAAK,GAAG;AACjD,YAAQ,OAAO,IAAI,WAAW,CAAC,GAAG,IAAI,WAAW,IAAI,CAAC,CAAC;AAAA,EACzD;AAEA,QAAM,SAAS,IAAI,UAAU;AAC7B,MAAI;AACJ,MAAI,WAAW,SAAS,WAAW,QAAQ;AACzC,UAAM,SAAmB,CAAC;AAC1B,qBAAiB,SAAS,KAAK;AAC7B,aAAO,KAAK,OAAO,SAAS,KAAK,IAAI,QAAQ,OAAO,KAAK,KAAK,CAAC;AAAA,IACjE;AACA,QAAI,OAAO,QAAQ;AACjB,YAAM,QAAQ,IAAI,WAAW,OAAO,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,QAAQ,CAAC,CAAC;AACrE,UAAI,SAAS;AACb,iBAAW,SAAS,QAAQ;AAC1B,cAAM,IAAI,OAAO,MAAM;AACvB,kBAAU,MAAM;AAAA,MAClB;AACA,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,IAAI,QAAQ,KAAK,EAAE,QAAQ,SAAS,KAAK,CAAC;AACnD;AAEA,eAAsB,gBACpB,KACA,UACe;AACf,MAAI,aAAa,SAAS;AAC1B,WAAS,QAAQ,QAAQ,CAAC,OAAO,SAAS;AACxC,QAAI,KAAK,YAAY,MAAM,aAAc;AACzC,QAAI,UAAU,MAAM,KAAK;AAAA,EAC3B,CAAC;AACD,QAAM,aAAa,SAAS,QAAQ,aAAa;AACjD,MAAI,WAAW,OAAQ,KAAI,UAAU,cAAc,UAAU;AAE7D,MAAI,SAAS,MAAM;AACjB,UAAM,SAAS,OAAO,KAAK,MAAM,SAAS,YAAY,CAAC;AACvD,QAAI,IAAI,MAAM;AAAA,EAChB,OAAO;AACL,QAAI,IAAI;AAAA,EACV;AACF;AAcO,SAAS,cAAc,MAAmB;AAC/C,SAAO,OAAO,KAAsB,QAAuC;AACzE,UAAM,UAAU,MAAM,aAAa,GAAG;AACtC,UAAM,WAAW,MAAM,KAAK,QAAQ,OAAO;AAC3C,UAAM,gBAAgB,KAAK,QAAQ;AAAA,EACrC;AACF;AAGA,eAAsB,eAAe,MAAmB,KAAsB;AAC5E,SAAO,KAAK,WAAW,MAAM,aAAa,GAAG,CAAC;AAChD;","names":[]}
package/dist/cli.js ADDED
@@ -0,0 +1,170 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { randomBytes } from "crypto";
5
+
6
+ // src/core/register.ts
7
+ async function registerClient(options) {
8
+ const {
9
+ incortaUrl,
10
+ tenant,
11
+ name,
12
+ redirectUris,
13
+ scope = "openid profile email",
14
+ grantTypes = ["authorization_code", "refresh_token"],
15
+ fetchImpl = fetch
16
+ } = options;
17
+ if (!redirectUris.length) {
18
+ throw new Error("[incorta-auth] registerClient requires at least one redirect URI.");
19
+ }
20
+ const endpoint = `${incortaUrl.replace(/\/+$/, "")}/oauth/${tenant}/register`;
21
+ const response = await fetchImpl(endpoint, {
22
+ method: "POST",
23
+ headers: { "content-type": "application/json", accept: "application/json" },
24
+ body: JSON.stringify({
25
+ client_name: name,
26
+ redirect_uris: redirectUris,
27
+ grant_types: grantTypes,
28
+ scope,
29
+ token_endpoint_auth_method: "client_secret_basic"
30
+ })
31
+ });
32
+ let body;
33
+ try {
34
+ body = await response.json();
35
+ } catch {
36
+ throw new Error(
37
+ `[incorta-auth] Client registration returned a non-JSON response (HTTP ${response.status}). Is the OAuth authorization server enabled on this cluster?`
38
+ );
39
+ }
40
+ if (!response.ok || !body.client_id || !body.client_secret) {
41
+ throw new Error(
42
+ `[incorta-auth] Client registration failed (HTTP ${response.status}): ${body.error ?? "unknown_error"} \u2014 ${body.error_description ?? "no description"}`
43
+ );
44
+ }
45
+ return {
46
+ clientId: body.client_id,
47
+ clientSecret: body.client_secret,
48
+ registrationAccessToken: body.registration_access_token,
49
+ registrationClientUri: body.registration_client_uri
50
+ };
51
+ }
52
+
53
+ // src/cli.ts
54
+ var HELP = `incorta-auth \u2014 IncortaAuth SDK helper
55
+
56
+ Usage:
57
+ incorta-auth register --url <incortaUrl> --tenant <tenant> --name <name> \\
58
+ --redirect <callbackUrl> [--redirect <callbackUrl> ...] \\
59
+ [--scope "openid profile email"] [--json]
60
+
61
+ Registers an OAuth client in Incorta (RFC 7591 dynamic registration) and prints
62
+ the .env entries your app needs.
63
+
64
+ Example:
65
+ incorta-auth register \\
66
+ --url http://localhost:8080/incorta \\
67
+ --tenant demo \\
68
+ --name "My App" \\
69
+ --redirect http://localhost:4000/auth/callback
70
+ `;
71
+ function parseArgs(argv) {
72
+ const args = { redirects: [], json: false };
73
+ for (let i = 0; i < argv.length; i++) {
74
+ const flag = argv[i];
75
+ const next = () => {
76
+ const value = argv[++i];
77
+ if (value === void 0) throw new Error(`Missing value for ${flag}`);
78
+ return value;
79
+ };
80
+ switch (flag) {
81
+ case "--url":
82
+ args.url = next();
83
+ break;
84
+ case "--tenant":
85
+ args.tenant = next();
86
+ break;
87
+ case "--name":
88
+ args.name = next();
89
+ break;
90
+ case "--scope":
91
+ args.scope = next();
92
+ break;
93
+ case "--redirect":
94
+ args.redirects.push(next());
95
+ break;
96
+ case "--json":
97
+ args.json = true;
98
+ break;
99
+ default:
100
+ throw new Error(`Unknown flag: ${flag}`);
101
+ }
102
+ }
103
+ return args;
104
+ }
105
+ async function main() {
106
+ const [command, ...rest] = process.argv.slice(2);
107
+ if (!command || command === "help" || command === "--help" || command === "-h") {
108
+ console.log(HELP);
109
+ return command ? 0 : 1;
110
+ }
111
+ if (command !== "register") {
112
+ console.error(`Unknown command: ${command}
113
+ `);
114
+ console.log(HELP);
115
+ return 1;
116
+ }
117
+ let args;
118
+ try {
119
+ args = parseArgs(rest);
120
+ } catch (error) {
121
+ console.error(`${error.message}
122
+ `);
123
+ console.log(HELP);
124
+ return 1;
125
+ }
126
+ const missing = ["url", "tenant", "name"].filter((key) => !args[key]);
127
+ if (missing.length || !args.redirects.length) {
128
+ console.error(
129
+ `Missing required flag(s): ${[...missing.map((m) => `--${m}`), ...args.redirects.length ? [] : ["--redirect"]].join(", ")}
130
+ `
131
+ );
132
+ console.log(HELP);
133
+ return 1;
134
+ }
135
+ const client = await registerClient({
136
+ incortaUrl: args.url,
137
+ tenant: args.tenant,
138
+ name: args.name,
139
+ redirectUris: args.redirects,
140
+ scope: args.scope
141
+ });
142
+ if (args.json) {
143
+ console.log(JSON.stringify(client, null, 2));
144
+ return 0;
145
+ }
146
+ const authSecret = randomBytes(32).toString("base64url");
147
+ console.log(`Client registered successfully.
148
+ `);
149
+ console.log(`Add this to your app's .env:
150
+ `);
151
+ console.log(`INCORTA_URL=${args.url}`);
152
+ console.log(`INCORTA_TENANT=${args.tenant}`);
153
+ console.log(`INCORTA_CLIENT_ID=${client.clientId}`);
154
+ console.log(`INCORTA_CLIENT_SECRET=${client.clientSecret}`);
155
+ console.log(`INCORTA_AUTH_SECRET=${authSecret}`);
156
+ if (client.registrationAccessToken) {
157
+ console.log(
158
+ `
159
+ # Keep these to manage the registration later (PUT/DELETE ${client.registrationClientUri ?? "the registration endpoint"}):`
160
+ );
161
+ console.log(`# registration_access_token: ${client.registrationAccessToken}`);
162
+ }
163
+ return 0;
164
+ }
165
+ main().then((code) => {
166
+ process.exitCode = code;
167
+ }).catch((error) => {
168
+ console.error(error.message);
169
+ process.exitCode = 1;
170
+ });
@@ -0,0 +1,116 @@
1
+ import { JWTVerifyGetKey } from 'jose';
2
+
3
+ /** The Incorta user identity carried by the session (claims from the ID token). */
4
+ interface IncortaUser {
5
+ /** Incorta login name (`sub` claim). */
6
+ sub: string;
7
+ name?: string;
8
+ email?: string;
9
+ /** Incorta role names, as minted into the ID token. */
10
+ roles: string[];
11
+ /** Tenant the user authenticated against. */
12
+ tenant: string;
13
+ }
14
+ /** What the sealed session cookie holds. */
15
+ interface SessionData {
16
+ user: IncortaUser;
17
+ /** Incorta-issued access token (RS256 JWT, aud = client_id). */
18
+ accessToken: string;
19
+ /** Epoch millis when the access token expires. */
20
+ accessTokenExpiresAt: number;
21
+ /** Rotating refresh token, present when the client has the refresh_token grant. */
22
+ refreshToken?: string;
23
+ /** Epoch millis when this session was first created (login time). */
24
+ createdAt: number;
25
+ }
26
+ interface SessionInfo {
27
+ user: IncortaUser;
28
+ /** Epoch millis when the session cookie expires (sliding). */
29
+ expiresAt: number;
30
+ /** Epoch millis when the access token expires. */
31
+ accessTokenExpiresAt: number;
32
+ }
33
+ interface IncortaAuthConfig {
34
+ /**
35
+ * Base URL of the Incorta web application, e.g. `https://acme.cloud.incorta.com/incorta`
36
+ * or `http://localhost:8080/incorta`. Defaults to `INCORTA_URL`.
37
+ */
38
+ incortaUrl?: string;
39
+ /** Incorta tenant name, e.g. `demo`. Defaults to `INCORTA_TENANT`. */
40
+ tenant?: string;
41
+ /** OAuth client id (see `incorta-auth register`). Defaults to `INCORTA_CLIENT_ID`. */
42
+ clientId?: string;
43
+ /** OAuth client secret. Defaults to `INCORTA_CLIENT_SECRET`. */
44
+ clientSecret?: string;
45
+ /**
46
+ * Secret used to encrypt the session cookie (any long random string, >= 32 chars).
47
+ * Defaults to `INCORTA_AUTH_SECRET`.
48
+ */
49
+ secret?: string;
50
+ /**
51
+ * Path prefix the auth routes are mounted under. The SDK serves
52
+ * `{basePath}/login`, `{basePath}/callback`, `{basePath}/session`,
53
+ * `{basePath}/logout` (and optionally `{basePath}/token`).
54
+ * @default "/auth"
55
+ */
56
+ basePath?: string;
57
+ /**
58
+ * External origin of THIS app, e.g. `http://localhost:4000`. Used to build the
59
+ * OAuth callback URL and to validate `redirect_to` targets. When omitted it is
60
+ * derived per request from `x-forwarded-proto`/`x-forwarded-host`/`host`.
61
+ * Defaults to `INCORTA_APP_URL`.
62
+ */
63
+ appUrl?: string;
64
+ /** OAuth scopes to request. @default "openid profile email" */
65
+ scope?: string;
66
+ session?: {
67
+ /** @default "incorta_auth_session" */
68
+ cookieName?: string;
69
+ /** Session lifetime in seconds (sliding — renewed on activity). @default 43200 (12h) */
70
+ maxAge?: number;
71
+ };
72
+ cookies?: {
73
+ /**
74
+ * `Secure` attribute for cookies. `"auto"` sets it when the request is HTTPS.
75
+ * @default "auto"
76
+ */
77
+ secure?: boolean | "auto";
78
+ };
79
+ /**
80
+ * Expose `GET {basePath}/token` returning the raw Incorta access token to the
81
+ * browser (for calling Incorta public APIs directly from the frontend). Off by
82
+ * default — prefer proxying through your backend.
83
+ * @default false
84
+ */
85
+ exposeAccessToken?: boolean;
86
+ advanced?: {
87
+ /** Override the OIDC discovery document URL (rarely needed). */
88
+ discoveryUrl?: string;
89
+ /** Override JWKS resolution (used by tests to verify against a local key). */
90
+ jwks?: JWTVerifyGetKey;
91
+ /** Override fetch (used by tests). */
92
+ fetch?: typeof fetch;
93
+ };
94
+ }
95
+ interface ResolvedConfig {
96
+ incortaUrl: string;
97
+ tenant: string;
98
+ clientId: string;
99
+ clientSecret: string;
100
+ secret: string;
101
+ basePath: string;
102
+ appUrl?: string;
103
+ scope: string;
104
+ cookieName: string;
105
+ stateCookieName: string;
106
+ sessionMaxAge: number;
107
+ secureCookies: boolean | "auto";
108
+ exposeAccessToken: boolean;
109
+ /** `{incortaUrl}/oauth/{tenant}` — the OIDC issuer for this tenant. */
110
+ issuer: string;
111
+ discoveryUrl: string;
112
+ jwksOverride?: JWTVerifyGetKey;
113
+ fetch: typeof fetch;
114
+ }
115
+
116
+ export type { IncortaAuthConfig as I, ResolvedConfig as R, SessionInfo as S, IncortaUser as a, SessionData as b };
@@ -0,0 +1,116 @@
1
+ import { JWTVerifyGetKey } from 'jose';
2
+
3
+ /** The Incorta user identity carried by the session (claims from the ID token). */
4
+ interface IncortaUser {
5
+ /** Incorta login name (`sub` claim). */
6
+ sub: string;
7
+ name?: string;
8
+ email?: string;
9
+ /** Incorta role names, as minted into the ID token. */
10
+ roles: string[];
11
+ /** Tenant the user authenticated against. */
12
+ tenant: string;
13
+ }
14
+ /** What the sealed session cookie holds. */
15
+ interface SessionData {
16
+ user: IncortaUser;
17
+ /** Incorta-issued access token (RS256 JWT, aud = client_id). */
18
+ accessToken: string;
19
+ /** Epoch millis when the access token expires. */
20
+ accessTokenExpiresAt: number;
21
+ /** Rotating refresh token, present when the client has the refresh_token grant. */
22
+ refreshToken?: string;
23
+ /** Epoch millis when this session was first created (login time). */
24
+ createdAt: number;
25
+ }
26
+ interface SessionInfo {
27
+ user: IncortaUser;
28
+ /** Epoch millis when the session cookie expires (sliding). */
29
+ expiresAt: number;
30
+ /** Epoch millis when the access token expires. */
31
+ accessTokenExpiresAt: number;
32
+ }
33
+ interface IncortaAuthConfig {
34
+ /**
35
+ * Base URL of the Incorta web application, e.g. `https://acme.cloud.incorta.com/incorta`
36
+ * or `http://localhost:8080/incorta`. Defaults to `INCORTA_URL`.
37
+ */
38
+ incortaUrl?: string;
39
+ /** Incorta tenant name, e.g. `demo`. Defaults to `INCORTA_TENANT`. */
40
+ tenant?: string;
41
+ /** OAuth client id (see `incorta-auth register`). Defaults to `INCORTA_CLIENT_ID`. */
42
+ clientId?: string;
43
+ /** OAuth client secret. Defaults to `INCORTA_CLIENT_SECRET`. */
44
+ clientSecret?: string;
45
+ /**
46
+ * Secret used to encrypt the session cookie (any long random string, >= 32 chars).
47
+ * Defaults to `INCORTA_AUTH_SECRET`.
48
+ */
49
+ secret?: string;
50
+ /**
51
+ * Path prefix the auth routes are mounted under. The SDK serves
52
+ * `{basePath}/login`, `{basePath}/callback`, `{basePath}/session`,
53
+ * `{basePath}/logout` (and optionally `{basePath}/token`).
54
+ * @default "/auth"
55
+ */
56
+ basePath?: string;
57
+ /**
58
+ * External origin of THIS app, e.g. `http://localhost:4000`. Used to build the
59
+ * OAuth callback URL and to validate `redirect_to` targets. When omitted it is
60
+ * derived per request from `x-forwarded-proto`/`x-forwarded-host`/`host`.
61
+ * Defaults to `INCORTA_APP_URL`.
62
+ */
63
+ appUrl?: string;
64
+ /** OAuth scopes to request. @default "openid profile email" */
65
+ scope?: string;
66
+ session?: {
67
+ /** @default "incorta_auth_session" */
68
+ cookieName?: string;
69
+ /** Session lifetime in seconds (sliding — renewed on activity). @default 43200 (12h) */
70
+ maxAge?: number;
71
+ };
72
+ cookies?: {
73
+ /**
74
+ * `Secure` attribute for cookies. `"auto"` sets it when the request is HTTPS.
75
+ * @default "auto"
76
+ */
77
+ secure?: boolean | "auto";
78
+ };
79
+ /**
80
+ * Expose `GET {basePath}/token` returning the raw Incorta access token to the
81
+ * browser (for calling Incorta public APIs directly from the frontend). Off by
82
+ * default — prefer proxying through your backend.
83
+ * @default false
84
+ */
85
+ exposeAccessToken?: boolean;
86
+ advanced?: {
87
+ /** Override the OIDC discovery document URL (rarely needed). */
88
+ discoveryUrl?: string;
89
+ /** Override JWKS resolution (used by tests to verify against a local key). */
90
+ jwks?: JWTVerifyGetKey;
91
+ /** Override fetch (used by tests). */
92
+ fetch?: typeof fetch;
93
+ };
94
+ }
95
+ interface ResolvedConfig {
96
+ incortaUrl: string;
97
+ tenant: string;
98
+ clientId: string;
99
+ clientSecret: string;
100
+ secret: string;
101
+ basePath: string;
102
+ appUrl?: string;
103
+ scope: string;
104
+ cookieName: string;
105
+ stateCookieName: string;
106
+ sessionMaxAge: number;
107
+ secureCookies: boolean | "auto";
108
+ exposeAccessToken: boolean;
109
+ /** `{incortaUrl}/oauth/{tenant}` — the OIDC issuer for this tenant. */
110
+ issuer: string;
111
+ discoveryUrl: string;
112
+ jwksOverride?: JWTVerifyGetKey;
113
+ fetch: typeof fetch;
114
+ }
115
+
116
+ export type { IncortaAuthConfig as I, ResolvedConfig as R, SessionInfo as S, IncortaUser as a, SessionData as b };