@githat/nextjs 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/proxy.mjs ADDED
@@ -0,0 +1,101 @@
1
+ // src/lib/auth-handler.ts
2
+ import { NextResponse } from "next/server";
3
+ import * as jose from "jose";
4
+ function decodeJwtPayload(token) {
5
+ try {
6
+ const parts = token.split(".");
7
+ if (parts.length !== 3) return null;
8
+ const payload = JSON.parse(atob(parts[1]));
9
+ return payload;
10
+ } catch {
11
+ return null;
12
+ }
13
+ }
14
+ async function verifyJwt(token, secretKey) {
15
+ try {
16
+ const secret = new TextEncoder().encode(secretKey);
17
+ const { payload } = await jose.jwtVerify(token, secret, {
18
+ algorithms: ["HS256"]
19
+ });
20
+ return payload;
21
+ } catch {
22
+ return null;
23
+ }
24
+ }
25
+ async function handleAuthRequest(request, options = {}) {
26
+ const {
27
+ publicRoutes = ["/"],
28
+ signInUrl = "/sign-in",
29
+ tokenCookie = "githat_access",
30
+ legacyTokenCookie = "githat_access_token",
31
+ injectHeaders = false,
32
+ secretKey
33
+ } = options;
34
+ const { pathname } = request.nextUrl;
35
+ const isPublic = publicRoutes.some((route) => {
36
+ if (route.endsWith("/*")) {
37
+ const prefix = route.slice(0, -1);
38
+ return pathname === prefix.slice(0, -1) || pathname.startsWith(prefix);
39
+ }
40
+ return pathname === route;
41
+ });
42
+ if (isPublic) {
43
+ return NextResponse.next();
44
+ }
45
+ if (pathname.startsWith("/_next") || pathname.startsWith("/api") || pathname.includes(".")) {
46
+ return NextResponse.next();
47
+ }
48
+ let token = request.cookies.get(tokenCookie)?.value;
49
+ if (!token) {
50
+ token = request.cookies.get(legacyTokenCookie)?.value;
51
+ }
52
+ if (!token) {
53
+ const signInUrlObj = new URL(signInUrl, request.url);
54
+ signInUrlObj.searchParams.set("redirect_url", pathname);
55
+ return NextResponse.redirect(signInUrlObj);
56
+ }
57
+ if (!injectHeaders) {
58
+ return NextResponse.next();
59
+ }
60
+ let payload = null;
61
+ if (secretKey) {
62
+ payload = await verifyJwt(token, secretKey);
63
+ if (!payload) {
64
+ const signInUrlObj = new URL(signInUrl, request.url);
65
+ signInUrlObj.searchParams.set("redirect_url", pathname);
66
+ return NextResponse.redirect(signInUrlObj);
67
+ }
68
+ } else {
69
+ payload = decodeJwtPayload(token);
70
+ }
71
+ const response = NextResponse.next();
72
+ if (payload) {
73
+ if (payload.userId) {
74
+ response.headers.set("x-githat-user-id", String(payload.userId));
75
+ }
76
+ if (payload.email) {
77
+ response.headers.set("x-githat-email", String(payload.email));
78
+ }
79
+ if (payload.orgId) {
80
+ response.headers.set("x-githat-org-id", String(payload.orgId));
81
+ }
82
+ if (payload.orgSlug) {
83
+ response.headers.set("x-githat-org-slug", String(payload.orgSlug));
84
+ }
85
+ if (payload.orgRole) {
86
+ response.headers.set("x-githat-role", String(payload.orgRole));
87
+ }
88
+ }
89
+ return response;
90
+ }
91
+
92
+ // src/proxy/index.ts
93
+ function authProxy(options = {}) {
94
+ return async function proxy(request) {
95
+ return handleAuthRequest(request, options);
96
+ };
97
+ }
98
+ export {
99
+ authProxy
100
+ };
101
+ //# sourceMappingURL=proxy.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/auth-handler.ts","../src/proxy/index.ts"],"sourcesContent":["import { NextResponse } from 'next/server';\nimport type { NextRequest } from 'next/server';\nimport * as jose from 'jose';\n\nexport interface AuthHandlerOptions {\n /**\n * Routes that don't require authentication.\n * Supports exact paths ('/') and path prefixes ('/public/*').\n */\n publicRoutes?: string[];\n\n /**\n * URL to redirect to when authentication is required but not present.\n * @default '/sign-in'\n */\n signInUrl?: string;\n\n /**\n * Cookie name for the access token.\n * @default 'githat_access'\n */\n tokenCookie?: string;\n\n /**\n * Legacy localStorage token cookie name (for backward compatibility).\n * @default 'githat_access_token'\n */\n legacyTokenCookie?: string;\n\n /**\n * When true, decode the JWT and inject x-githat-* headers into the request.\n * This allows downstream API routes to access user/org info without re-verifying.\n *\n * Injected headers:\n * - x-githat-user-id: User's unique ID\n * - x-githat-email: User's email address\n * - x-githat-org-id: Current org ID (if any)\n * - x-githat-org-slug: Current org slug (if any)\n * - x-githat-role: User's role in the org (owner/admin/member)\n *\n * @default false\n */\n injectHeaders?: boolean;\n\n /**\n * Secret key for local JWT verification when injectHeaders is true.\n * If not provided, headers are populated from the decoded (unverified) token payload.\n * For production, always provide the secret key for full verification.\n */\n secretKey?: string;\n}\n\n/**\n * Decode a JWT without verifying the signature.\n * Used when secretKey is not provided but we still want header injection.\n */\nfunction decodeJwtPayload(token: string): Record<string, unknown> | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) return null;\n const payload = JSON.parse(atob(parts[1]));\n return payload;\n } catch {\n return null;\n }\n}\n\n/**\n * Verify a JWT and return the payload.\n * Uses jose for proper signature verification.\n */\nasync function verifyJwt(\n token: string,\n secretKey: string\n): Promise<Record<string, unknown> | null> {\n try {\n const secret = new TextEncoder().encode(secretKey);\n const { payload } = await jose.jwtVerify(token, secret, {\n algorithms: ['HS256'],\n });\n return payload as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n/**\n * Shared auth handling logic for both middleware (Next.js 14/15) and proxy (Next.js 16+).\n * Validates authentication tokens and optionally injects headers with user/org info.\n */\nexport async function handleAuthRequest(\n request: NextRequest,\n options: AuthHandlerOptions = {}\n): Promise<NextResponse> {\n const {\n publicRoutes = ['/'],\n signInUrl = '/sign-in',\n tokenCookie = 'githat_access',\n legacyTokenCookie = 'githat_access_token',\n injectHeaders = false,\n secretKey,\n } = options;\n\n const { pathname } = request.nextUrl;\n\n // Allow public routes (exact match or prefix with /*)\n const isPublic = publicRoutes.some((route) => {\n if (route.endsWith('/*')) {\n const prefix = route.slice(0, -1); // Remove the *\n return pathname === prefix.slice(0, -1) || pathname.startsWith(prefix);\n }\n return pathname === route;\n });\n\n if (isPublic) {\n return NextResponse.next();\n }\n\n // IMPORTANT: /api routes are intentionally skipped here.\n // API route protection must be handled per-route using withAuth() or getAuth()\n // from @githat/nextjs/server. This is documented in the SDK README and docs.\n if (\n pathname.startsWith('/_next') ||\n pathname.startsWith('/api') ||\n pathname.includes('.')\n ) {\n return NextResponse.next();\n }\n\n // Check for token in cookies (try new httpOnly cookie first, then legacy)\n let token = request.cookies.get(tokenCookie)?.value;\n if (!token) {\n token = request.cookies.get(legacyTokenCookie)?.value;\n }\n\n // No token — redirect to sign-in\n if (!token) {\n const signInUrlObj = new URL(signInUrl, request.url);\n signInUrlObj.searchParams.set('redirect_url', pathname);\n return NextResponse.redirect(signInUrlObj);\n }\n\n // If not injecting headers, just let the request through\n if (!injectHeaders) {\n return NextResponse.next();\n }\n\n // Decode or verify the token to inject headers\n let payload: Record<string, unknown> | null = null;\n\n if (secretKey) {\n // Full verification with secret key\n payload = await verifyJwt(token, secretKey);\n if (!payload) {\n // Token verification failed — redirect to sign-in\n const signInUrlObj = new URL(signInUrl, request.url);\n signInUrlObj.searchParams.set('redirect_url', pathname);\n return NextResponse.redirect(signInUrlObj);\n }\n } else {\n // Decode without verification (less secure, but works without secret)\n payload = decodeJwtPayload(token);\n }\n\n // Create a new response with injected headers\n const response = NextResponse.next();\n\n if (payload) {\n // Inject user/org info as headers\n if (payload.userId) {\n response.headers.set('x-githat-user-id', String(payload.userId));\n }\n if (payload.email) {\n response.headers.set('x-githat-email', String(payload.email));\n }\n if (payload.orgId) {\n response.headers.set('x-githat-org-id', String(payload.orgId));\n }\n if (payload.orgSlug) {\n response.headers.set('x-githat-org-slug', String(payload.orgSlug));\n }\n if (payload.orgRole) {\n response.headers.set('x-githat-role', String(payload.orgRole));\n }\n }\n\n return response;\n}\n","import type { NextRequest } from 'next/server';\nimport type { NextResponse } from 'next/server';\nimport { handleAuthRequest, AuthHandlerOptions } from '../lib/auth-handler';\n\n/**\n * Options for the authProxy function.\n * @see AuthHandlerOptions for detailed property documentation.\n */\nexport interface AuthProxyOptions extends AuthHandlerOptions {}\n\n/**\n * Creates an auth proxy handler for Next.js 16+.\n *\n * Next.js 16 renamed middleware.ts to proxy.ts and the export from\n * `export default middleware` to `export const proxy`.\n *\n * @example\n * ```typescript\n * // proxy.ts (Next.js 16+)\n * import { authProxy } from '@githat/nextjs/proxy';\n *\n * export const proxy = authProxy({\n * publicRoutes: ['/', '/about', '/pricing'],\n * signInUrl: '/sign-in',\n * });\n *\n * export const config = {\n * matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],\n * };\n * ```\n *\n * @param options - Configuration options for the auth proxy\n * @returns A proxy function compatible with Next.js 16+ proxy.ts convention\n */\nexport function authProxy(options: AuthProxyOptions = {}) {\n return async function proxy(request: NextRequest): Promise<NextResponse> {\n return handleAuthRequest(request, options);\n };\n}\n\n// Re-export types for convenience\nexport type { AuthProxyOptions as AuthProxyConfig };\nexport type { AuthHandlerOptions };\n"],"mappings":"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","names":[]}
@@ -0,0 +1,164 @@
1
+ /**
2
+ * @githat/nextjs/server
3
+ *
4
+ * Server-side utilities for token verification in Next.js API routes and middleware.
5
+ * This module runs on the server only — do not import in client components.
6
+ */
7
+ interface AuthPayload {
8
+ userId: string;
9
+ email: string;
10
+ orgId: string | null;
11
+ orgSlug: string | null;
12
+ role: 'owner' | 'admin' | 'member' | null;
13
+ tier: 'free' | 'basic' | 'pro' | 'enterprise' | null;
14
+ }
15
+ interface VerifyOptions {
16
+ /**
17
+ * Secret key for local JWT verification. If provided, tokens are verified
18
+ * locally without making an API call (~1ms vs ~50-100ms).
19
+ * Must match the JWT_SECRET used by the GitHat backend.
20
+ */
21
+ secretKey?: string;
22
+ /**
23
+ * API URL for remote token verification. Defaults to https://api.githat.io
24
+ */
25
+ apiUrl?: string;
26
+ }
27
+ interface OrgMetadata {
28
+ [key: string]: unknown;
29
+ }
30
+ declare const COOKIE_NAMES: {
31
+ readonly accessToken: "githat_access";
32
+ readonly refreshToken: "githat_refresh";
33
+ };
34
+ /**
35
+ * Verify a JWT token and return the decoded auth payload.
36
+ *
37
+ * Supports two verification modes:
38
+ * 1. Local verification (recommended for performance): Pass `secretKey` option
39
+ * 2. API-based verification: No secret key needed, calls api.githat.io/auth/verify
40
+ *
41
+ * @example Local verification (fast, ~1ms)
42
+ * ```ts
43
+ * const auth = await verifyToken(token, {
44
+ * secretKey: process.env.GITHAT_SECRET_KEY
45
+ * });
46
+ * ```
47
+ *
48
+ * @example API-based verification (simpler setup)
49
+ * ```ts
50
+ * const auth = await verifyToken(token);
51
+ * ```
52
+ */
53
+ declare function verifyToken(token: string, options?: VerifyOptions): Promise<AuthPayload>;
54
+ /**
55
+ * Extract and verify the auth token from a Next.js request.
56
+ * Checks cookies first (for httpOnly cookie mode), then Authorization header.
57
+ *
58
+ * Returns null if no token is found (unauthenticated request).
59
+ * Throws if a token is found but is invalid/expired.
60
+ *
61
+ * @example In a Next.js API route
62
+ * ```ts
63
+ * import { getAuth } from '@githat/nextjs/server';
64
+ *
65
+ * export async function GET(request: Request) {
66
+ * const auth = await getAuth(request, {
67
+ * secretKey: process.env.GITHAT_SECRET_KEY
68
+ * });
69
+ *
70
+ * if (!auth) {
71
+ * return Response.json({ error: 'Unauthorized' }, { status: 401 });
72
+ * }
73
+ *
74
+ * return Response.json({ userId: auth.userId });
75
+ * }
76
+ * ```
77
+ */
78
+ declare function getAuth(request: Request, options?: VerifyOptions): Promise<AuthPayload | null>;
79
+ /**
80
+ * Get organization metadata from the server.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * import { getOrgMetadata } from '@githat/nextjs/server';
85
+ *
86
+ * const meta = await getOrgMetadata(orgId, {
87
+ * token: accessToken,
88
+ * apiUrl: 'https://api.githat.io'
89
+ * });
90
+ * console.log(meta.stripeAccountId);
91
+ * ```
92
+ */
93
+ declare function getOrgMetadata(orgId: string, options: {
94
+ token: string;
95
+ apiUrl?: string;
96
+ }): Promise<OrgMetadata>;
97
+ /**
98
+ * Update organization metadata from the server.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * import { updateOrgMetadata } from '@githat/nextjs/server';
103
+ *
104
+ * await updateOrgMetadata(orgId, { stripeAccountId: 'acct_xxx' }, {
105
+ * token: accessToken,
106
+ * apiUrl: 'https://api.githat.io'
107
+ * });
108
+ * ```
109
+ */
110
+ declare function updateOrgMetadata(orgId: string, metadata: OrgMetadata, options: {
111
+ token: string;
112
+ apiUrl?: string;
113
+ }): Promise<OrgMetadata>;
114
+ /**
115
+ * Handler function that receives the request and verified auth payload.
116
+ */
117
+ type AuthenticatedHandler = (request: Request, auth: AuthPayload) => Promise<Response> | Response;
118
+ /**
119
+ * Options for the withAuth wrapper.
120
+ */
121
+ interface WithAuthOptions {
122
+ /**
123
+ * Secret key for local JWT verification.
124
+ * Defaults to process.env.GITHAT_SECRET_KEY if not provided.
125
+ */
126
+ secretKey?: string;
127
+ /**
128
+ * Custom response to return when authentication fails.
129
+ * Defaults to JSON { error: 'Unauthorized' } with status 401.
130
+ */
131
+ onUnauthorized?: () => Response;
132
+ }
133
+ /**
134
+ * Wrap an API route handler with authentication.
135
+ * The handler will only be called if the request has a valid auth token.
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * // app/api/orders/route.ts
140
+ * import { withAuth } from '@githat/nextjs/server';
141
+ *
142
+ * export const GET = withAuth(async (request, auth) => {
143
+ * // auth.userId, auth.orgId, auth.role available
144
+ * const orders = await db.orders.findMany({ where: { orgId: auth.orgId } });
145
+ * return Response.json({ orders });
146
+ * }, { secretKey: process.env.GITHAT_SECRET_KEY });
147
+ * ```
148
+ *
149
+ * @example With custom unauthorized response
150
+ * ```ts
151
+ * export const GET = withAuth(
152
+ * async (request, auth) => {
153
+ * return Response.json({ userId: auth.userId });
154
+ * },
155
+ * {
156
+ * secretKey: process.env.GITHAT_SECRET_KEY,
157
+ * onUnauthorized: () => Response.redirect('/sign-in'),
158
+ * }
159
+ * );
160
+ * ```
161
+ */
162
+ declare function withAuth(handler: AuthenticatedHandler, options?: WithAuthOptions): (request: Request) => Promise<Response>;
163
+
164
+ export { type AuthPayload, type AuthenticatedHandler, COOKIE_NAMES, type OrgMetadata, type VerifyOptions, type WithAuthOptions, getAuth, getOrgMetadata, updateOrgMetadata, verifyToken, withAuth };
@@ -0,0 +1,164 @@
1
+ /**
2
+ * @githat/nextjs/server
3
+ *
4
+ * Server-side utilities for token verification in Next.js API routes and middleware.
5
+ * This module runs on the server only — do not import in client components.
6
+ */
7
+ interface AuthPayload {
8
+ userId: string;
9
+ email: string;
10
+ orgId: string | null;
11
+ orgSlug: string | null;
12
+ role: 'owner' | 'admin' | 'member' | null;
13
+ tier: 'free' | 'basic' | 'pro' | 'enterprise' | null;
14
+ }
15
+ interface VerifyOptions {
16
+ /**
17
+ * Secret key for local JWT verification. If provided, tokens are verified
18
+ * locally without making an API call (~1ms vs ~50-100ms).
19
+ * Must match the JWT_SECRET used by the GitHat backend.
20
+ */
21
+ secretKey?: string;
22
+ /**
23
+ * API URL for remote token verification. Defaults to https://api.githat.io
24
+ */
25
+ apiUrl?: string;
26
+ }
27
+ interface OrgMetadata {
28
+ [key: string]: unknown;
29
+ }
30
+ declare const COOKIE_NAMES: {
31
+ readonly accessToken: "githat_access";
32
+ readonly refreshToken: "githat_refresh";
33
+ };
34
+ /**
35
+ * Verify a JWT token and return the decoded auth payload.
36
+ *
37
+ * Supports two verification modes:
38
+ * 1. Local verification (recommended for performance): Pass `secretKey` option
39
+ * 2. API-based verification: No secret key needed, calls api.githat.io/auth/verify
40
+ *
41
+ * @example Local verification (fast, ~1ms)
42
+ * ```ts
43
+ * const auth = await verifyToken(token, {
44
+ * secretKey: process.env.GITHAT_SECRET_KEY
45
+ * });
46
+ * ```
47
+ *
48
+ * @example API-based verification (simpler setup)
49
+ * ```ts
50
+ * const auth = await verifyToken(token);
51
+ * ```
52
+ */
53
+ declare function verifyToken(token: string, options?: VerifyOptions): Promise<AuthPayload>;
54
+ /**
55
+ * Extract and verify the auth token from a Next.js request.
56
+ * Checks cookies first (for httpOnly cookie mode), then Authorization header.
57
+ *
58
+ * Returns null if no token is found (unauthenticated request).
59
+ * Throws if a token is found but is invalid/expired.
60
+ *
61
+ * @example In a Next.js API route
62
+ * ```ts
63
+ * import { getAuth } from '@githat/nextjs/server';
64
+ *
65
+ * export async function GET(request: Request) {
66
+ * const auth = await getAuth(request, {
67
+ * secretKey: process.env.GITHAT_SECRET_KEY
68
+ * });
69
+ *
70
+ * if (!auth) {
71
+ * return Response.json({ error: 'Unauthorized' }, { status: 401 });
72
+ * }
73
+ *
74
+ * return Response.json({ userId: auth.userId });
75
+ * }
76
+ * ```
77
+ */
78
+ declare function getAuth(request: Request, options?: VerifyOptions): Promise<AuthPayload | null>;
79
+ /**
80
+ * Get organization metadata from the server.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * import { getOrgMetadata } from '@githat/nextjs/server';
85
+ *
86
+ * const meta = await getOrgMetadata(orgId, {
87
+ * token: accessToken,
88
+ * apiUrl: 'https://api.githat.io'
89
+ * });
90
+ * console.log(meta.stripeAccountId);
91
+ * ```
92
+ */
93
+ declare function getOrgMetadata(orgId: string, options: {
94
+ token: string;
95
+ apiUrl?: string;
96
+ }): Promise<OrgMetadata>;
97
+ /**
98
+ * Update organization metadata from the server.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * import { updateOrgMetadata } from '@githat/nextjs/server';
103
+ *
104
+ * await updateOrgMetadata(orgId, { stripeAccountId: 'acct_xxx' }, {
105
+ * token: accessToken,
106
+ * apiUrl: 'https://api.githat.io'
107
+ * });
108
+ * ```
109
+ */
110
+ declare function updateOrgMetadata(orgId: string, metadata: OrgMetadata, options: {
111
+ token: string;
112
+ apiUrl?: string;
113
+ }): Promise<OrgMetadata>;
114
+ /**
115
+ * Handler function that receives the request and verified auth payload.
116
+ */
117
+ type AuthenticatedHandler = (request: Request, auth: AuthPayload) => Promise<Response> | Response;
118
+ /**
119
+ * Options for the withAuth wrapper.
120
+ */
121
+ interface WithAuthOptions {
122
+ /**
123
+ * Secret key for local JWT verification.
124
+ * Defaults to process.env.GITHAT_SECRET_KEY if not provided.
125
+ */
126
+ secretKey?: string;
127
+ /**
128
+ * Custom response to return when authentication fails.
129
+ * Defaults to JSON { error: 'Unauthorized' } with status 401.
130
+ */
131
+ onUnauthorized?: () => Response;
132
+ }
133
+ /**
134
+ * Wrap an API route handler with authentication.
135
+ * The handler will only be called if the request has a valid auth token.
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * // app/api/orders/route.ts
140
+ * import { withAuth } from '@githat/nextjs/server';
141
+ *
142
+ * export const GET = withAuth(async (request, auth) => {
143
+ * // auth.userId, auth.orgId, auth.role available
144
+ * const orders = await db.orders.findMany({ where: { orgId: auth.orgId } });
145
+ * return Response.json({ orders });
146
+ * }, { secretKey: process.env.GITHAT_SECRET_KEY });
147
+ * ```
148
+ *
149
+ * @example With custom unauthorized response
150
+ * ```ts
151
+ * export const GET = withAuth(
152
+ * async (request, auth) => {
153
+ * return Response.json({ userId: auth.userId });
154
+ * },
155
+ * {
156
+ * secretKey: process.env.GITHAT_SECRET_KEY,
157
+ * onUnauthorized: () => Response.redirect('/sign-in'),
158
+ * }
159
+ * );
160
+ * ```
161
+ */
162
+ declare function withAuth(handler: AuthenticatedHandler, options?: WithAuthOptions): (request: Request) => Promise<Response>;
163
+
164
+ export { type AuthPayload, type AuthenticatedHandler, COOKIE_NAMES, type OrgMetadata, type VerifyOptions, type WithAuthOptions, getAuth, getOrgMetadata, updateOrgMetadata, verifyToken, withAuth };
package/dist/server.js ADDED
@@ -0,0 +1,203 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/server.ts
31
+ var server_exports = {};
32
+ __export(server_exports, {
33
+ COOKIE_NAMES: () => COOKIE_NAMES,
34
+ getAuth: () => getAuth,
35
+ getOrgMetadata: () => getOrgMetadata,
36
+ updateOrgMetadata: () => updateOrgMetadata,
37
+ verifyToken: () => verifyToken,
38
+ withAuth: () => withAuth
39
+ });
40
+ module.exports = __toCommonJS(server_exports);
41
+ var jose = __toESM(require("jose"));
42
+
43
+ // src/config.ts
44
+ var DEFAULT_API_URL = "https://api.githat.io";
45
+
46
+ // src/server.ts
47
+ var COOKIE_NAMES = {
48
+ accessToken: "githat_access",
49
+ refreshToken: "githat_refresh"
50
+ };
51
+ async function verifyToken(token, options = {}) {
52
+ const { secretKey, apiUrl = DEFAULT_API_URL } = options;
53
+ if (secretKey) {
54
+ return verifyTokenLocally(token, secretKey);
55
+ }
56
+ return verifyTokenViaAPI(token, apiUrl);
57
+ }
58
+ async function verifyTokenLocally(token, secretKey) {
59
+ try {
60
+ const secret = new TextEncoder().encode(secretKey);
61
+ const { payload } = await jose.jwtVerify(token, secret, {
62
+ algorithms: ["HS256"]
63
+ });
64
+ if (payload.type && payload.type !== "user") {
65
+ throw new Error("Invalid token type");
66
+ }
67
+ if (payload.tokenType !== "access") {
68
+ throw new Error("Invalid token type");
69
+ }
70
+ return {
71
+ userId: payload.userId,
72
+ email: payload.email,
73
+ orgId: payload.orgId || null,
74
+ orgSlug: payload.orgSlug || null,
75
+ role: payload.orgRole || null,
76
+ tier: null
77
+ // Tier requires DB lookup, not available in local verification
78
+ };
79
+ } catch (err) {
80
+ if (err instanceof jose.errors.JWTExpired) {
81
+ throw new Error("Token expired");
82
+ }
83
+ if (err instanceof jose.errors.JWTClaimValidationFailed) {
84
+ throw new Error("Invalid token claims");
85
+ }
86
+ if (err instanceof jose.errors.JWTInvalid) {
87
+ throw new Error("Invalid token");
88
+ }
89
+ if (err instanceof jose.errors.JWSSignatureVerificationFailed) {
90
+ throw new Error("Invalid token signature");
91
+ }
92
+ throw err;
93
+ }
94
+ }
95
+ async function verifyTokenViaAPI(token, apiUrl) {
96
+ const response = await fetch(`${apiUrl}/auth/verify`, {
97
+ method: "GET",
98
+ headers: {
99
+ Authorization: `Bearer ${token}`,
100
+ "Content-Type": "application/json"
101
+ }
102
+ });
103
+ if (!response.ok) {
104
+ const data2 = await response.json().catch(() => ({}));
105
+ throw new Error(data2.error || "Token verification failed");
106
+ }
107
+ const data = await response.json();
108
+ return {
109
+ userId: data.userId,
110
+ email: data.email,
111
+ orgId: data.orgId,
112
+ orgSlug: data.orgSlug,
113
+ role: data.role,
114
+ tier: data.tier
115
+ };
116
+ }
117
+ async function getAuth(request, options = {}) {
118
+ const cookieHeader = request.headers.get("cookie");
119
+ let token = null;
120
+ if (cookieHeader) {
121
+ const cookies = parseCookies(cookieHeader);
122
+ token = cookies[COOKIE_NAMES.accessToken] || null;
123
+ }
124
+ if (!token) {
125
+ const authHeader = request.headers.get("authorization");
126
+ if (authHeader?.startsWith("Bearer ")) {
127
+ token = authHeader.slice(7);
128
+ }
129
+ }
130
+ if (!token) {
131
+ return null;
132
+ }
133
+ return verifyToken(token, options);
134
+ }
135
+ function parseCookies(cookieHeader) {
136
+ const cookies = {};
137
+ const pairs = cookieHeader.split(";");
138
+ for (const pair of pairs) {
139
+ const [name, ...rest] = pair.trim().split("=");
140
+ if (name) {
141
+ cookies[name] = rest.join("=");
142
+ }
143
+ }
144
+ return cookies;
145
+ }
146
+ async function getOrgMetadata(orgId, options) {
147
+ const { token, apiUrl = DEFAULT_API_URL } = options;
148
+ const response = await fetch(`${apiUrl}/orgs/${orgId}/metadata`, {
149
+ method: "GET",
150
+ headers: {
151
+ Authorization: `Bearer ${token}`,
152
+ "Content-Type": "application/json"
153
+ }
154
+ });
155
+ if (!response.ok) {
156
+ const data2 = await response.json().catch(() => ({}));
157
+ throw new Error(data2.error || "Failed to get org metadata");
158
+ }
159
+ const data = await response.json();
160
+ return data.metadata || {};
161
+ }
162
+ async function updateOrgMetadata(orgId, metadata, options) {
163
+ const { token, apiUrl = DEFAULT_API_URL } = options;
164
+ const response = await fetch(`${apiUrl}/orgs/${orgId}/metadata`, {
165
+ method: "PATCH",
166
+ headers: {
167
+ Authorization: `Bearer ${token}`,
168
+ "Content-Type": "application/json"
169
+ },
170
+ body: JSON.stringify(metadata)
171
+ });
172
+ if (!response.ok) {
173
+ const data2 = await response.json().catch(() => ({}));
174
+ throw new Error(data2.error || "Failed to update org metadata");
175
+ }
176
+ const data = await response.json();
177
+ return data.metadata || {};
178
+ }
179
+ function withAuth(handler, options = {}) {
180
+ return async (request) => {
181
+ const auth = await getAuth(request, { secretKey: options.secretKey });
182
+ if (!auth) {
183
+ if (options.onUnauthorized) {
184
+ return options.onUnauthorized();
185
+ }
186
+ return new Response(JSON.stringify({ error: "Unauthorized" }), {
187
+ status: 401,
188
+ headers: { "Content-Type": "application/json" }
189
+ });
190
+ }
191
+ return handler(request, auth);
192
+ };
193
+ }
194
+ // Annotate the CommonJS export names for ESM import in node:
195
+ 0 && (module.exports = {
196
+ COOKIE_NAMES,
197
+ getAuth,
198
+ getOrgMetadata,
199
+ updateOrgMetadata,
200
+ verifyToken,
201
+ withAuth
202
+ });
203
+ //# sourceMappingURL=server.js.map