@krutai/auth 0.2.3 → 0.4.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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/index.ts"],"names":["validateApiKeyFormat","validateApiKeyWithService","betterAuth"],"mappings":";;;;;;AAiCO,IAAM,WAAN,MAAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUlB,YAAoB,MAAA,EAAwB;AAAxB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAChB,IAAA,MAAM,GAAA,GAAM,MAAA,CAAO,MAAA,IAAU,OAAA,CAAQ,IAAI,cAAA,IAAkB,EAAA;AAE3D,IAAAA,2BAAA,CAAqB,GAAG,CAAA;AACxB,IAAA,IAAA,CAAK,MAAA,GAAS,GAAA;AAGd,IAAA,IAAI,MAAA,CAAO,mBAAmB,KAAA,EAAO;AACjC,MAAA,IAAA,CAAK,oBAAA,EAAqB;AAAA,IAC9B;AAAA,EACJ;AAAA,EAnBQ,MAAA;AAAA,EACA,kBAAA,GAAkC,IAAA;AAAA,EAClC,WAAA,GAAc,KAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBtB,MAAM,UAAA,GAA4B;AAC9B,IAAA,IAAI,KAAK,WAAA,EAAa;AAClB,MAAA;AAAA,IACJ;AAGA,IAAA,IAAI,IAAA,CAAK,MAAA,CAAO,cAAA,KAAmB,KAAA,EAAO;AACtC,MAAA,MAAMC,gCAAA,CAA0B,IAAA,CAAK,MAAA,EAAQ,IAAA,CAAK,OAAO,SAAS,CAAA;AAAA,IACtE;AAEA,IAAA,IAAA,CAAK,oBAAA,EAAqB;AAC1B,IAAA,IAAA,CAAK,WAAA,GAAc,IAAA;AAAA,EACvB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,oBAAA,GAA6B;AACjC,IAAA,IAAA,CAAK,qBAAqBC,qBAAA,CAAW;AAAA,MACjC,GAAG,KAAK,MAAA,CAAO;AAAA,KAClB,CAAA;AAAA,EACL;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAA,GAAsB;AAClB,IAAA,IAAI,CAAC,KAAK,kBAAA,EAAoB;AAC1B,MAAA,MAAM,IAAI,KAAA;AAAA,QACN;AAAA,OACJ;AAAA,IACJ;AACA,IAAA,OAAO,IAAA,CAAK,kBAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA,EAKA,aAAA,GAAyB;AACrB,IAAA,OAAO,IAAA,CAAK,WAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,SAAA,GAAoB;AAChB,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,MAAA,GAAwB;AAC1B,IAAA,OAAO,KAAK,aAAA,EAAc;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,OAAA,GAAyB;AAC3B,IAAA,OAAO,KAAK,aAAA,EAAc;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,UAAA,GAA4B;AAC9B,IAAA,OAAO,KAAK,aAAA,EAAc;AAAA,EAC9B;AACJ;ACtFO,SAAS,SAAS,OAAA,EAA4B;AACjD,EAAA,OAAOA,sBAAW,OAAO,CAAA;AAC7B;AAgBO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["import { betterAuth } from 'better-auth';\nimport type { Auth } from 'better-auth';\nimport type { KrutAuthConfig } from './types';\n// Import validation from krutai peer dependency\nimport {\n validateApiKeyFormat,\n validateApiKeyWithService,\n} from 'krutai';\n\n/**\n * KrutAuth - Authentication client for KrutAI\n *\n * This class wraps Better Auth and adds API key validation\n * to ensure only authorized users can access authentication features.\n *\n * @example\n * ```typescript\n * import { KrutAuth } from '@krutai/auth';\n *\n * const auth = new KrutAuth({\n * apiKey: 'your-api-key-here',\n * betterAuthOptions: {\n * // Better Auth configuration\n * }\n * });\n *\n * // Initialize the client (validates API key)\n * await auth.initialize();\n *\n * // Use authentication features\n * const betterAuth = auth.getBetterAuth();\n * ```\n */\nexport class KrutAuth {\n private apiKey: string;\n private betterAuthInstance: Auth | null = null;\n private initialized = false;\n\n /**\n * Creates a new KrutAuth instance\n * @param config - Configuration options\n * @throws {ApiKeyValidationError} If API key is invalid\n */\n constructor(private config: KrutAuthConfig) {\n const key = config.apiKey || process.env.KRUTAI_API_KEY || '';\n // Validate API key format immediately\n validateApiKeyFormat(key);\n this.apiKey = key;\n\n // Initialize if validation is not required on init\n if (config.validateOnInit === false) {\n this.initializeBetterAuth();\n }\n }\n\n /**\n * Initialize the authentication client\n * Validates the API key and sets up Better Auth\n * @throws {ApiKeyValidationError} If API key validation fails\n */\n async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n // Validate API key with service if needed\n if (this.config.validateOnInit !== false) {\n await validateApiKeyWithService(this.apiKey, this.config.serverUrl);\n }\n\n this.initializeBetterAuth();\n this.initialized = true;\n }\n\n /**\n * Initialize Better Auth instance\n * @private\n */\n private initializeBetterAuth(): void {\n this.betterAuthInstance = betterAuth({\n ...this.config.betterAuthOptions,\n });\n }\n\n /**\n * Get the Better Auth instance\n * @throws {Error} If not initialized\n */\n getBetterAuth(): Auth {\n if (!this.betterAuthInstance) {\n throw new Error(\n 'KrutAuth not initialized. Call initialize() first or set validateOnInit to false.'\n );\n }\n return this.betterAuthInstance;\n }\n\n /**\n * Check if the client is initialized\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the API key (useful for making authenticated requests)\n * @returns The API key\n */\n getApiKey(): string {\n return this.apiKey;\n }\n\n /**\n * Sign in a user\n * This is a convenience method that wraps Better Auth\n * You can access the full Better Auth API via getBetterAuth()\n */\n async signIn(): Promise<Auth> {\n return this.getBetterAuth();\n }\n\n /**\n * Sign out the current user\n * You can access the full Better Auth API via getBetterAuth()\n */\n async signOut(): Promise<Auth> {\n return this.getBetterAuth();\n }\n\n /**\n * Get the current session\n * You can access the full Better Auth API via getBetterAuth()\n */\n async getSession(): Promise<Auth> {\n return this.getBetterAuth();\n }\n}\n","/**\n * @krutai/auth - Authentication package for KrutAI\n *\n * Requires `krutai` as a peer dependency (installed automatically).\n *\n * @example Server-side (Next.js API route / server component)\n * ```typescript\n * import { krutAuth } from \"@krutai/auth\";\n * import Database from \"better-sqlite3\";\n *\n * export const auth = krutAuth({\n * database: new Database(\"./sqlite.db\"),\n * emailAndPassword: { enabled: true },\n * baseURL: process.env.BETTER_AUTH_BASE_URL ?? \"http://localhost:3000\",\n * });\n * ```\n *\n * @example Client-side (React / Next.js client component)\n * ```typescript\n * import { createAuthClient } from \"@krutai/auth/react\";\n *\n * export const authClient = createAuthClient({\n * baseURL: process.env.NEXT_PUBLIC_APP_URL ?? \"http://localhost:3000\",\n * });\n *\n * export const { signIn, signUp, signOut, useSession } = authClient;\n * ```\n *\n * @packageDocumentation\n */\n\nimport { betterAuth } from 'better-auth';\nimport type { BetterAuthOptions } from 'better-auth';\n\n/**\n * krutAuth — drop-in replacement for betterAuth.\n *\n * Use this instead of importing betterAuth directly.\n *\n * @example\n * ```typescript\n * import { krutAuth } from \"@krutai/auth\";\n * import Database from \"better-sqlite3\";\n *\n * export const auth = krutAuth({\n * database: new Database(\"./sqlite.db\"),\n * emailAndPassword: { enabled: true },\n * });\n * ```\n */\nexport function krutAuth(options: BetterAuthOptions) {\n return betterAuth(options);\n}\n\n// Export main KrutAuth class (API-key-protected wrapper)\nexport { KrutAuth } from './client';\n\n// Export types\nexport type { KrutAuthConfig, AuthSession, BetterAuthOptions } from './types';\n\n// Re-export minimal validator utilities (format/length check only)\nexport {\n validateApiKeyFormat,\n validateApiKeyWithService,\n ApiKeyValidationError,\n} from 'krutai';\n\n// Package metadata\nexport const VERSION = '0.1.9';\n"]}
1
+ {"version":3,"sources":["../src/types.ts","../src/client.ts","../src/index.ts"],"names":["validateApiKeyFormat","validateApiKey"],"mappings":";;;;;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O,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * Types for @krutai/auth\n *\n * Pure fetch-based auth client — no local better-auth dependency.\n */\n\n/**\n * Default base URL for the KrutAI server.\n * Used when no serverUrl is provided in the config.\n */\nexport const DEFAULT_SERVER_URL = 'http://localhost:8000' as const;\n\n/**\n * Default path prefix for the auth routes on the server.\n * The server mounts better-auth under this prefix.\n */\nexport const DEFAULT_AUTH_PREFIX = '/lib-auth' as const;\n\n/**\n * Configuration options for KrutAuth\n */\nexport interface KrutAuthConfig {\n /**\n * KrutAI API key.\n * Validated against the server before use.\n * Optional: defaults to process.env.KRUTAI_API_KEY\n */\n apiKey?: string;\n\n /**\n * Base URL of your deployed KrutAI server.\n * @default \"http://localhost:8000\"\n * @example \"https://krut.ai\"\n */\n serverUrl?: string;\n\n /**\n * Path prefix for the auth routes on the server.\n * @default \"/lib-auth\"\n */\n authPrefix?: string;\n\n /**\n * Whether to validate the API key against the server on initialization.\n * Set to false to skip the validation round-trip (e.g. in tests).\n * @default true\n */\n validateOnInit?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Auth method parameter types\n// ---------------------------------------------------------------------------\n\n/**\n * Parameters for email/password sign-up\n */\nexport interface SignUpEmailParams {\n /** User email */\n email: string;\n /** User password */\n password: string;\n /** Display name */\n name: string;\n}\n\n/**\n * Parameters for email/password sign-in\n */\nexport interface SignInEmailParams {\n /** User email */\n email: string;\n /** User password */\n password: string;\n}\n\n// ---------------------------------------------------------------------------\n// Auth response types\n// ---------------------------------------------------------------------------\n\n/**\n * A user record returned by the auth server\n */\nexport interface AuthUser {\n id: string;\n email: string;\n name?: string;\n emailVerified: boolean;\n createdAt: string;\n updatedAt: string;\n [key: string]: unknown;\n}\n\n/**\n * A session record returned by the auth server\n */\nexport interface AuthSessionRecord {\n id: string;\n userId: string;\n token: string;\n expiresAt: string;\n [key: string]: unknown;\n}\n\n/**\n * Combined session + user response\n */\nexport interface AuthSession {\n user: AuthUser;\n session: AuthSessionRecord;\n}\n\n/**\n * Sign-up / sign-in response (contains token + user)\n */\nexport interface AuthResponse {\n token: string;\n user: AuthUser;\n [key: string]: unknown;\n}\n","import type {\n KrutAuthConfig,\n SignUpEmailParams,\n SignInEmailParams,\n AuthSession,\n AuthResponse,\n} from './types';\nimport { DEFAULT_SERVER_URL, DEFAULT_AUTH_PREFIX } from './types';\nimport {\n validateApiKey,\n validateApiKeyFormat,\n KrutAIKeyValidationError,\n} from 'krutai';\n\nexport { KrutAIKeyValidationError };\n\n/**\n * KrutAuth — fetch-based authentication client for KrutAI\n *\n * Calls your deployed server's `/lib-auth` routes for all auth operations.\n * The API key is validated against the server before use.\n *\n * @example\n * ```typescript\n * import { KrutAuth } from '@krutai/auth';\n *\n * const auth = new KrutAuth({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n *\n * await auth.initialize(); // validates key against server\n *\n * // Sign up\n * const { token, user } = await auth.signUpEmail({\n * email: 'user@example.com',\n * password: 'secret123',\n * name: 'Alice',\n * });\n *\n * // Sign in\n * const result = await auth.signInEmail({\n * email: 'user@example.com',\n * password: 'secret123',\n * });\n *\n * // Get session\n * const session = await auth.getSession(result.token);\n * ```\n */\nexport class KrutAuth {\n private readonly apiKey: string;\n private readonly serverUrl: string;\n private readonly authPrefix: string;\n private readonly config: KrutAuthConfig;\n\n private initialized = false;\n\n constructor(config: KrutAuthConfig) {\n this.config = config;\n this.apiKey = config.apiKey || process.env.KRUTAI_API_KEY || '';\n this.serverUrl = (config.serverUrl ?? DEFAULT_SERVER_URL).replace(/\\/$/, '');\n this.authPrefix = (config.authPrefix ?? DEFAULT_AUTH_PREFIX).replace(/\\/$/, '');\n\n // Basic format check immediately on construction\n validateApiKeyFormat(this.apiKey);\n\n // If validation is disabled, mark as ready immediately\n if (config.validateOnInit === false) {\n this.initialized = true;\n }\n }\n\n /**\n * Initialize the auth client.\n * Validates the API key against the server, then marks client as ready.\n *\n * @throws {KrutAuthKeyValidationError} if the key is rejected or the server is unreachable\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n if (this.config.validateOnInit !== false) {\n await validateApiKey(this.apiKey, this.serverUrl);\n }\n\n this.initialized = true;\n }\n\n /**\n * Returns whether the client has been initialized.\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private assertInitialized(): void {\n if (!this.initialized) {\n throw new Error(\n 'KrutAuth not initialized. Call initialize() first or set validateOnInit to false.'\n );\n }\n }\n\n /** Common request headers sent to the server on every auth call. */\n private authHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'x-api-key': this.apiKey,\n };\n }\n\n /**\n * Build the full URL for an auth endpoint.\n * @param path - The better-auth sub-path, e.g. `/api/auth/sign-up/email`\n */\n private url(path: string): string {\n const cleanPath = path.startsWith('/') ? path : `/${path}`;\n return `${this.serverUrl}${this.authPrefix}${cleanPath}`;\n }\n\n // ---------------------------------------------------------------------------\n // Public Auth Methods\n // ---------------------------------------------------------------------------\n\n /**\n * Generic request helper for any better-auth endpoint.\n *\n * Use this to call endpoints not covered by the convenience methods.\n *\n * @param method - HTTP method (GET, POST, etc.)\n * @param path - The better-auth endpoint path (e.g. `/api/auth/sign-up/email`)\n * @param body - Optional JSON body\n * @returns The parsed JSON response\n */\n async request<T = unknown>(\n method: string,\n path: string,\n body?: Record<string, unknown> | object\n ): Promise<T> {\n this.assertInitialized();\n\n const options: RequestInit = {\n method,\n headers: this.authHeaders(),\n };\n\n if (body && method !== 'GET') {\n options.body = JSON.stringify(body);\n }\n\n const response = await fetch(this.url(path), options);\n\n if (!response.ok) {\n let errorMessage = `Auth server returned HTTP ${response.status} for ${path}`;\n try {\n const errorData = (await response.json()) as { message?: string; error?: string };\n if (errorData?.error) errorMessage = errorData.error;\n else if (errorData?.message) errorMessage = errorData.message;\n } catch { }\n throw new Error(errorMessage);\n }\n\n return (await response.json()) as T;\n }\n\n /**\n * Sign up a new user with email and password.\n *\n * Calls: POST {serverUrl}/lib-auth/api/auth/sign-up/email\n *\n * @param params - Sign-up parameters (email, password, name)\n * @returns The auth response containing token and user\n */\n async signUpEmail(params: SignUpEmailParams): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/auth/sign-up/email', params);\n }\n\n /**\n * Sign in with email and password.\n *\n * Calls: POST {serverUrl}/lib-auth/api/auth/sign-in/email\n *\n * @param params - Sign-in parameters (email, password)\n * @returns The auth response containing token and user\n */\n async signInEmail(params: SignInEmailParams): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/auth/sign-in/email', params);\n }\n\n /**\n * Get the current session for a user.\n *\n * Calls: GET {serverUrl}/lib-auth/api/auth/get-session\n *\n * @param sessionToken - The session token (Bearer token from sign-in)\n * @returns The session containing user and session data\n */\n async getSession(sessionToken: string): Promise<AuthSession> {\n this.assertInitialized();\n\n const response = await fetch(this.url('/api/auth/get-session'), {\n method: 'GET',\n headers: {\n ...this.authHeaders(),\n Cookie: `better-auth.session_token=${sessionToken}`,\n },\n });\n\n if (!response.ok) {\n let errorMessage = `Auth server returned HTTP ${response.status} for /api/auth/get-session`;\n try {\n const errorData = (await response.json()) as { message?: string; error?: string };\n if (errorData?.error) errorMessage = errorData.error;\n else if (errorData?.message) errorMessage = errorData.message;\n } catch { }\n throw new Error(errorMessage);\n }\n\n return (await response.json()) as AuthSession;\n }\n\n /**\n * Sign out the current user.\n *\n * Calls: POST {serverUrl}/lib-auth/api/auth/sign-out\n *\n * @param sessionToken - The session token to invalidate\n */\n async signOut(sessionToken: string): Promise<void> {\n this.assertInitialized();\n\n const response = await fetch(this.url('/api/auth/sign-out'), {\n method: 'POST',\n headers: {\n ...this.authHeaders(),\n Cookie: `better-auth.session_token=${sessionToken}`,\n },\n });\n\n if (!response.ok) {\n let errorMessage = `Auth server returned HTTP ${response.status} for /api/auth/sign-out`;\n try {\n const errorData = (await response.json()) as { message?: string; error?: string };\n if (errorData?.error) errorMessage = errorData.error;\n else if (errorData?.message) errorMessage = errorData.message;\n } catch { }\n throw new Error(errorMessage);\n }\n }\n}\n","/**\n * @krutai/auth — Authentication package for KrutAI\n *\n * A fetch-based wrapper that calls your deployed server's `/lib-auth` routes.\n * The user's API key is validated against the server before any auth call is made.\n *\n * @example Basic usage\n * ```typescript\n * import { krutAuth } from '@krutai/auth';\n *\n * const auth = krutAuth({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n *\n * await auth.initialize(); // validates key with server\n *\n * const { token, user } = await auth.signUpEmail({\n * email: 'user@example.com',\n * password: 'secret123',\n * name: 'Alice',\n * });\n * ```\n *\n * @example Sign in\n * ```typescript\n * const auth = krutAuth({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n * await auth.initialize();\n *\n * const { token, user } = await auth.signInEmail({\n * email: 'user@example.com',\n * password: 'secret123',\n * });\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { KrutAuthConfig } from './types';\nimport { KrutAuth } from './client';\n\nexport { KrutAuth } from './client';\nexport { KrutAIKeyValidationError } from './client';\nexport {\n validateApiKey,\n validateApiKeyFormat,\n} from 'krutai';\nexport type {\n KrutAuthConfig,\n SignUpEmailParams,\n SignInEmailParams,\n AuthSession,\n AuthSessionRecord,\n AuthUser,\n AuthResponse,\n} from './types';\nexport { DEFAULT_SERVER_URL, DEFAULT_AUTH_PREFIX } from './types';\n\n/**\n * krutAuth — convenience factory.\n *\n * Creates a `KrutAuth` instance configured to call your server's `/lib-auth` routes.\n *\n * @param config - Auth configuration (`apiKey` and `serverUrl` are required)\n * @returns A `KrutAuth` instance — call `.initialize()` before use\n *\n * @example\n * ```typescript\n * import { krutAuth } from '@krutai/auth';\n *\n * const auth = krutAuth({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n *\n * await auth.initialize();\n * const { token, user } = await auth.signInEmail({\n * email: 'user@example.com',\n * password: 'secret123',\n * });\n * ```\n */\nexport function krutAuth(config: KrutAuthConfig): KrutAuth {\n return new KrutAuth(config);\n}\n\n// Package metadata\nexport const VERSION = '0.4.0';\n"]}
package/dist/index.mjs CHANGED
@@ -1,103 +1,189 @@
1
- import { betterAuth } from 'better-auth';
2
- import { validateApiKeyFormat, validateApiKeyWithService } from 'krutai';
3
- export { ApiKeyValidationError, validateApiKeyFormat, validateApiKeyWithService } from 'krutai';
1
+ import { validateApiKeyFormat, validateApiKey } from 'krutai';
2
+ export { KrutAIKeyValidationError, validateApiKey, validateApiKeyFormat } from 'krutai';
4
3
 
5
- // src/index.ts
4
+ // src/types.ts
5
+ var DEFAULT_SERVER_URL = "http://localhost:8000";
6
+ var DEFAULT_AUTH_PREFIX = "/lib-auth";
6
7
  var KrutAuth = class {
7
- /**
8
- * Creates a new KrutAuth instance
9
- * @param config - Configuration options
10
- * @throws {ApiKeyValidationError} If API key is invalid
11
- */
8
+ apiKey;
9
+ serverUrl;
10
+ authPrefix;
11
+ config;
12
+ initialized = false;
12
13
  constructor(config) {
13
14
  this.config = config;
14
- const key = config.apiKey || process.env.KRUTAI_API_KEY || "";
15
- validateApiKeyFormat(key);
16
- this.apiKey = key;
15
+ this.apiKey = config.apiKey || process.env.KRUTAI_API_KEY || "";
16
+ this.serverUrl = (config.serverUrl ?? DEFAULT_SERVER_URL).replace(/\/$/, "");
17
+ this.authPrefix = (config.authPrefix ?? DEFAULT_AUTH_PREFIX).replace(/\/$/, "");
18
+ validateApiKeyFormat(this.apiKey);
17
19
  if (config.validateOnInit === false) {
18
- this.initializeBetterAuth();
20
+ this.initialized = true;
19
21
  }
20
22
  }
21
- apiKey;
22
- betterAuthInstance = null;
23
- initialized = false;
24
23
  /**
25
- * Initialize the authentication client
26
- * Validates the API key and sets up Better Auth
27
- * @throws {ApiKeyValidationError} If API key validation fails
24
+ * Initialize the auth client.
25
+ * Validates the API key against the server, then marks client as ready.
26
+ *
27
+ * @throws {KrutAuthKeyValidationError} if the key is rejected or the server is unreachable
28
28
  */
29
29
  async initialize() {
30
- if (this.initialized) {
31
- return;
32
- }
30
+ if (this.initialized) return;
33
31
  if (this.config.validateOnInit !== false) {
34
- await validateApiKeyWithService(this.apiKey, this.config.serverUrl);
32
+ await validateApiKey(this.apiKey, this.serverUrl);
35
33
  }
36
- this.initializeBetterAuth();
37
34
  this.initialized = true;
38
35
  }
39
36
  /**
40
- * Initialize Better Auth instance
41
- * @private
37
+ * Returns whether the client has been initialized.
42
38
  */
43
- initializeBetterAuth() {
44
- this.betterAuthInstance = betterAuth({
45
- ...this.config.betterAuthOptions
46
- });
39
+ isInitialized() {
40
+ return this.initialized;
47
41
  }
48
- /**
49
- * Get the Better Auth instance
50
- * @throws {Error} If not initialized
51
- */
52
- getBetterAuth() {
53
- if (!this.betterAuthInstance) {
42
+ // ---------------------------------------------------------------------------
43
+ // Private helpers
44
+ // ---------------------------------------------------------------------------
45
+ assertInitialized() {
46
+ if (!this.initialized) {
54
47
  throw new Error(
55
48
  "KrutAuth not initialized. Call initialize() first or set validateOnInit to false."
56
49
  );
57
50
  }
58
- return this.betterAuthInstance;
51
+ }
52
+ /** Common request headers sent to the server on every auth call. */
53
+ authHeaders() {
54
+ return {
55
+ "Content-Type": "application/json",
56
+ Authorization: `Bearer ${this.apiKey}`,
57
+ "x-api-key": this.apiKey
58
+ };
59
59
  }
60
60
  /**
61
- * Check if the client is initialized
61
+ * Build the full URL for an auth endpoint.
62
+ * @param path - The better-auth sub-path, e.g. `/api/auth/sign-up/email`
62
63
  */
63
- isInitialized() {
64
- return this.initialized;
64
+ url(path) {
65
+ const cleanPath = path.startsWith("/") ? path : `/${path}`;
66
+ return `${this.serverUrl}${this.authPrefix}${cleanPath}`;
67
+ }
68
+ // ---------------------------------------------------------------------------
69
+ // Public Auth Methods
70
+ // ---------------------------------------------------------------------------
71
+ /**
72
+ * Generic request helper for any better-auth endpoint.
73
+ *
74
+ * Use this to call endpoints not covered by the convenience methods.
75
+ *
76
+ * @param method - HTTP method (GET, POST, etc.)
77
+ * @param path - The better-auth endpoint path (e.g. `/api/auth/sign-up/email`)
78
+ * @param body - Optional JSON body
79
+ * @returns The parsed JSON response
80
+ */
81
+ async request(method, path, body) {
82
+ this.assertInitialized();
83
+ const options = {
84
+ method,
85
+ headers: this.authHeaders()
86
+ };
87
+ if (body && method !== "GET") {
88
+ options.body = JSON.stringify(body);
89
+ }
90
+ const response = await fetch(this.url(path), options);
91
+ if (!response.ok) {
92
+ let errorMessage = `Auth server returned HTTP ${response.status} for ${path}`;
93
+ try {
94
+ const errorData = await response.json();
95
+ if (errorData?.error) errorMessage = errorData.error;
96
+ else if (errorData?.message) errorMessage = errorData.message;
97
+ } catch {
98
+ }
99
+ throw new Error(errorMessage);
100
+ }
101
+ return await response.json();
65
102
  }
66
103
  /**
67
- * Get the API key (useful for making authenticated requests)
68
- * @returns The API key
104
+ * Sign up a new user with email and password.
105
+ *
106
+ * Calls: POST {serverUrl}/lib-auth/api/auth/sign-up/email
107
+ *
108
+ * @param params - Sign-up parameters (email, password, name)
109
+ * @returns The auth response containing token and user
69
110
  */
70
- getApiKey() {
71
- return this.apiKey;
111
+ async signUpEmail(params) {
112
+ return this.request("POST", "/api/auth/sign-up/email", params);
72
113
  }
73
114
  /**
74
- * Sign in a user
75
- * This is a convenience method that wraps Better Auth
76
- * You can access the full Better Auth API via getBetterAuth()
115
+ * Sign in with email and password.
116
+ *
117
+ * Calls: POST {serverUrl}/lib-auth/api/auth/sign-in/email
118
+ *
119
+ * @param params - Sign-in parameters (email, password)
120
+ * @returns The auth response containing token and user
77
121
  */
78
- async signIn() {
79
- return this.getBetterAuth();
122
+ async signInEmail(params) {
123
+ return this.request("POST", "/api/auth/sign-in/email", params);
80
124
  }
81
125
  /**
82
- * Sign out the current user
83
- * You can access the full Better Auth API via getBetterAuth()
126
+ * Get the current session for a user.
127
+ *
128
+ * Calls: GET {serverUrl}/lib-auth/api/auth/get-session
129
+ *
130
+ * @param sessionToken - The session token (Bearer token from sign-in)
131
+ * @returns The session containing user and session data
84
132
  */
85
- async signOut() {
86
- return this.getBetterAuth();
133
+ async getSession(sessionToken) {
134
+ this.assertInitialized();
135
+ const response = await fetch(this.url("/api/auth/get-session"), {
136
+ method: "GET",
137
+ headers: {
138
+ ...this.authHeaders(),
139
+ Cookie: `better-auth.session_token=${sessionToken}`
140
+ }
141
+ });
142
+ if (!response.ok) {
143
+ let errorMessage = `Auth server returned HTTP ${response.status} for /api/auth/get-session`;
144
+ try {
145
+ const errorData = await response.json();
146
+ if (errorData?.error) errorMessage = errorData.error;
147
+ else if (errorData?.message) errorMessage = errorData.message;
148
+ } catch {
149
+ }
150
+ throw new Error(errorMessage);
151
+ }
152
+ return await response.json();
87
153
  }
88
154
  /**
89
- * Get the current session
90
- * You can access the full Better Auth API via getBetterAuth()
155
+ * Sign out the current user.
156
+ *
157
+ * Calls: POST {serverUrl}/lib-auth/api/auth/sign-out
158
+ *
159
+ * @param sessionToken - The session token to invalidate
91
160
  */
92
- async getSession() {
93
- return this.getBetterAuth();
161
+ async signOut(sessionToken) {
162
+ this.assertInitialized();
163
+ const response = await fetch(this.url("/api/auth/sign-out"), {
164
+ method: "POST",
165
+ headers: {
166
+ ...this.authHeaders(),
167
+ Cookie: `better-auth.session_token=${sessionToken}`
168
+ }
169
+ });
170
+ if (!response.ok) {
171
+ let errorMessage = `Auth server returned HTTP ${response.status} for /api/auth/sign-out`;
172
+ try {
173
+ const errorData = await response.json();
174
+ if (errorData?.error) errorMessage = errorData.error;
175
+ else if (errorData?.message) errorMessage = errorData.message;
176
+ } catch {
177
+ }
178
+ throw new Error(errorMessage);
179
+ }
94
180
  }
95
181
  };
96
- function krutAuth(options) {
97
- return betterAuth(options);
182
+ function krutAuth(config) {
183
+ return new KrutAuth(config);
98
184
  }
99
- var VERSION = "0.1.9";
185
+ var VERSION = "0.4.0";
100
186
 
101
- export { KrutAuth, VERSION, krutAuth };
187
+ export { DEFAULT_AUTH_PREFIX, DEFAULT_SERVER_URL, KrutAuth, VERSION, krutAuth };
102
188
  //# sourceMappingURL=index.mjs.map
103
189
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/index.ts"],"names":["betterAuth"],"mappings":";;;;;AAiCO,IAAM,WAAN,MAAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUlB,YAAoB,MAAA,EAAwB;AAAxB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAChB,IAAA,MAAM,GAAA,GAAM,MAAA,CAAO,MAAA,IAAU,OAAA,CAAQ,IAAI,cAAA,IAAkB,EAAA;AAE3D,IAAA,oBAAA,CAAqB,GAAG,CAAA;AACxB,IAAA,IAAA,CAAK,MAAA,GAAS,GAAA;AAGd,IAAA,IAAI,MAAA,CAAO,mBAAmB,KAAA,EAAO;AACjC,MAAA,IAAA,CAAK,oBAAA,EAAqB;AAAA,IAC9B;AAAA,EACJ;AAAA,EAnBQ,MAAA;AAAA,EACA,kBAAA,GAAkC,IAAA;AAAA,EAClC,WAAA,GAAc,KAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBtB,MAAM,UAAA,GAA4B;AAC9B,IAAA,IAAI,KAAK,WAAA,EAAa;AAClB,MAAA;AAAA,IACJ;AAGA,IAAA,IAAI,IAAA,CAAK,MAAA,CAAO,cAAA,KAAmB,KAAA,EAAO;AACtC,MAAA,MAAM,yBAAA,CAA0B,IAAA,CAAK,MAAA,EAAQ,IAAA,CAAK,OAAO,SAAS,CAAA;AAAA,IACtE;AAEA,IAAA,IAAA,CAAK,oBAAA,EAAqB;AAC1B,IAAA,IAAA,CAAK,WAAA,GAAc,IAAA;AAAA,EACvB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,oBAAA,GAA6B;AACjC,IAAA,IAAA,CAAK,qBAAqB,UAAA,CAAW;AAAA,MACjC,GAAG,KAAK,MAAA,CAAO;AAAA,KAClB,CAAA;AAAA,EACL;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAA,GAAsB;AAClB,IAAA,IAAI,CAAC,KAAK,kBAAA,EAAoB;AAC1B,MAAA,MAAM,IAAI,KAAA;AAAA,QACN;AAAA,OACJ;AAAA,IACJ;AACA,IAAA,OAAO,IAAA,CAAK,kBAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA,EAKA,aAAA,GAAyB;AACrB,IAAA,OAAO,IAAA,CAAK,WAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,SAAA,GAAoB;AAChB,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,MAAA,GAAwB;AAC1B,IAAA,OAAO,KAAK,aAAA,EAAc;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,OAAA,GAAyB;AAC3B,IAAA,OAAO,KAAK,aAAA,EAAc;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,UAAA,GAA4B;AAC9B,IAAA,OAAO,KAAK,aAAA,EAAc;AAAA,EAC9B;AACJ;ACtFO,SAAS,SAAS,OAAA,EAA4B;AACjD,EAAA,OAAOA,WAAW,OAAO,CAAA;AAC7B;AAgBO,IAAM,OAAA,GAAU","file":"index.mjs","sourcesContent":["import { betterAuth } from 'better-auth';\nimport type { Auth } from 'better-auth';\nimport type { KrutAuthConfig } from './types';\n// Import validation from krutai peer dependency\nimport {\n validateApiKeyFormat,\n validateApiKeyWithService,\n} from 'krutai';\n\n/**\n * KrutAuth - Authentication client for KrutAI\n *\n * This class wraps Better Auth and adds API key validation\n * to ensure only authorized users can access authentication features.\n *\n * @example\n * ```typescript\n * import { KrutAuth } from '@krutai/auth';\n *\n * const auth = new KrutAuth({\n * apiKey: 'your-api-key-here',\n * betterAuthOptions: {\n * // Better Auth configuration\n * }\n * });\n *\n * // Initialize the client (validates API key)\n * await auth.initialize();\n *\n * // Use authentication features\n * const betterAuth = auth.getBetterAuth();\n * ```\n */\nexport class KrutAuth {\n private apiKey: string;\n private betterAuthInstance: Auth | null = null;\n private initialized = false;\n\n /**\n * Creates a new KrutAuth instance\n * @param config - Configuration options\n * @throws {ApiKeyValidationError} If API key is invalid\n */\n constructor(private config: KrutAuthConfig) {\n const key = config.apiKey || process.env.KRUTAI_API_KEY || '';\n // Validate API key format immediately\n validateApiKeyFormat(key);\n this.apiKey = key;\n\n // Initialize if validation is not required on init\n if (config.validateOnInit === false) {\n this.initializeBetterAuth();\n }\n }\n\n /**\n * Initialize the authentication client\n * Validates the API key and sets up Better Auth\n * @throws {ApiKeyValidationError} If API key validation fails\n */\n async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n // Validate API key with service if needed\n if (this.config.validateOnInit !== false) {\n await validateApiKeyWithService(this.apiKey, this.config.serverUrl);\n }\n\n this.initializeBetterAuth();\n this.initialized = true;\n }\n\n /**\n * Initialize Better Auth instance\n * @private\n */\n private initializeBetterAuth(): void {\n this.betterAuthInstance = betterAuth({\n ...this.config.betterAuthOptions,\n });\n }\n\n /**\n * Get the Better Auth instance\n * @throws {Error} If not initialized\n */\n getBetterAuth(): Auth {\n if (!this.betterAuthInstance) {\n throw new Error(\n 'KrutAuth not initialized. Call initialize() first or set validateOnInit to false.'\n );\n }\n return this.betterAuthInstance;\n }\n\n /**\n * Check if the client is initialized\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get the API key (useful for making authenticated requests)\n * @returns The API key\n */\n getApiKey(): string {\n return this.apiKey;\n }\n\n /**\n * Sign in a user\n * This is a convenience method that wraps Better Auth\n * You can access the full Better Auth API via getBetterAuth()\n */\n async signIn(): Promise<Auth> {\n return this.getBetterAuth();\n }\n\n /**\n * Sign out the current user\n * You can access the full Better Auth API via getBetterAuth()\n */\n async signOut(): Promise<Auth> {\n return this.getBetterAuth();\n }\n\n /**\n * Get the current session\n * You can access the full Better Auth API via getBetterAuth()\n */\n async getSession(): Promise<Auth> {\n return this.getBetterAuth();\n }\n}\n","/**\n * @krutai/auth - Authentication package for KrutAI\n *\n * Requires `krutai` as a peer dependency (installed automatically).\n *\n * @example Server-side (Next.js API route / server component)\n * ```typescript\n * import { krutAuth } from \"@krutai/auth\";\n * import Database from \"better-sqlite3\";\n *\n * export const auth = krutAuth({\n * database: new Database(\"./sqlite.db\"),\n * emailAndPassword: { enabled: true },\n * baseURL: process.env.BETTER_AUTH_BASE_URL ?? \"http://localhost:3000\",\n * });\n * ```\n *\n * @example Client-side (React / Next.js client component)\n * ```typescript\n * import { createAuthClient } from \"@krutai/auth/react\";\n *\n * export const authClient = createAuthClient({\n * baseURL: process.env.NEXT_PUBLIC_APP_URL ?? \"http://localhost:3000\",\n * });\n *\n * export const { signIn, signUp, signOut, useSession } = authClient;\n * ```\n *\n * @packageDocumentation\n */\n\nimport { betterAuth } from 'better-auth';\nimport type { BetterAuthOptions } from 'better-auth';\n\n/**\n * krutAuth — drop-in replacement for betterAuth.\n *\n * Use this instead of importing betterAuth directly.\n *\n * @example\n * ```typescript\n * import { krutAuth } from \"@krutai/auth\";\n * import Database from \"better-sqlite3\";\n *\n * export const auth = krutAuth({\n * database: new Database(\"./sqlite.db\"),\n * emailAndPassword: { enabled: true },\n * });\n * ```\n */\nexport function krutAuth(options: BetterAuthOptions) {\n return betterAuth(options);\n}\n\n// Export main KrutAuth class (API-key-protected wrapper)\nexport { KrutAuth } from './client';\n\n// Export types\nexport type { KrutAuthConfig, AuthSession, BetterAuthOptions } from './types';\n\n// Re-export minimal validator utilities (format/length check only)\nexport {\n validateApiKeyFormat,\n validateApiKeyWithService,\n ApiKeyValidationError,\n} from 'krutai';\n\n// Package metadata\nexport const VERSION = '0.1.9';\n"]}
1
+ {"version":3,"sources":["../src/types.ts","../src/client.ts","../src/index.ts"],"names":[],"mappings":";;;;AAUO,IAAM,kBAAA,GAAqB;AAM3B,IAAM,mBAAA,GAAsB;ACkC5B,IAAM,WAAN,MAAe;AAAA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ependency.\n */\n\n/**\n * Default base URL for the KrutAI server.\n * Used when no serverUrl is provided in the config.\n */\nexport const DEFAULT_SERVER_URL = 'http://localhost:8000' as const;\n\n/**\n * Default path prefix for the auth routes on the server.\n * The server mounts better-auth under this prefix.\n */\nexport const DEFAULT_AUTH_PREFIX = '/lib-auth' as const;\n\n/**\n * Configuration options for KrutAuth\n */\nexport interface KrutAuthConfig {\n /**\n * KrutAI API key.\n * Validated against the server before use.\n * Optional: defaults to process.env.KRUTAI_API_KEY\n */\n apiKey?: string;\n\n /**\n * Base URL of your deployed KrutAI server.\n * @default \"http://localhost:8000\"\n * @example \"https://krut.ai\"\n */\n serverUrl?: string;\n\n /**\n * Path prefix for the auth routes on the server.\n * @default \"/lib-auth\"\n */\n authPrefix?: string;\n\n /**\n * Whether to validate the API key against the server on initialization.\n * Set to false to skip the validation round-trip (e.g. in tests).\n * @default true\n */\n validateOnInit?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Auth method parameter types\n// ---------------------------------------------------------------------------\n\n/**\n * Parameters for email/password sign-up\n */\nexport interface SignUpEmailParams {\n /** User email */\n email: string;\n /** User password */\n password: string;\n /** Display name */\n name: string;\n}\n\n/**\n * Parameters for email/password sign-in\n */\nexport interface SignInEmailParams {\n /** User email */\n email: string;\n /** User password */\n password: string;\n}\n\n// ---------------------------------------------------------------------------\n// Auth response types\n// ---------------------------------------------------------------------------\n\n/**\n * A user record returned by the auth server\n */\nexport interface AuthUser {\n id: string;\n email: string;\n name?: string;\n emailVerified: boolean;\n createdAt: string;\n updatedAt: string;\n [key: string]: unknown;\n}\n\n/**\n * A session record returned by the auth server\n */\nexport interface AuthSessionRecord {\n id: string;\n userId: string;\n token: string;\n expiresAt: string;\n [key: string]: unknown;\n}\n\n/**\n * Combined session + user response\n */\nexport interface AuthSession {\n user: AuthUser;\n session: AuthSessionRecord;\n}\n\n/**\n * Sign-up / sign-in response (contains token + user)\n */\nexport interface AuthResponse {\n token: string;\n user: AuthUser;\n [key: string]: unknown;\n}\n","import type {\n KrutAuthConfig,\n SignUpEmailParams,\n SignInEmailParams,\n AuthSession,\n AuthResponse,\n} from './types';\nimport { DEFAULT_SERVER_URL, DEFAULT_AUTH_PREFIX } from './types';\nimport {\n validateApiKey,\n validateApiKeyFormat,\n KrutAIKeyValidationError,\n} from 'krutai';\n\nexport { KrutAIKeyValidationError };\n\n/**\n * KrutAuth — fetch-based authentication client for KrutAI\n *\n * Calls your deployed server's `/lib-auth` routes for all auth operations.\n * The API key is validated against the server before use.\n *\n * @example\n * ```typescript\n * import { KrutAuth } from '@krutai/auth';\n *\n * const auth = new KrutAuth({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n *\n * await auth.initialize(); // validates key against server\n *\n * // Sign up\n * const { token, user } = await auth.signUpEmail({\n * email: 'user@example.com',\n * password: 'secret123',\n * name: 'Alice',\n * });\n *\n * // Sign in\n * const result = await auth.signInEmail({\n * email: 'user@example.com',\n * password: 'secret123',\n * });\n *\n * // Get session\n * const session = await auth.getSession(result.token);\n * ```\n */\nexport class KrutAuth {\n private readonly apiKey: string;\n private readonly serverUrl: string;\n private readonly authPrefix: string;\n private readonly config: KrutAuthConfig;\n\n private initialized = false;\n\n constructor(config: KrutAuthConfig) {\n this.config = config;\n this.apiKey = config.apiKey || process.env.KRUTAI_API_KEY || '';\n this.serverUrl = (config.serverUrl ?? DEFAULT_SERVER_URL).replace(/\\/$/, '');\n this.authPrefix = (config.authPrefix ?? DEFAULT_AUTH_PREFIX).replace(/\\/$/, '');\n\n // Basic format check immediately on construction\n validateApiKeyFormat(this.apiKey);\n\n // If validation is disabled, mark as ready immediately\n if (config.validateOnInit === false) {\n this.initialized = true;\n }\n }\n\n /**\n * Initialize the auth client.\n * Validates the API key against the server, then marks client as ready.\n *\n * @throws {KrutAuthKeyValidationError} if the key is rejected or the server is unreachable\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n if (this.config.validateOnInit !== false) {\n await validateApiKey(this.apiKey, this.serverUrl);\n }\n\n this.initialized = true;\n }\n\n /**\n * Returns whether the client has been initialized.\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private assertInitialized(): void {\n if (!this.initialized) {\n throw new Error(\n 'KrutAuth not initialized. Call initialize() first or set validateOnInit to false.'\n );\n }\n }\n\n /** Common request headers sent to the server on every auth call. */\n private authHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'x-api-key': this.apiKey,\n };\n }\n\n /**\n * Build the full URL for an auth endpoint.\n * @param path - The better-auth sub-path, e.g. `/api/auth/sign-up/email`\n */\n private url(path: string): string {\n const cleanPath = path.startsWith('/') ? path : `/${path}`;\n return `${this.serverUrl}${this.authPrefix}${cleanPath}`;\n }\n\n // ---------------------------------------------------------------------------\n // Public Auth Methods\n // ---------------------------------------------------------------------------\n\n /**\n * Generic request helper for any better-auth endpoint.\n *\n * Use this to call endpoints not covered by the convenience methods.\n *\n * @param method - HTTP method (GET, POST, etc.)\n * @param path - The better-auth endpoint path (e.g. `/api/auth/sign-up/email`)\n * @param body - Optional JSON body\n * @returns The parsed JSON response\n */\n async request<T = unknown>(\n method: string,\n path: string,\n body?: Record<string, unknown> | object\n ): Promise<T> {\n this.assertInitialized();\n\n const options: RequestInit = {\n method,\n headers: this.authHeaders(),\n };\n\n if (body && method !== 'GET') {\n options.body = JSON.stringify(body);\n }\n\n const response = await fetch(this.url(path), options);\n\n if (!response.ok) {\n let errorMessage = `Auth server returned HTTP ${response.status} for ${path}`;\n try {\n const errorData = (await response.json()) as { message?: string; error?: string };\n if (errorData?.error) errorMessage = errorData.error;\n else if (errorData?.message) errorMessage = errorData.message;\n } catch { }\n throw new Error(errorMessage);\n }\n\n return (await response.json()) as T;\n }\n\n /**\n * Sign up a new user with email and password.\n *\n * Calls: POST {serverUrl}/lib-auth/api/auth/sign-up/email\n *\n * @param params - Sign-up parameters (email, password, name)\n * @returns The auth response containing token and user\n */\n async signUpEmail(params: SignUpEmailParams): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/auth/sign-up/email', params);\n }\n\n /**\n * Sign in with email and password.\n *\n * Calls: POST {serverUrl}/lib-auth/api/auth/sign-in/email\n *\n * @param params - Sign-in parameters (email, password)\n * @returns The auth response containing token and user\n */\n async signInEmail(params: SignInEmailParams): Promise<AuthResponse> {\n return this.request<AuthResponse>('POST', '/api/auth/sign-in/email', params);\n }\n\n /**\n * Get the current session for a user.\n *\n * Calls: GET {serverUrl}/lib-auth/api/auth/get-session\n *\n * @param sessionToken - The session token (Bearer token from sign-in)\n * @returns The session containing user and session data\n */\n async getSession(sessionToken: string): Promise<AuthSession> {\n this.assertInitialized();\n\n const response = await fetch(this.url('/api/auth/get-session'), {\n method: 'GET',\n headers: {\n ...this.authHeaders(),\n Cookie: `better-auth.session_token=${sessionToken}`,\n },\n });\n\n if (!response.ok) {\n let errorMessage = `Auth server returned HTTP ${response.status} for /api/auth/get-session`;\n try {\n const errorData = (await response.json()) as { message?: string; error?: string };\n if (errorData?.error) errorMessage = errorData.error;\n else if (errorData?.message) errorMessage = errorData.message;\n } catch { }\n throw new Error(errorMessage);\n }\n\n return (await response.json()) as AuthSession;\n }\n\n /**\n * Sign out the current user.\n *\n * Calls: POST {serverUrl}/lib-auth/api/auth/sign-out\n *\n * @param sessionToken - The session token to invalidate\n */\n async signOut(sessionToken: string): Promise<void> {\n this.assertInitialized();\n\n const response = await fetch(this.url('/api/auth/sign-out'), {\n method: 'POST',\n headers: {\n ...this.authHeaders(),\n Cookie: `better-auth.session_token=${sessionToken}`,\n },\n });\n\n if (!response.ok) {\n let errorMessage = `Auth server returned HTTP ${response.status} for /api/auth/sign-out`;\n try {\n const errorData = (await response.json()) as { message?: string; error?: string };\n if (errorData?.error) errorMessage = errorData.error;\n else if (errorData?.message) errorMessage = errorData.message;\n } catch { }\n throw new Error(errorMessage);\n }\n }\n}\n","/**\n * @krutai/auth — Authentication package for KrutAI\n *\n * A fetch-based wrapper that calls your deployed server's `/lib-auth` routes.\n * The user's API key is validated against the server before any auth call is made.\n *\n * @example Basic usage\n * ```typescript\n * import { krutAuth } from '@krutai/auth';\n *\n * const auth = krutAuth({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n *\n * await auth.initialize(); // validates key with server\n *\n * const { token, user } = await auth.signUpEmail({\n * email: 'user@example.com',\n * password: 'secret123',\n * name: 'Alice',\n * });\n * ```\n *\n * @example Sign in\n * ```typescript\n * const auth = krutAuth({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n * await auth.initialize();\n *\n * const { token, user } = await auth.signInEmail({\n * email: 'user@example.com',\n * password: 'secret123',\n * });\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { KrutAuthConfig } from './types';\nimport { KrutAuth } from './client';\n\nexport { KrutAuth } from './client';\nexport { KrutAIKeyValidationError } from './client';\nexport {\n validateApiKey,\n validateApiKeyFormat,\n} from 'krutai';\nexport type {\n KrutAuthConfig,\n SignUpEmailParams,\n SignInEmailParams,\n AuthSession,\n AuthSessionRecord,\n AuthUser,\n AuthResponse,\n} from './types';\nexport { DEFAULT_SERVER_URL, DEFAULT_AUTH_PREFIX } from './types';\n\n/**\n * krutAuth — convenience factory.\n *\n * Creates a `KrutAuth` instance configured to call your server's `/lib-auth` routes.\n *\n * @param config - Auth configuration (`apiKey` and `serverUrl` are required)\n * @returns A `KrutAuth` instance — call `.initialize()` before use\n *\n * @example\n * ```typescript\n * import { krutAuth } from '@krutai/auth';\n *\n * const auth = krutAuth({\n * apiKey: process.env.KRUTAI_API_KEY!,\n * serverUrl: 'https://krut.ai',\n * });\n *\n * await auth.initialize();\n * const { token, user } = await auth.signInEmail({\n * email: 'user@example.com',\n * password: 'secret123',\n * });\n * ```\n */\nexport function krutAuth(config: KrutAuthConfig): KrutAuth {\n return new KrutAuth(config);\n}\n\n// Package metadata\nexport const VERSION = '0.4.0';\n"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@krutai/auth",
3
- "version": "0.2.3",
4
- "description": "Authentication package for KrutAI — installs krutai, better-auth, and better-sqlite3 automatically",
3
+ "version": "0.4.2",
4
+ "description": "Authentication package for KrutAI — fetch-based client for your server's auth routes with API key validation",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
7
7
  "types": "./dist/index.d.ts",
@@ -10,47 +10,30 @@
10
10
  "types": "./dist/index.d.ts",
11
11
  "import": "./dist/index.mjs",
12
12
  "require": "./dist/index.js"
13
- },
14
- "./react": {
15
- "types": "./dist/react.d.ts",
16
- "import": "./dist/react.mjs",
17
- "require": "./dist/react.js"
18
- },
19
- "./next-js": {
20
- "types": "./dist/next-js.d.ts",
21
- "import": "./dist/next-js.mjs",
22
- "require": "./dist/next-js.js"
23
13
  }
24
14
  },
25
15
  "files": [
26
16
  "dist",
27
- "scripts",
28
17
  "README.md",
29
18
  "AI_REFERENCE.md"
30
19
  ],
31
20
  "scripts": {
21
+ "prepack": "npm run build",
32
22
  "build": "tsup",
33
23
  "dev": "tsup --watch",
34
24
  "clean": "rm -rf dist *.tsbuildinfo",
35
- "typecheck": "tsc --noEmit",
36
- "postinstall": "node scripts/migrate.js"
25
+ "typecheck": "tsc --noEmit"
37
26
  },
38
27
  "keywords": [
39
28
  "krutai",
40
29
  "auth",
41
30
  "authentication",
42
- "better-auth"
31
+ "fetch"
43
32
  ],
44
33
  "author": "",
45
34
  "license": "MIT",
46
35
  "dependencies": {
47
- "better-auth": "^1.1.7",
48
- "better-sqlite3": "^12.0.0",
49
- "@types/better-sqlite3": "^7.6.0",
50
- "krutai": ">=0.1.4"
51
- },
52
- "peerDependencies": {
53
- "krutai": ">=0.1.4"
36
+ "krutai": "0.1.6"
54
37
  },
55
38
  "devDependencies": {
56
39
  "@types/node": "^20.11.0",
@@ -1 +0,0 @@
1
- export * from 'better-auth/next-js';
package/dist/next-js.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from 'better-auth/next-js';
package/dist/next-js.js DELETED
@@ -1,14 +0,0 @@
1
- 'use strict';
2
-
3
- var nextJs = require('better-auth/next-js');
4
-
5
-
6
-
7
- Object.keys(nextJs).forEach(function (k) {
8
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
9
- enumerable: true,
10
- get: function () { return nextJs[k]; }
11
- });
12
- });
13
- //# sourceMappingURL=next-js.js.map
14
- //# sourceMappingURL=next-js.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"next-js.js","sourcesContent":[]}
package/dist/next-js.mjs DELETED
@@ -1,3 +0,0 @@
1
- export * from 'better-auth/next-js';
2
- //# sourceMappingURL=next-js.mjs.map
3
- //# sourceMappingURL=next-js.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"next-js.mjs","sourcesContent":[]}
package/dist/react.d.mts DELETED
@@ -1 +0,0 @@
1
- export * from 'better-auth/react';
package/dist/react.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from 'better-auth/react';
package/dist/react.js DELETED
@@ -1,14 +0,0 @@
1
- 'use strict';
2
-
3
- var react = require('better-auth/react');
4
-
5
-
6
-
7
- Object.keys(react).forEach(function (k) {
8
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
9
- enumerable: true,
10
- get: function () { return react[k]; }
11
- });
12
- });
13
- //# sourceMappingURL=react.js.map
14
- //# sourceMappingURL=react.js.map
package/dist/react.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"react.js","sourcesContent":[]}
package/dist/react.mjs DELETED
@@ -1,3 +0,0 @@
1
- export * from 'better-auth/react';
2
- //# sourceMappingURL=react.mjs.map
3
- //# sourceMappingURL=react.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"react.mjs","sourcesContent":[]}
@@ -1,53 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * @krutai/auth — postinstall migration script
4
- *
5
- * Automatically creates (or updates) the SQLite database tables
6
- * required by Better Auth. Runs after `npm install @krutai/auth`.
7
- *
8
- * The database file is placed at the project root as `sqlite.db`.
9
- * Set BETTER_AUTH_DB_PATH to override the location.
10
- * Set SKIP_KRUTAI_MIGRATE=1 to skip this script entirely.
11
- */
12
-
13
- const { execSync } = require('child_process');
14
- const path = require('path');
15
- const fs = require('fs');
16
-
17
- // Allow opt-out
18
- if (process.env.SKIP_KRUTAI_MIGRATE === '1') {
19
- console.log('[krutai/auth] Skipping migration (SKIP_KRUTAI_MIGRATE=1)');
20
- process.exit(0);
21
- }
22
-
23
- // Determine project root (where the consuming project's package.json lives)
24
- // When postinstall runs under node_modules/@krutai/auth, we go up 3 levels.
25
- const projectRoot = path.resolve(__dirname, '..', '..', '..', '..');
26
-
27
- // Fallback: if we're being run from within the monorepo itself, use cwd
28
- const packageJson = path.join(projectRoot, 'package.json');
29
- const root = fs.existsSync(packageJson) ? projectRoot : process.cwd();
30
-
31
- const dbPath = process.env.BETTER_AUTH_DB_PATH ?? path.join(root, 'sqlite.db');
32
-
33
- console.log('[krutai/auth] Running Better Auth SQLite migration...');
34
- console.log(`[krutai/auth] Database: ${dbPath}`);
35
-
36
- try {
37
- // better-auth provides a CLI via `npx better-auth migrate`
38
- // Pass the db path via env so it's picked up automatically
39
- execSync('npx better-auth migrate --yes', {
40
- cwd: root,
41
- stdio: 'inherit',
42
- env: {
43
- ...process.env,
44
- BETTER_AUTH_DB_PATH: dbPath,
45
- BETTER_AUTH_DATABASE_URL: `file:${dbPath}`,
46
- },
47
- });
48
- console.log('[krutai/auth] Migration complete. SQLite tables are ready.');
49
- } catch (err) {
50
- // Don't fail the install — the user may not have a lib/auth.ts yet
51
- console.warn('[krutai/auth] Migration skipped or failed (this is OK if you have not created lib/auth.ts yet).');
52
- console.warn('[krutai/auth] Run `npx better-auth migrate` manually after setting up your auth config.');
53
- }