@egdesk/next-api-plugin 1.5.26 → 1.5.28

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/README.md CHANGED
@@ -29,10 +29,14 @@ npx egdesk-next-setup
29
29
  ```
30
30
 
31
31
  This will generate:
32
- - `middleware.ts` - Database proxy middleware
32
+ - `middleware.ts` or `proxy.ts` - Database proxy (includes visitor auth/google)
33
33
  - `egdesk.config.ts` - Type-safe table definitions
34
34
  - `egdesk-helpers.ts` - Helper functions for database access
35
- - `.env.local` - Environment variables
35
+ - `egdesk-visitor-google.ts` - Visitor Google login (EGDesk Auth users, brokered by EGDesk)
36
+ - `app/auth/callback/page.tsx` - Exchanges EGDesk’s one-time login code
37
+ - `.env.local` - Environment variables (`NEXT_PUBLIC_EGDESK_*` only — no Supabase keys)
38
+
39
+ Add `{EGDesk public URL}/visitor-auth/callback` to the EGDesk Supabase Auth redirect allowlist (once per EGDesk/tunnel origin, not each published site).
36
40
 
37
41
  2. Add `.env.local` to your `.gitignore` (if not already there)
38
42
 
@@ -66,6 +70,12 @@ NEXT_PUBLIC_EGDESK_API_URL=http://localhost:8080
66
70
  NEXT_PUBLIC_EGDESK_API_KEY=your-api-key-here
67
71
  ```
68
72
 
73
+ Published sites do **not** receive `SUPABASE_URL` or the anon key. Visitor Google sign-in is brokered by EGDesk: the site redirects through `{EGDESK_API}/visitor-auth`, EGDesk creates an Auth user, and the site stores an opaque session id.
74
+
75
+ Add the **EGDesk** callback (not each site origin) to **Supabase → Authentication → URL Configuration → Redirect URLs**, e.g. `http://localhost:8080/visitor-auth/callback` (and the tunnel URL in production).
76
+
77
+ Owner MCP (`startDriveAuthLogin`) is a separate credential on the EGDesk machine. Visitor login does not overwrite it.
78
+
69
79
  ### Custom Setup
70
80
 
71
81
  You can programmatically run the setup:
@@ -143,8 +153,27 @@ listCompanyResearch(status?: 'completed' | 'failed' | 'in_progress')
143
153
  getCompanyResearchById(researchId: string)
144
154
  getCompanyResearchByDomain(domain: string)
145
155
  searchCompanyResearch(searchText: string)
156
+
157
+ // Owner Drive MCP (THIS EGDesk instance)
158
+ startDriveAuthLogin()
159
+ getDriveAuthStatus()
160
+
161
+ // Visitor Google — import from egdesk-visitor-google.ts, not egdesk-helpers.ts
162
+ startVisitorGoogleLogin()
163
+ getVisitorGoogleStatus()
164
+ listVisitorDriveFiles()
165
+ getVisitorSheetRange(spreadsheetId, range)
146
166
  ```
147
167
 
168
+ ### Visitor Google vs owner MCP
169
+
170
+ | Who | Helper | Identity |
171
+ |-----|--------|----------|
172
+ | EGDesk owner | `startDriveAuthLogin()` | Owner token for this machine’s MCP (Drive watch, sync) |
173
+ | Website visitor | `startVisitorGoogleLogin()` from `egdesk-visitor-google.ts` | EGDesk Auth user (login brokered by EGDesk; opaque session on the site) |
174
+
175
+ Visitors **are** EGDesk Auth users. They are not the MCP owner. The published site never holds Supabase credentials; RLS still limits each user to their own token row on EGDesk.
176
+
148
177
  ### Configuration Types
149
178
 
150
179
  ```typescript
package/dist/cli.js CHANGED
@@ -36,6 +36,9 @@ async function main() {
36
36
  console.log(' --legacy-middleware Use middleware.ts instead of proxy.ts (for Next.js <16)');
37
37
  console.log(' --help, -h Show this help message');
38
38
  console.log('');
39
+ console.log('Visitor Google sign-in is brokered by EGDesk (no Supabase keys on the site).');
40
+ console.log('Add {EGDesk public URL}/visitor-auth/callback to the Supabase Auth redirect allowlist.');
41
+ console.log('');
39
42
  console.log('Example:');
40
43
  console.log(' egdesk-next-setup --url http://localhost:8080 --api-key mykey');
41
44
  console.log(' egdesk-next-setup --legacy-middleware # For Next.js <16');
@@ -137,7 +137,8 @@ function generateHelpers(projectPath, options = {}) {
137
137
  const helperContent = `/**
138
138
  * EGDesk Helper Functions for Next.js
139
139
  *
140
- * Type-safe helpers for EGDesk user data, FinanceHub (banks, cards, Hometax, promissory notes),
140
+ * Type-safe helpers for EGDesk user data, Google Workspace (Sheets / Drive / Gmail / Apps Script sync),
141
+ * FinanceHub (banks, cards, Hometax, promissory notes),
141
142
  * internal knowledge / business identity / company research (MCP), Korean law (MCP), and browser recorder replay.
142
143
  * Works in both client and server components.
143
144
  *
@@ -248,6 +249,78 @@ async function parseEgdeskMcpToolResponse(response: Response): Promise<any> {
248
249
  return content ? JSON.parse(content) : null;
249
250
  }
250
251
 
252
+ async function parseEgdeskHttpResponse(response: Response): Promise<any> {
253
+ const result = await response.json().catch(() => null);
254
+ if (!result) {
255
+ throw new Error(\`HTTP \${response.status}: \${response.statusText}\`);
256
+ }
257
+ if (!response.ok || result.status === 'error' || result.success === false) {
258
+ const msg =
259
+ (typeof result.message === 'string' && result.message) ||
260
+ (typeof result.error === 'string' && result.error) ||
261
+ \`HTTP \${response.status}\`;
262
+ throw new Error(msg);
263
+ }
264
+ return result;
265
+ }
266
+
267
+ export type WorkspaceSyncDirection = 'toWorkspace' | 'toLocal' | 'both';
268
+
269
+ export type EgdeskHttpMethod = 'GET' | 'POST';
270
+
271
+ /**
272
+ * Call an EGDesk HTTP endpoint (not MCP \`/tools/call\`).
273
+ * Used for bidirectional Google Workspace sync: \`/sheets/sync\`, \`/drive/sync\`, \`/apps-script/sync\`.
274
+ *
275
+ * - Server: \`GET|POST {apiUrl}{pathname}\`
276
+ * - Client: \`POST /__egdesk_http_proxy\`
277
+ */
278
+ export async function callEgdeskHttp(
279
+ pathname: string,
280
+ options: {
281
+ method?: EgdeskHttpMethod;
282
+ body?: Record<string, unknown>;
283
+ query?: Record<string, string | undefined>;
284
+ } = {}
285
+ ): Promise<any> {
286
+ const method: EgdeskHttpMethod = options.method || 'GET';
287
+ const query: Record<string, string> = {};
288
+ for (const [key, value] of Object.entries(options.query || {})) {
289
+ if (value) query[key] = value;
290
+ }
291
+
292
+ const isServer = typeof window === 'undefined';
293
+ let response: Response;
294
+ if (isServer) {
295
+ const apiUrl =
296
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
297
+ EGDESK_CONFIG.apiUrl;
298
+ const base = apiUrl.endsWith('/') ? apiUrl : \`\${apiUrl}/\`;
299
+ const url = new URL(pathname.startsWith('/') ? pathname.slice(1) : pathname, base);
300
+ for (const [key, value] of Object.entries(query)) {
301
+ url.searchParams.set(key, value);
302
+ }
303
+ response = await fetch(url.toString(), {
304
+ method,
305
+ headers: buildServerEgdeskHeaders(),
306
+ body: method === 'POST' ? JSON.stringify(options.body || {}) : undefined,
307
+ });
308
+ } else {
309
+ response = await apiFetch('/__egdesk_http_proxy', {
310
+ method: 'POST',
311
+ headers: { 'Content-Type': 'application/json' },
312
+ body: JSON.stringify({
313
+ path: pathname,
314
+ method,
315
+ body: options.body || {},
316
+ query,
317
+ }),
318
+ });
319
+ }
320
+
321
+ return parseEgdeskHttpResponse(response);
322
+ }
323
+
251
324
  /**
252
325
  * Call EGDesk user-data MCP tool
253
326
  *
@@ -2637,7 +2710,10 @@ export async function deletePageIndexDocument(docId: string) {
2637
2710
  /**
2638
2711
  * Call EGDesk Drive MCP tool (Google Drive change notifications + poll).
2639
2712
  *
2640
- * Auth on EGDesk: GOOGLE_SERVICE_ACCOUNT_JSON or Google Workspace sign-in.
2713
+ * Owner MCP auth on EGDesk: GOOGLE_SERVICE_ACCOUNT_JSON or Google Workspace sign-in
2714
+ * via startDriveAuthLogin() — configures THIS EGDesk instance, not website visitors.
2715
+ * Website visitors should use startVisitorGoogleLogin() from egdesk-visitor-google.ts
2716
+ * (EGDesk brokers Auth; the site never receives Supabase keys).
2641
2717
  * Share target folders with the service account when using SA credentials.
2642
2718
  *
2643
2719
  * - Server: \`POST {apiUrl}/drive/tools/call\`
@@ -2673,14 +2749,16 @@ export async function callDriveTool(
2673
2749
  return parseEgdeskMcpToolResponse(response);
2674
2750
  }
2675
2751
 
2676
- /** Check Drive auth (service account / Google OAuth) */
2752
+ /** Check owner Drive auth on this EGDesk instance (service account / Google OAuth) */
2677
2753
  export async function getDriveAuthStatus() {
2678
2754
  return callDriveTool('drive_auth_status', {});
2679
2755
  }
2680
2756
 
2681
2757
  /**
2682
- * Start Google OAuth for Drive. Returns { status:'pending', authUrl } immediately.
2683
- * Open authUrl in the browser, then poll getDriveAuthStatus() until connected.
2758
+ * Start Google OAuth for THIS EGDesk instance (owner MCP credentials).
2759
+ * Returns { status:'pending', authUrl } immediately. EGDesk receives the callback
2760
+ * on localhost:54321 (dev) or egdesk://. Do not use this for website visitors —
2761
+ * they sign in via startVisitorGoogleLogin() in egdesk-visitor-google.ts (EGDesk brokers Auth).
2684
2762
  */
2685
2763
  export async function startDriveAuthLogin(options: {
2686
2764
  openWindow?: boolean;
@@ -2754,6 +2832,205 @@ export async function setDriveTargetFolders(folderIds: string[]) {
2754
2832
  return callDriveTool('drive_set_target_folders', { folderIds });
2755
2833
  }
2756
2834
 
2835
+ /** Upload a local file into a watched Drive folder (local → Workspace) */
2836
+ export async function uploadDriveFile(options: {
2837
+ filePath: string;
2838
+ folderId?: string;
2839
+ destName?: string;
2840
+ mimeType?: string;
2841
+ }) {
2842
+ return callDriveTool('drive_upload', options);
2843
+ }
2844
+
2845
+ /**
2846
+ * Drive HTTP sync (same as GET/POST /drive/sync).
2847
+ * Omit options to GET status. Pass \`direction: 'toLocal'\` to download, or
2848
+ * \`direction: 'toWorkspace'\` + \`filePath\` to upload.
2849
+ */
2850
+ export async function syncDrive(options: {
2851
+ direction?: WorkspaceSyncDirection;
2852
+ filePath?: string;
2853
+ folderId?: string;
2854
+ destName?: string;
2855
+ } = {}) {
2856
+ const hasBody = Boolean(options.direction || options.filePath || options.folderId || options.destName);
2857
+ return callEgdeskHttp('/drive/sync', {
2858
+ method: hasBody ? 'POST' : 'GET',
2859
+ body: hasBody ? options : undefined,
2860
+ });
2861
+ }
2862
+
2863
+ // ==========================================
2864
+ // Google Sheets HTTP sync — My DB ↔ Workspace
2865
+ // ==========================================
2866
+
2867
+ /** List overwrite configs + incremental links (GET /sheets/sync) */
2868
+ export async function listSheetSyncConnections(options: {
2869
+ projectId?: string;
2870
+ environment?: 'development' | 'production';
2871
+ } = {}) {
2872
+ return callEgdeskHttp('/sheets/sync', {
2873
+ method: 'GET',
2874
+ query: {
2875
+ projectId: options.projectId,
2876
+ environment: options.environment,
2877
+ },
2878
+ });
2879
+ }
2880
+
2881
+ /**
2882
+ * Sync Sheets either direction (POST /sheets/sync).
2883
+ * - toWorkspace (default): My DB → Sheet overwrite, or incremental push if no overwrite config
2884
+ * - toLocal: Sheet → My DB (requires a sheet table link)
2885
+ * - both: pull then push
2886
+ */
2887
+ export async function syncSheets(options: {
2888
+ direction?: WorkspaceSyncDirection;
2889
+ projectId?: string;
2890
+ environment?: 'development' | 'production';
2891
+ configId?: string;
2892
+ linkId?: string;
2893
+ spreadsheetId?: string;
2894
+ tabName?: string;
2895
+ } = {}) {
2896
+ return callEgdeskHttp('/sheets/sync', {
2897
+ method: 'POST',
2898
+ body: options,
2899
+ });
2900
+ }
2901
+
2902
+ // ==========================================
2903
+ // Gmail (MCP) — fetch domain mail + send
2904
+ // ==========================================
2905
+
2906
+ /**
2907
+ * Call EGDesk Gmail MCP tool.
2908
+ *
2909
+ * - Server: \`POST {apiUrl}/gmail/tools/call\`
2910
+ * - Client: \`POST /__gmail_proxy\`
2911
+ */
2912
+ export async function callGmailTool(
2913
+ toolName: string,
2914
+ args: Record<string, any> = {}
2915
+ ): Promise<any> {
2916
+ const body = JSON.stringify({ tool: toolName, arguments: args });
2917
+ const isServer = typeof window === 'undefined';
2918
+ let response: Response;
2919
+ if (isServer) {
2920
+ const apiUrl =
2921
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2922
+ EGDESK_CONFIG.apiUrl;
2923
+ response = await fetch(\`\${apiUrl}/gmail/tools/call\`, {
2924
+ method: 'POST',
2925
+ headers: buildServerEgdeskHeaders(),
2926
+ body
2927
+ });
2928
+ } else {
2929
+ response = await apiFetch('/__gmail_proxy', {
2930
+ method: 'POST',
2931
+ headers: { 'Content-Type': 'application/json' },
2932
+ body
2933
+ });
2934
+ }
2935
+ return parseEgdeskMcpToolResponse(response);
2936
+ }
2937
+
2938
+ /** Workspace → local: list domain users */
2939
+ export async function listGmailUsers() {
2940
+ return callGmailTool('gmail_list_users', {});
2941
+ }
2942
+
2943
+ /** Workspace → local: fetch a user's messages */
2944
+ export async function getGmailUserMessages(email: string, options: { maxResults?: number } = {}) {
2945
+ return callGmailTool('gmail_get_user_messages', { email, ...options });
2946
+ }
2947
+
2948
+ export async function getGmailUserStats(email: string) {
2949
+ return callGmailTool('gmail_get_user_stats', { email });
2950
+ }
2951
+
2952
+ export async function searchGmailMessages(
2953
+ query: string,
2954
+ options: { email?: string; maxResults?: number } = {}
2955
+ ) {
2956
+ return callGmailTool('gmail_search_messages', { query, ...options });
2957
+ }
2958
+
2959
+ /** Local → Workspace: send from the signed-in Google account */
2960
+ export async function sendGmailMessage(options: {
2961
+ to: string;
2962
+ subject: string;
2963
+ body: string;
2964
+ attachments?: Array<{ filename: string; path: string; mimeType: string }>;
2965
+ }) {
2966
+ return callGmailTool('gmail_send_message', options);
2967
+ }
2968
+
2969
+ // ==========================================
2970
+ // Apps Script (MCP + HTTP) — local ↔ Google
2971
+ // ==========================================
2972
+
2973
+ /**
2974
+ * Call EGDesk Apps Script MCP tool.
2975
+ *
2976
+ * - Server: \`POST {apiUrl}/apps-script/tools/call\`
2977
+ * - Client: \`POST /__apps_script_proxy\`
2978
+ */
2979
+ export async function callAppsScriptTool(
2980
+ toolName: string,
2981
+ args: Record<string, any> = {}
2982
+ ): Promise<any> {
2983
+ const body = JSON.stringify({ tool: toolName, arguments: args });
2984
+ const isServer = typeof window === 'undefined';
2985
+ let response: Response;
2986
+ if (isServer) {
2987
+ const apiUrl =
2988
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2989
+ EGDESK_CONFIG.apiUrl;
2990
+ response = await fetch(\`\${apiUrl}/apps-script/tools/call\`, {
2991
+ method: 'POST',
2992
+ headers: buildServerEgdeskHeaders(),
2993
+ body
2994
+ });
2995
+ } else {
2996
+ response = await apiFetch('/__apps_script_proxy', {
2997
+ method: 'POST',
2998
+ headers: { 'Content-Type': 'application/json' },
2999
+ body
3000
+ });
3001
+ }
3002
+ return parseEgdeskMcpToolResponse(response);
3003
+ }
3004
+
3005
+ /** Local → Workspace */
3006
+ export async function pushAppsScriptToGoogle(
3007
+ projectId: string,
3008
+ options: { createVersion?: boolean; versionDescription?: string } = {}
3009
+ ) {
3010
+ return callAppsScriptTool('apps_script_push_to_google', { projectId, ...options });
3011
+ }
3012
+
3013
+ /** Workspace → local */
3014
+ export async function pullAppsScriptFromGoogle(projectId: string) {
3015
+ return callAppsScriptTool('apps_script_pull_from_google', { projectId });
3016
+ }
3017
+
3018
+ /**
3019
+ * Apps Script HTTP sync (POST /apps-script/sync).
3020
+ * direction toWorkspace = push; toLocal = pull. Does not accept \`both\`.
3021
+ */
3022
+ export async function syncAppsScript(options: {
3023
+ direction?: Exclude<WorkspaceSyncDirection, 'both'>;
3024
+ projectId: string;
3025
+ createVersion?: boolean;
3026
+ versionDescription?: string;
3027
+ }) {
3028
+ return callEgdeskHttp('/apps-script/sync', {
3029
+ method: 'POST',
3030
+ body: options,
3031
+ });
3032
+ }
3033
+
2757
3034
  // ==========================================
2758
3035
  // Knowledge Wiki (MCP) — Obsidian + wikiHow
2759
3036
  // ==========================================
@@ -3263,12 +3540,12 @@ export async function syncInstagramPostStats(options: {
3263
3540
  return callInstagramTool('instagram_sync_post_stats', options);
3264
3541
  }
3265
3542
 
3266
- /** Alias of syncInstagramPostStats — scrape recent posts with engagement. */
3543
+ /** @deprecated Use syncInstagramPostStats — same scrape + history merge. */
3267
3544
  export async function fetchInstagramPosts(options: {
3268
3545
  connectionId: string;
3269
3546
  limit?: number;
3270
3547
  }) {
3271
- return callInstagramTool('instagram_fetch_posts', options);
3548
+ return syncInstagramPostStats(options);
3272
3549
  }
3273
3550
 
3274
3551
  export type GenerateInstagramContentOptions = {
@@ -73,7 +73,7 @@ import type { NextRequest } from 'next/server';
73
73
  /**
74
74
  * EGDesk Database Proxy Middleware
75
75
  *
76
- * Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, __company_research_proxy, and __kakao_proxy requests
76
+ * Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, __company_research_proxy, __kakao_proxy, __drive_proxy, __egdesk_http_proxy, __gmail_proxy, __apps_script_proxy, __visitor_auth_proxy, and __visitor_google_proxy requests
77
77
  * and forwards them to the EGDesk MCP HTTP server.
78
78
  * This allows CORS-free database access in both local and tunneled environments.
79
79
  *
@@ -245,6 +245,159 @@ export async function middleware(request: NextRequest) {
245
245
  }
246
246
  }
247
247
 
248
+ if (pathname.includes('__drive_proxy')) {
249
+ try {
250
+ const body = await request.text();
251
+ const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
252
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
253
+ const headers: HeadersInit = { 'Content-Type': 'application/json' };
254
+ if (apiKey) headers['X-Api-Key'] = apiKey;
255
+
256
+ const response = await fetch(\`\${apiUrl}/drive/tools/call\`, {
257
+ method: 'POST',
258
+ headers,
259
+ body,
260
+ });
261
+ const result = await response.json();
262
+ return NextResponse.json(result, { status: response.status });
263
+ } catch (error: any) {
264
+ return NextResponse.json(
265
+ { error: 'Proxy error', message: error.message },
266
+ { status: 500 }
267
+ );
268
+ }
269
+ }
270
+
271
+ if (pathname.includes('__egdesk_http_proxy')) {
272
+ try {
273
+ const payload = await request.json().catch(() => ({} as Record<string, unknown>));
274
+ const allowed = new Set(['/sheets/sync', '/drive/sync', '/apps-script/sync']);
275
+ const targetPath = typeof payload.path === 'string' ? payload.path.split('?')[0] : '';
276
+ if (!allowed.has(targetPath)) {
277
+ return NextResponse.json({ error: 'Path not allowed', path: targetPath }, { status: 400 });
278
+ }
279
+ const method = payload.method === 'POST' ? 'POST' : 'GET';
280
+ const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
281
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
282
+ const projectId = process.env.NEXT_PUBLIC_EGDESK_PROJECT_ID;
283
+ const egdeskEnv = process.env.NEXT_PUBLIC_EGDESK_ENV;
284
+ const headers: HeadersInit = { 'Content-Type': 'application/json' };
285
+ if (apiKey) headers['X-Api-Key'] = apiKey;
286
+ if (projectId) headers['X-EGDesk-Project-Id'] = projectId;
287
+ if (egdeskEnv) headers['X-EGDesk-Env'] = egdeskEnv;
288
+ const base = apiUrl.endsWith('/') ? apiUrl : \`\${apiUrl}/\`;
289
+ const url = new URL(targetPath.startsWith('/') ? targetPath.slice(1) : targetPath, base);
290
+ const query = payload.query && typeof payload.query === 'object' ? payload.query as Record<string, unknown> : {};
291
+ for (const [key, value] of Object.entries(query)) {
292
+ if (typeof value === 'string' && value) url.searchParams.set(key, value);
293
+ }
294
+ const response = await fetch(url.toString(), {
295
+ method,
296
+ headers,
297
+ body: method === 'POST' ? JSON.stringify(payload.body || {}) : undefined,
298
+ });
299
+ const result = await response.json();
300
+ return NextResponse.json(result, { status: response.status });
301
+ } catch (error: any) {
302
+ return NextResponse.json(
303
+ { error: 'Proxy error', message: error.message },
304
+ { status: 500 }
305
+ );
306
+ }
307
+ }
308
+
309
+ if (pathname.includes('__gmail_proxy')) {
310
+ try {
311
+ const body = await request.text();
312
+ const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
313
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
314
+ const headers: HeadersInit = { 'Content-Type': 'application/json' };
315
+ if (apiKey) headers['X-Api-Key'] = apiKey;
316
+ const response = await fetch(\`\${apiUrl}/gmail/tools/call\`, {
317
+ method: 'POST',
318
+ headers,
319
+ body,
320
+ });
321
+ const result = await response.json();
322
+ return NextResponse.json(result, { status: response.status });
323
+ } catch (error: any) {
324
+ return NextResponse.json(
325
+ { error: 'Proxy error', message: error.message },
326
+ { status: 500 }
327
+ );
328
+ }
329
+ }
330
+
331
+ if (pathname.includes('__apps_script_proxy')) {
332
+ try {
333
+ const body = await request.text();
334
+ const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
335
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
336
+ const headers: HeadersInit = { 'Content-Type': 'application/json' };
337
+ if (apiKey) headers['X-Api-Key'] = apiKey;
338
+ const response = await fetch(\`\${apiUrl}/apps-script/tools/call\`, {
339
+ method: 'POST',
340
+ headers,
341
+ body,
342
+ });
343
+ const result = await response.json();
344
+ return NextResponse.json(result, { status: response.status });
345
+ } catch (error: any) {
346
+ return NextResponse.json(
347
+ { error: 'Proxy error', message: error.message },
348
+ { status: 500 }
349
+ );
350
+ }
351
+ }
352
+
353
+ if (pathname.includes('__visitor_auth_proxy')) {
354
+ try {
355
+ const body = await request.text();
356
+ const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
357
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
358
+ const headers: HeadersInit = { 'Content-Type': 'application/json' };
359
+ if (apiKey) headers['X-Api-Key'] = apiKey;
360
+
361
+ const response = await fetch(\`\${apiUrl}/visitor-auth/tools/call\`, {
362
+ method: 'POST',
363
+ headers,
364
+ body,
365
+ });
366
+ const result = await response.json();
367
+ return NextResponse.json(result, { status: response.status });
368
+ } catch (error: any) {
369
+ return NextResponse.json(
370
+ { error: 'Proxy error', message: error.message },
371
+ { status: 500 }
372
+ );
373
+ }
374
+ }
375
+
376
+ if (pathname.includes('__visitor_google_proxy')) {
377
+ try {
378
+ const body = await request.text();
379
+ const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
380
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
381
+ const headers: HeadersInit = { 'Content-Type': 'application/json' };
382
+ if (apiKey) headers['X-Api-Key'] = apiKey;
383
+ const authorization = request.headers.get('authorization');
384
+ if (authorization) headers['Authorization'] = authorization;
385
+
386
+ const response = await fetch(\`\${apiUrl}/visitor-google/tools/call\`, {
387
+ method: 'POST',
388
+ headers,
389
+ body,
390
+ });
391
+ const result = await response.json();
392
+ return NextResponse.json(result, { status: response.status });
393
+ } catch (error: any) {
394
+ return NextResponse.json(
395
+ { error: 'Proxy error', message: error.message },
396
+ { status: 500 }
397
+ );
398
+ }
399
+ }
400
+
248
401
  // Continue to next middleware or route
249
402
  return NextResponse.next();
250
403
  }
@@ -75,7 +75,7 @@ import type { NextRequest } from 'next/server';
75
75
  /**
76
76
  * EGDesk Database Proxy (Next.js 16+)
77
77
  *
78
- * Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, __company_research_proxy, __ai_center_proxy, __korean_law_proxy, __seo_proxy, __ssl_proxy, __local_agent_proxy, __pageindex_proxy, __drive_proxy, __knowledge_wiki_proxy, __egdesk_config_proxy, __ai_caller_proxy, __kakao_proxy, __phone_proxy, __instagram_proxy, __financehub_proxy, __blog_proxy, and __youtube_proxy requests
78
+ * Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, __company_research_proxy, __ai_center_proxy, __korean_law_proxy, __seo_proxy, __ssl_proxy, __local_agent_proxy, __pageindex_proxy, __drive_proxy, __egdesk_http_proxy, __gmail_proxy, __apps_script_proxy, __knowledge_wiki_proxy, __egdesk_config_proxy, __ai_caller_proxy, __kakao_proxy, __phone_proxy, __instagram_proxy, __financehub_proxy, __blog_proxy, __youtube_proxy, __visitor_auth_proxy, and __visitor_google_proxy requests
79
79
  * and forwards them to the EGDesk MCP HTTP server. This avoids CORS in local and tunneled environments.
80
80
  *
81
81
  * Generated by @egdesk/next-api-plugin
@@ -340,6 +340,75 @@ export async function proxy(request: NextRequest) {
340
340
  }
341
341
  }
342
342
 
343
+ if (pathname.includes('__egdesk_http_proxy')) {
344
+ try {
345
+ const payload = await request.json().catch(() => ({} as Record<string, unknown>));
346
+ const allowed = new Set(['/sheets/sync', '/drive/sync', '/apps-script/sync']);
347
+ const targetPath = typeof payload.path === 'string' ? payload.path.split('?')[0] : '';
348
+ if (!allowed.has(targetPath)) {
349
+ return NextResponse.json({ error: 'Path not allowed', path: targetPath }, { status: 400 });
350
+ }
351
+ const method = payload.method === 'POST' ? 'POST' : 'GET';
352
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
353
+ const base = apiUrl.endsWith('/') ? apiUrl : \`\${apiUrl}/\`;
354
+ const url = new URL(targetPath.startsWith('/') ? targetPath.slice(1) : targetPath, base);
355
+ const query = payload.query && typeof payload.query === 'object' ? payload.query as Record<string, unknown> : {};
356
+ for (const [key, value] of Object.entries(query)) {
357
+ if (typeof value === 'string' && value) url.searchParams.set(key, value);
358
+ }
359
+ const response = await fetch(url.toString(), {
360
+ method,
361
+ headers: buildEgdeskHeaders(),
362
+ body: method === 'POST' ? JSON.stringify(payload.body || {}) : undefined,
363
+ });
364
+ const result = await response.json();
365
+ return NextResponse.json(result, { status: response.status });
366
+ } catch (error: any) {
367
+ return NextResponse.json(
368
+ { error: 'Proxy error', message: error.message },
369
+ { status: 500 }
370
+ );
371
+ }
372
+ }
373
+
374
+ if (pathname.includes('__gmail_proxy')) {
375
+ try {
376
+ const body = await request.text();
377
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
378
+ const response = await fetch(\`\${apiUrl}/gmail/tools/call\`, {
379
+ method: 'POST',
380
+ headers: buildEgdeskHeaders(),
381
+ body,
382
+ });
383
+ const result = await response.json();
384
+ return NextResponse.json(result, { status: response.status });
385
+ } catch (error: any) {
386
+ return NextResponse.json(
387
+ { error: 'Proxy error', message: error.message },
388
+ { status: 500 }
389
+ );
390
+ }
391
+ }
392
+
393
+ if (pathname.includes('__apps_script_proxy')) {
394
+ try {
395
+ const body = await request.text();
396
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
397
+ const response = await fetch(\`\${apiUrl}/apps-script/tools/call\`, {
398
+ method: 'POST',
399
+ headers: buildEgdeskHeaders(),
400
+ body,
401
+ });
402
+ const result = await response.json();
403
+ return NextResponse.json(result, { status: response.status });
404
+ } catch (error: any) {
405
+ return NextResponse.json(
406
+ { error: 'Proxy error', message: error.message },
407
+ { status: 500 }
408
+ );
409
+ }
410
+ }
411
+
343
412
  if (pathname.includes('__knowledge_wiki_proxy')) {
344
413
  try {
345
414
  const body = await request.text();
@@ -538,6 +607,53 @@ export async function proxy(request: NextRequest) {
538
607
  }
539
608
  }
540
609
 
610
+ if (pathname.includes('__visitor_auth_proxy')) {
611
+ try {
612
+ const body = await request.text();
613
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
614
+
615
+ const response = await fetch(\`\${apiUrl}/visitor-auth/tools/call\`, {
616
+ method: 'POST',
617
+ headers: buildEgdeskHeaders(),
618
+ body,
619
+ });
620
+
621
+ const result = await response.json();
622
+
623
+ return NextResponse.json(result, { status: response.status });
624
+ } catch (error: any) {
625
+ return NextResponse.json(
626
+ { error: 'Proxy error', message: error.message },
627
+ { status: 500 }
628
+ );
629
+ }
630
+ }
631
+
632
+ if (pathname.includes('__visitor_google_proxy')) {
633
+ try {
634
+ const body = await request.text();
635
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
636
+ const headers = buildEgdeskHeaders();
637
+ const authorization = request.headers.get('authorization');
638
+ if (authorization) headers['Authorization'] = authorization;
639
+
640
+ const response = await fetch(\`\${apiUrl}/visitor-google/tools/call\`, {
641
+ method: 'POST',
642
+ headers,
643
+ body,
644
+ });
645
+
646
+ const result = await response.json();
647
+
648
+ return NextResponse.json(result, { status: response.status });
649
+ } catch (error: any) {
650
+ return NextResponse.json(
651
+ { error: 'Proxy error', message: error.message },
652
+ { status: 500 }
653
+ );
654
+ }
655
+ }
656
+
541
657
  // Continue to next proxy or route
542
658
  return NextResponse.next();
543
659
  }
@@ -546,7 +662,7 @@ export const config = {
546
662
  matcher: [
547
663
  /*
548
664
  * Match all paths except static assets
549
- * The proxy function filters for __user_data_proxy / __browser_recording_proxy / __internal_knowledge_proxy / __company_research_proxy / __ai_center_proxy / __korean_law_proxy / __seo_proxy / __ssl_proxy / __local_agent_proxy / __pageindex_proxy / __drive_proxy / __knowledge_wiki_proxy / __egdesk_config_proxy / __ai_caller_proxy / __kakao_proxy / __phone_proxy / __instagram_proxy / __financehub_proxy / __blog_proxy / __youtube_proxy
665
+ * The proxy function filters for __user_data_proxy / __browser_recording_proxy / __internal_knowledge_proxy / __company_research_proxy / __ai_center_proxy / __korean_law_proxy / __seo_proxy / __ssl_proxy / __local_agent_proxy / __pageindex_proxy / __drive_proxy / __egdesk_http_proxy / __gmail_proxy / __apps_script_proxy / __knowledge_wiki_proxy / __egdesk_config_proxy / __ai_caller_proxy / __kakao_proxy / __phone_proxy / __instagram_proxy / __financehub_proxy / __blog_proxy / __youtube_proxy / __visitor_auth_proxy / __visitor_google_proxy
550
666
  */
551
667
  '/:path*',
552
668
  ],
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Generate visitor Google OAuth scaffolding for published Next.js sites.
3
+ *
4
+ * Owner MCP auth (drive_auth_login) stays on EGDesk. Visitors sign in through
5
+ * EGDesk (same Auth project) and receive an opaque session id.
6
+ * Published sites never receive SUPABASE_URL or the anon key.
7
+ */
8
+ export declare function generateVisitorAuth(projectPath: string): void;
@@ -0,0 +1,275 @@
1
+ "use strict";
2
+ /**
3
+ * Generate visitor Google OAuth scaffolding for published Next.js sites.
4
+ *
5
+ * Owner MCP auth (drive_auth_login) stays on EGDesk. Visitors sign in through
6
+ * EGDesk (same Auth project) and receive an opaque session id.
7
+ * Published sites never receive SUPABASE_URL or the anon key.
8
+ */
9
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || (function () {
26
+ var ownKeys = function(o) {
27
+ ownKeys = Object.getOwnPropertyNames || function (o) {
28
+ var ar = [];
29
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
30
+ return ar;
31
+ };
32
+ return ownKeys(o);
33
+ };
34
+ return function (mod) {
35
+ if (mod && mod.__esModule) return mod;
36
+ var result = {};
37
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
38
+ __setModuleDefault(result, mod);
39
+ return result;
40
+ };
41
+ })();
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.generateVisitorAuth = generateVisitorAuth;
44
+ const fs = __importStar(require("fs"));
45
+ const path = __importStar(require("path"));
46
+ const os = __importStar(require("os"));
47
+ function usesSrcDirectory(projectPath) {
48
+ const srcPath = path.join(projectPath, 'src');
49
+ const srcAppPath = path.join(projectPath, 'src', 'app');
50
+ return fs.existsSync(srcPath) && fs.existsSync(srcAppPath);
51
+ }
52
+ function resolveAppDir(projectPath) {
53
+ if (usesSrcDirectory(projectPath)) {
54
+ return path.join(projectPath, 'src', 'app');
55
+ }
56
+ const appDir = path.join(projectPath, 'app');
57
+ if (!fs.existsSync(appDir)) {
58
+ fs.mkdirSync(appDir, { recursive: true });
59
+ }
60
+ return appDir;
61
+ }
62
+ function backupIfExists(filePath) {
63
+ if (!fs.existsSync(filePath))
64
+ return;
65
+ const backupPath = `${filePath.replace(/\.tsx?$/, '')}.backup${path.extname(filePath)}`;
66
+ fs.copyFileSync(filePath, backupPath);
67
+ console.log(`⚠️ ${path.basename(filePath)} already exists - backing up to ${path.basename(backupPath)}`);
68
+ }
69
+ function writeGenerated(filePath, contents) {
70
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
71
+ backupIfExists(filePath);
72
+ fs.writeFileSync(filePath, contents.replace(/\r?\n/g, os.EOL), 'utf-8');
73
+ console.log(`✅ Generated ${filePath}`);
74
+ }
75
+ function removeIfExists(filePath) {
76
+ if (!fs.existsSync(filePath))
77
+ return;
78
+ try {
79
+ fs.unlinkSync(filePath);
80
+ console.log(`🗑️ Removed ${filePath} (visitor Google now goes through EGDesk)`);
81
+ }
82
+ catch (error) {
83
+ console.warn(`⚠️ Could not remove ${filePath}:`, error);
84
+ }
85
+ }
86
+ const CALLBACK_PAGE = `'use client';
87
+
88
+ /**
89
+ * Visitor Google OAuth callback.
90
+ * Generated by @egdesk/next-api-plugin.
91
+ *
92
+ * EGDesk completes Google/Supabase OAuth, then redirects here with ?code=
93
+ * (a one-time EGDesk code, not a Supabase token). This page exchanges it
94
+ * for an opaque visitor session id.
95
+ */
96
+
97
+ import { useEffect, useState } from 'react';
98
+ import { exchangeVisitorAuthCode } from '@/egdesk-visitor-google';
99
+
100
+ export default function VisitorAuthCallbackPage() {
101
+ const [message, setMessage] = useState('Finishing sign-in…');
102
+
103
+ useEffect(() => {
104
+ const params = new URLSearchParams(window.location.search);
105
+ const code = params.get('code');
106
+ const next = params.get('next') || '/';
107
+ if (!code) {
108
+ setMessage('Missing login code. Close this page and try Sign in with Google again.');
109
+ return;
110
+ }
111
+ void exchangeVisitorAuthCode(code)
112
+ .then(() => {
113
+ const dest = next.startsWith('/') ? next : '/';
114
+ window.location.replace(dest);
115
+ })
116
+ .catch((err: unknown) => {
117
+ const text = err instanceof Error ? err.message : String(err);
118
+ setMessage('Sign-in failed: ' + text);
119
+ });
120
+ }, []);
121
+
122
+ return (
123
+ <main style={{ fontFamily: 'system-ui, sans-serif', padding: 24 }}>
124
+ <p>{message}</p>
125
+ </main>
126
+ );
127
+ }
128
+ `;
129
+ const VISITOR_HELPERS = `/**
130
+ * EGDesk visitor Google helpers (published-site visitors).
131
+ *
132
+ * Visitors become EGDesk Auth users. Login is brokered by EGDesk so this
133
+ * site never receives SUPABASE_URL or the anon key.
134
+ *
135
+ * Import this file only from pages that need visitor Google.
136
+ *
137
+ * Generated by @egdesk/next-api-plugin.
138
+ */
139
+
140
+ import { apiFetch } from './egdesk-helpers';
141
+
142
+ const VISITOR_SESSION_KEY = 'egdesk_visitor_session';
143
+
144
+ export const VISITOR_GOOGLE_OAUTH_SCOPES = [
145
+ 'https://www.googleapis.com/auth/userinfo.email',
146
+ 'https://www.googleapis.com/auth/userinfo.profile',
147
+ 'https://www.googleapis.com/auth/drive.file',
148
+ 'https://www.googleapis.com/auth/spreadsheets',
149
+ 'openid',
150
+ ] as const;
151
+
152
+ function getVisitorSessionId(): string | null {
153
+ if (typeof window === 'undefined') return null;
154
+ return window.localStorage.getItem(VISITOR_SESSION_KEY);
155
+ }
156
+
157
+ function setVisitorSessionId(sessionId: string | null): void {
158
+ if (typeof window === 'undefined') return;
159
+ if (sessionId) window.localStorage.setItem(VISITOR_SESSION_KEY, sessionId);
160
+ else window.localStorage.removeItem(VISITOR_SESSION_KEY);
161
+ }
162
+
163
+ async function parseEgdeskJson(response: Response): Promise<any> {
164
+ const result = await response.json().catch(() => null);
165
+ if (!response.ok) {
166
+ const errMsg =
167
+ result && typeof result === 'object' && typeof result.error === 'string'
168
+ ? result.error
169
+ : \`Request failed (\${response.status})\`;
170
+ throw new Error(errMsg);
171
+ }
172
+ return result;
173
+ }
174
+
175
+ async function callVisitorAuth(tool: string, args: Record<string, unknown> = {}) {
176
+ const response = await apiFetch('/__visitor_auth_proxy', {
177
+ method: 'POST',
178
+ headers: { 'Content-Type': 'application/json' },
179
+ body: JSON.stringify({ tool, arguments: args }),
180
+ });
181
+ return parseEgdeskJson(response);
182
+ }
183
+
184
+ async function callVisitorGoogle(tool: string, args: Record<string, unknown> = {}) {
185
+ const sessionId = getVisitorSessionId();
186
+ if (!sessionId) {
187
+ throw new Error('Visitor is not signed in. Call startVisitorGoogleLogin() first.');
188
+ }
189
+ const response = await apiFetch('/__visitor_google_proxy', {
190
+ method: 'POST',
191
+ headers: {
192
+ 'Content-Type': 'application/json',
193
+ Authorization: \`Bearer \${sessionId}\`,
194
+ },
195
+ body: JSON.stringify({ tool, arguments: args }),
196
+ });
197
+ return parseEgdeskJson(response);
198
+ }
199
+
200
+ /**
201
+ * Sign a website visitor in with Google via EGDesk.
202
+ * Creates/uses an EGDesk user; Google tokens stay under that user_id on EGDesk.
203
+ */
204
+ export async function startVisitorGoogleLogin(options: {
205
+ next?: string;
206
+ forceConsent?: boolean;
207
+ } = {}) {
208
+ if (typeof window === 'undefined') {
209
+ throw new Error('startVisitorGoogleLogin() must run in the browser');
210
+ }
211
+ const next =
212
+ options.next && options.next.startsWith('/') ? options.next : window.location.pathname;
213
+ const returnTo = new URL('/auth/callback', window.location.origin);
214
+ returnTo.searchParams.set('next', next);
215
+ const egdeskPublicUrl =
216
+ process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
217
+
218
+ const result = await callVisitorAuth('start', {
219
+ returnTo: returnTo.toString(),
220
+ egdeskPublicUrl,
221
+ forceConsent: options.forceConsent !== false,
222
+ });
223
+ if (!result?.authUrl) {
224
+ throw new Error(result?.error || 'Failed to start visitor Google login');
225
+ }
226
+ window.location.href = result.authUrl;
227
+ }
228
+
229
+ export async function exchangeVisitorAuthCode(code: string) {
230
+ const result = await callVisitorAuth('exchange', { code });
231
+ if (!result?.sessionId) {
232
+ throw new Error(result?.error || 'Failed to complete visitor login');
233
+ }
234
+ setVisitorSessionId(result.sessionId);
235
+ return result;
236
+ }
237
+
238
+ export async function signOutVisitorGoogle() {
239
+ try {
240
+ const sessionId = getVisitorSessionId();
241
+ if (sessionId) {
242
+ await callVisitorAuth('logout', { sessionId });
243
+ }
244
+ } finally {
245
+ setVisitorSessionId(null);
246
+ }
247
+ }
248
+
249
+ export async function getVisitorGoogleStatus() {
250
+ const sessionId = getVisitorSessionId();
251
+ if (!sessionId) {
252
+ return { connected: false, email: null, message: 'Visitor is not signed in.' };
253
+ }
254
+ try {
255
+ return await callVisitorGoogle('status');
256
+ } catch {
257
+ return { connected: false, email: null, message: 'Visitor is not signed in.' };
258
+ }
259
+ }
260
+
261
+ export async function listVisitorDriveFiles(options: { pageSize?: number; query?: string } = {}) {
262
+ return callVisitorGoogle('listDriveFiles', options);
263
+ }
264
+
265
+ export async function getVisitorSheetRange(spreadsheetId: string, range: string) {
266
+ return callVisitorGoogle('getSheetRange', { spreadsheetId, range });
267
+ }
268
+ `;
269
+ function generateVisitorAuth(projectPath) {
270
+ const appDir = resolveAppDir(projectPath);
271
+ writeGenerated(path.join(appDir, 'auth', 'callback', 'page.tsx'), CALLBACK_PAGE);
272
+ writeGenerated(path.join(projectPath, 'egdesk-visitor-google.ts'), VISITOR_HELPERS);
273
+ removeIfExists(path.join(appDir, 'api', 'visitor-google', 'route.ts'));
274
+ removeIfExists(path.join(appDir, 'api', 'visitor-google', 'route.js'));
275
+ }
package/dist/index.d.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * The minimum EGDesk app version this plugin version is compatible with.
9
9
  * The app checks this at setup time and warns on mismatch.
10
10
  */
11
- export declare const COMPATIBLE_APP_VERSION = "1.4.39";
11
+ export declare const COMPATIBLE_APP_VERSION = "1.4.41";
12
12
  export interface SetupOptions {
13
13
  egdeskUrl?: string;
14
14
  /** Production EGDesk server URL — written to .env.production.local. Falls back to egdeskUrl. */
@@ -43,3 +43,4 @@ export { generateProxy } from './generate-proxy';
43
43
  export { generateHelpers, generateSchemaFile, ensureSchemaFile, formatEgdeskSchemaFileContent } from './generate-helpers';
44
44
  export type { SchemaTableDefinition, EnsureSchemaFileResult, GenerateHelpersOptions } from './generate-helpers';
45
45
  export { generateApiWrapper } from './generate-api-wrapper';
46
+ export { generateVisitorAuth } from './generate-visitor-auth';
package/dist/index.js CHANGED
@@ -39,14 +39,14 @@ var __importStar = (this && this.__importStar) || (function () {
39
39
  };
40
40
  })();
41
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
- exports.generateApiWrapper = exports.formatEgdeskSchemaFileContent = exports.ensureSchemaFile = exports.generateSchemaFile = exports.generateHelpers = exports.generateProxy = exports.generateMiddleware = exports.updateEnvFiles = exports.loadTablesFromSchemaFile = exports.generateConfigFile = exports.discoverTables = exports.COMPATIBLE_APP_VERSION = void 0;
42
+ exports.generateVisitorAuth = exports.generateApiWrapper = exports.formatEgdeskSchemaFileContent = exports.ensureSchemaFile = exports.generateSchemaFile = exports.generateHelpers = exports.generateProxy = exports.generateMiddleware = exports.updateEnvFiles = exports.loadTablesFromSchemaFile = exports.generateConfigFile = exports.discoverTables = exports.COMPATIBLE_APP_VERSION = void 0;
43
43
  exports.detectNextUseProxy = detectNextUseProxy;
44
44
  exports.setupNextApiPlugin = setupNextApiPlugin;
45
45
  /**
46
46
  * The minimum EGDesk app version this plugin version is compatible with.
47
47
  * The app checks this at setup time and warns on mismatch.
48
48
  */
49
- exports.COMPATIBLE_APP_VERSION = '1.4.39';
49
+ exports.COMPATIBLE_APP_VERSION = '1.4.41';
50
50
  const fs = __importStar(require("fs"));
51
51
  const path = __importStar(require("path"));
52
52
  const setup_userdata_1 = require("./setup-userdata");
@@ -54,6 +54,7 @@ const generate_middleware_1 = require("./generate-middleware");
54
54
  const generate_proxy_1 = require("./generate-proxy");
55
55
  const generate_helpers_1 = require("./generate-helpers");
56
56
  const generate_api_wrapper_1 = require("./generate-api-wrapper");
57
+ const generate_visitor_auth_1 = require("./generate-visitor-auth");
57
58
  /** Next.js 15 and below use middleware.ts; proxy.ts requires Next.js 16+. */
58
59
  function detectNextUseProxy(projectPath) {
59
60
  try {
@@ -115,7 +116,7 @@ async function discoverApiKeyNames(egdeskUrl, apiKey, egdeskProjectId) {
115
116
  * - .env.local (environment variables)
116
117
  */
117
118
  async function setupNextApiPlugin(projectPath, options = {}) {
118
- const { egdeskUrl = 'http://localhost:8080', prodEgdeskUrl, discoveryUrl, egdeskProjectId, apiKey, useProxy } = options;
119
+ const { egdeskUrl = 'http://localhost:8080', prodEgdeskUrl, discoveryUrl, egdeskProjectId, apiKey, useProxy, } = options;
119
120
  const resolvedUseProxy = useProxy ?? detectNextUseProxy(projectPath);
120
121
  console.log('🔍 Discovering EGDesk user-data tables...');
121
122
  let devTables = [];
@@ -186,6 +187,7 @@ async function setupNextApiPlugin(projectPath, options = {}) {
186
187
  })));
187
188
  (0, generate_helpers_1.generateHelpers)(projectPath, { apiKeyNames });
188
189
  (0, generate_api_wrapper_1.generateApiWrapper)(projectPath);
190
+ (0, generate_visitor_auth_1.generateVisitorAuth)(projectPath);
189
191
  (0, setup_userdata_1.updateEnvFiles)(projectPath, config, prodTables);
190
192
  const proxyFile = resolvedUseProxy ? 'proxy.ts' : 'middleware.ts';
191
193
  console.log('');
@@ -194,14 +196,18 @@ async function setupNextApiPlugin(projectPath, options = {}) {
194
196
  console.log(' - egdesk.config.ts (type-safe config)');
195
197
  console.log(' - egdesk.schema.ts (committed seed schema — add to git if newly created)');
196
198
  console.log(' - egdesk-helpers.ts (helper functions)');
199
+ console.log(' - egdesk-visitor-google.ts (visitor Google via EGDesk Auth broker)');
197
200
  console.log(' - src/lib/api.ts (basePath-aware fetch wrapper)');
201
+ console.log(' - app/auth/callback/page.tsx (exchanges EGDesk one-time login code)');
198
202
  console.log(' - .env.development.local (dev environment variables)');
199
203
  console.log(' - .env.production.local (prod environment variables)');
200
204
  console.log('');
201
205
  console.log('📝 Next steps:');
202
206
  console.log(' 1. Add .env.*.local to your .gitignore');
203
- console.log(' 2. Restart your Next.js dev server');
204
- console.log(' 3. Import and use helpers in your components:');
207
+ console.log(' 2. Add this EGDesk public URL + /visitor-auth/callback to Supabase Auth redirect URLs');
208
+ console.log(' (once per EGDesk/tunnel origin — not each published site)');
209
+ console.log(' 3. Restart your Next.js dev server');
210
+ console.log(' 4. Import and use helpers in your components:');
205
211
  console.log(' import { queryTable } from "./egdesk-helpers"');
206
212
  console.log(' import { TABLES } from "./egdesk.config"');
207
213
  console.log(' import { apiFetch } from "@/lib/api"');
@@ -234,3 +240,5 @@ Object.defineProperty(exports, "ensureSchemaFile", { enumerable: true, get: func
234
240
  Object.defineProperty(exports, "formatEgdeskSchemaFileContent", { enumerable: true, get: function () { return generate_helpers_2.formatEgdeskSchemaFileContent; } });
235
241
  var generate_api_wrapper_2 = require("./generate-api-wrapper");
236
242
  Object.defineProperty(exports, "generateApiWrapper", { enumerable: true, get: function () { return generate_api_wrapper_2.generateApiWrapper; } });
243
+ var generate_visitor_auth_2 = require("./generate-visitor-auth");
244
+ Object.defineProperty(exports, "generateVisitorAuth", { enumerable: true, get: function () { return generate_visitor_auth_2.generateVisitorAuth; } });
@@ -222,7 +222,9 @@ prodTables) {
222
222
  function writeEnvFile(envPath, apiUrl, label, egdeskEnv, tables) {
223
223
  // Preserve existing non-EGDesk vars
224
224
  const existing = parseEnvFile(envPath);
225
- const preserved = Object.fromEntries(Object.entries(existing).filter(([k]) => !egdeskKeys.has(k)));
225
+ const preserved = Object.fromEntries(Object.entries(existing).filter(([k]) => !egdeskKeys.has(k) &&
226
+ k !== 'NEXT_PUBLIC_SUPABASE_URL' &&
227
+ k !== 'NEXT_PUBLIC_SUPABASE_ANON_KEY'));
226
228
  const aiWarning = egdeskEnv === 'production' ? [
227
229
  '# ============================================================',
228
230
  '# ⚠️ AI ASSISTANT — DO NOT READ, EDIT, OR USE THIS FILE ⚠️',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@egdesk/next-api-plugin",
3
- "version": "1.5.26",
3
+ "version": "1.5.28",
4
4
  "description": "Next.js plugin for EGDesk database proxy integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",