@egdesk/next-api-plugin 1.5.106 → 1.5.110

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
@@ -308,6 +308,20 @@ Ensure:
308
308
  - You have tables imported in EGDesk
309
309
  - API key is correct (if required)
310
310
 
311
+ ## Operator BYO OAuth (security)
312
+
313
+ **Do not expose operator GCP config to site visitors.** `workspace_oauth_clients` / `workspace_oauth_clients_manage` run on the operator's EGDesk (`POST /workspace-oauth/tools/call`), not on visitor-auth routes.
314
+
315
+ This plugin **must never** generate:
316
+
317
+ - `app/api/workspace-oauth/**` (or any public Next route that proxies browser POSTs to `/workspace-oauth/tools/call`)
318
+
319
+ Visitor-facing codegen is limited to **`__visitor_auth_proxy`** and **`__visitor_google_proxy`** (allow-listed tools only). Operator BYO upload belongs in **EGDesk → Google Workspace** or host-side MCP with `oauthClientJsonPath`.
320
+
321
+ See `apps/egdesk/.../workspace-oauth-byo-multi-HANDOFF-README.md` **§6.9** and security invariant **2**.
322
+
323
+ The **`egdesk-system-demo`** repo may include a gated `app/api/workspace-oauth/route.ts` for local QA only — not a pattern for production sites.
324
+
311
325
  ## License
312
326
 
313
327
  MIT
@@ -240,6 +240,8 @@ export type WorkspaceVisitorCallOptions = {
240
240
  visitorOrigin?: string;
241
241
  /** Owner MCP: use personal Google login before service account when both are configured. */
242
242
  preferOAuth?: boolean;
243
+ /** Owner MCP: operator GCP connection (id or label). Overrides EGDESK_OWNER_OAUTH_PROFILE when set. */
244
+ oauthClientProfileId?: string;
243
245
  };
244
246
 
245
247
  function getBrowserVisitorSessionId(): string | null {
@@ -301,6 +303,18 @@ function withVisitorToolArgs(
301
303
  const out = { ...args };
302
304
  if (options.asVisitor) out.asVisitor = true;
303
305
  if (options.preferOAuth !== undefined) out.preferOAuth = options.preferOAuth;
306
+ if (!options.asVisitor) {
307
+ const explicit = options.oauthClientProfileId?.trim();
308
+ const fromEnv =
309
+ typeof process !== 'undefined' ? process.env?.EGDESK_OWNER_OAUTH_PROFILE?.trim() : '';
310
+ const pin = explicit || fromEnv;
311
+ if (pin && out.oauthClientProfileId === undefined && out.profileId === undefined) {
312
+ out.oauthClientProfileId = pin;
313
+ }
314
+ }
315
+ if (options.oauthClientProfileId?.trim()) {
316
+ out.oauthClientProfileId = options.oauthClientProfileId.trim();
317
+ }
304
318
  return out;
305
319
  }
306
320
 
@@ -74,6 +74,9 @@ import type { NextRequest } from 'next/server';
74
74
  * EGDesk Database Proxy Middleware
75
75
  *
76
76
  * Intercepts __user_data_proxy, __browser_recording_proxy, __business_identity_proxy, __company_research_proxy, __kakao_proxy, __drive_proxy, __sheets_proxy, __docs_proxy, __slides_proxy, __egdesk_http_proxy, __gmail_proxy, __apps_script_proxy, __visitor_auth_proxy, and __visitor_google_proxy requests
77
+ *
78
+ * POLICY (workspace-oauth-byo-multi-HANDOFF-README.md §6.9): Never codegen app/api/workspace-oauth/*
79
+ * or browser proxies to POST /workspace-oauth/tools/call — operator BYO config is not a visitor API.
77
80
  * and forwards them to the EGDesk MCP HTTP server.
78
81
  * This allows CORS-free database access in both local and tunneled environments.
79
82
  *
@@ -121,6 +124,20 @@ function resolveEgdeskMcpApiUrl(): string {
121
124
  return (process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080').replace(/\\/$/, '');
122
125
  }
123
126
 
127
+ /**
128
+ * Hosted coding on the same PC: always use loopback MCP (operator BYO + local pending).
129
+ * Published-only deploys without EGDESK_MCP_INTERNAL_URL may use the tunnel gateway.
130
+ */
131
+ function resolveVisitorAuthMcpApiUrl(): string {
132
+ const internal = process.env.EGDESK_MCP_INTERNAL_URL;
133
+ if (internal && internal.trim()) return internal.replace(/\\/$/, '');
134
+ const tunnel = process.env.NEXT_PUBLIC_EGDESK_TUNNEL_URL;
135
+ if (tunnel && tunnel.trim()) return tunnel.replace(/\\/$/, '');
136
+ const publicUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL;
137
+ if (publicUrl && publicUrl.trim()) return publicUrl.replace(/\\/$/, '');
138
+ return 'http://localhost:8080';
139
+ }
140
+
124
141
  export async function middleware(request: NextRequest) {
125
142
  const { pathname } = request.nextUrl;
126
143
 
@@ -446,7 +463,7 @@ export async function middleware(request: NextRequest) {
446
463
  if (pathname.includes('__visitor_auth_proxy')) {
447
464
  try {
448
465
  const body = await request.text();
449
- const apiUrl = resolveEgdeskMcpApiUrl();
466
+ const apiUrl = resolveVisitorAuthMcpApiUrl();
450
467
 
451
468
  const response = await fetch(\`\${apiUrl}/visitor-auth/tools/call\`, {
452
469
  method: 'POST',
@@ -466,7 +483,7 @@ export async function middleware(request: NextRequest) {
466
483
  if (pathname.includes('__visitor_google_proxy')) {
467
484
  try {
468
485
  const body = await request.text();
469
- const apiUrl = resolveEgdeskMcpApiUrl();
486
+ const apiUrl = resolveVisitorAuthMcpApiUrl();
470
487
  const headers = visitorUpstreamHeaders(request);
471
488
  const authorization = request.headers.get('authorization');
472
489
  if (authorization) headers['Authorization'] = authorization;
@@ -76,6 +76,9 @@ import type { NextRequest } from 'next/server';
76
76
  * EGDesk Database Proxy (Next.js 16+)
77
77
  *
78
78
  * Intercepts __user_data_proxy, __browser_recording_proxy, __business_identity_proxy, __company_research_proxy, __ai_center_proxy, __korean_law_proxy, __bizinfo_proxy, __nps_proxy, __seo_proxy, __hosting_coding_proxy, __local_agent_proxy, __pageindex_proxy, __drive_proxy, __sheets_proxy, __docs_proxy, __slides_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
+ *
80
+ * POLICY (workspace-oauth-byo-multi-HANDOFF-README.md §6.9): Never codegen app/api/workspace-oauth/*
81
+ * or browser proxies to POST /workspace-oauth/tools/call — operator BYO config is not a visitor API.
79
82
  * and forwards them to the EGDesk MCP HTTP server. This avoids CORS in local and tunneled environments.
80
83
  *
81
84
  * Generated by @egdesk/next-api-plugin
@@ -100,6 +103,19 @@ function resolveEgdeskMcpApiUrl(): string {
100
103
  return (process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080').replace(/\\/$/, '');
101
104
  }
102
105
 
106
+ /**
107
+ * Prefer loopback MCP when EGDESK_MCP_INTERNAL_URL is set (hosted coding on the PC).
108
+ */
109
+ function resolveVisitorAuthMcpApiUrl(): string {
110
+ const internal = process.env.EGDESK_MCP_INTERNAL_URL;
111
+ if (internal && internal.trim()) return internal.replace(/\\/$/, '');
112
+ const tunnel = process.env.NEXT_PUBLIC_EGDESK_TUNNEL_URL;
113
+ if (tunnel && tunnel.trim()) return tunnel.replace(/\\/$/, '');
114
+ const publicUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL;
115
+ if (publicUrl && publicUrl.trim()) return publicUrl.replace(/\\/$/, '');
116
+ return 'http://localhost:8080';
117
+ }
118
+
103
119
  /** Forward this site's origin so EGDesk can bind visitor sessions to this site only. */
104
120
  function visitorForwardHeaders(request: NextRequest): Record<string, string> {
105
121
  const headers = buildEgdeskHeaders();
@@ -800,7 +816,7 @@ export async function proxy(request: NextRequest) {
800
816
  if (pathname.includes('__visitor_auth_proxy')) {
801
817
  try {
802
818
  const body = await request.text();
803
- const apiUrl = resolveEgdeskMcpApiUrl();
819
+ const apiUrl = resolveVisitorAuthMcpApiUrl();
804
820
 
805
821
  const response = await fetch(\`\${apiUrl}/visitor-auth/tools/call\`, {
806
822
  method: 'POST',
@@ -822,7 +838,7 @@ export async function proxy(request: NextRequest) {
822
838
  if (pathname.includes('__visitor_google_proxy')) {
823
839
  try {
824
840
  const body = await request.text();
825
- const apiUrl = resolveEgdeskMcpApiUrl();
841
+ const apiUrl = resolveVisitorAuthMcpApiUrl();
826
842
  const headers = visitorForwardHeaders(request);
827
843
  const authorization = request.headers.get('authorization');
828
844
  if (authorization) headers['Authorization'] = authorization;
@@ -465,6 +465,9 @@ export async function startVisitorGoogleLogin(options: {
465
465
  next?: string;
466
466
  forceConsent?: boolean;
467
467
  scopes?: readonly string[] | VisitorScopePreset;
468
+ /** platform | operator:<label> | self (7b) — must match hosted project visitorGcp allow-list */
469
+ gcp?: string;
470
+ handle?: string;
468
471
  } = {}) {
469
472
  if (typeof window === 'undefined') {
470
473
  throw new Error('startVisitorGoogleLogin() must run in the browser');
@@ -483,12 +486,15 @@ export async function startVisitorGoogleLogin(options: {
483
486
  }
484
487
  const scopes = resolveVisitorLoginScopes(options.scopes);
485
488
 
486
- const result = await callVisitorAuth('start', {
489
+ const startArgs: Record<string, unknown> = {
487
490
  returnTo: returnTo.toString(),
488
491
  egdeskPublicUrl,
489
492
  forceConsent: options.forceConsent === true,
490
493
  scopes,
491
- });
494
+ };
495
+ if (options.gcp?.trim()) startArgs.gcp = options.gcp.trim();
496
+ if (options.handle?.trim()) startArgs.handle = options.handle.trim();
497
+ const result = await callVisitorAuth('start', startArgs);
492
498
  if (!result?.authUrl) {
493
499
  throw new Error(result?.error || 'Failed to start visitor Google login');
494
500
  }
@@ -527,6 +533,54 @@ export async function getVisitorGoogleStatus() {
527
533
  }
528
534
  }
529
535
 
536
+ export async function registerVisitorGcp(options: {
537
+ oauthClientJson: unknown;
538
+ handle?: string;
539
+ egdeskPublicUrl?: string;
540
+ }) {
541
+ if (typeof window === 'undefined') {
542
+ throw new Error('registerVisitorGcp() must run in the browser');
543
+ }
544
+ const sampleReturnTo = new URL(resolveVisitorAppPath('/auth/callback'), window.location.origin).toString();
545
+ const egdeskPublicUrl = options.egdeskPublicUrl?.trim() || resolveEgdeskPublicUrl();
546
+ const result = await callVisitorAuth('register_gcp', {
547
+ oauthClientJson: options.oauthClientJson,
548
+ handle: options.handle,
549
+ egdeskPublicUrl,
550
+ sampleReturnTo,
551
+ });
552
+ return result;
553
+ }
554
+
555
+ export async function getVisitorGcpStatus(handle: string) {
556
+ if (typeof window === 'undefined') {
557
+ throw new Error('getVisitorGcpStatus() must run in the browser');
558
+ }
559
+ const sampleReturnTo = new URL(resolveVisitorAppPath('/auth/callback'), window.location.origin).toString();
560
+ return callVisitorAuth('gcp_status', { handle, sampleReturnTo });
561
+ }
562
+
563
+ export async function forgetVisitorGcp(handle: string) {
564
+ if (typeof window === 'undefined') {
565
+ throw new Error('forgetVisitorGcp() must run in the browser');
566
+ }
567
+ const sampleReturnTo = new URL(resolveVisitorAppPath('/auth/callback'), window.location.origin).toString();
568
+ return callVisitorAuth('forget_gcp', { handle, sampleReturnTo });
569
+ }
570
+
571
+ const VISITOR_GCP_HANDLE_KEY = 'egdesk_visitor_gcp_handle';
572
+
573
+ export function getStoredVisitorGcpHandle(): string | null {
574
+ if (typeof window === 'undefined') return null;
575
+ return window.localStorage.getItem(VISITOR_GCP_HANDLE_KEY);
576
+ }
577
+
578
+ export function setStoredVisitorGcpHandle(handle: string | null): void {
579
+ if (typeof window === 'undefined') return;
580
+ if (handle) window.localStorage.setItem(VISITOR_GCP_HANDLE_KEY, handle);
581
+ else window.localStorage.removeItem(VISITOR_GCP_HANDLE_KEY);
582
+ }
583
+
530
584
  export async function listVisitorDriveFiles(options: { pageSize?: number; query?: string } = {}) {
531
585
  return callVisitorGoogle('listDriveFiles', options);
532
586
  }
@@ -535,6 +589,114 @@ export async function getVisitorSheetRange(spreadsheetId: string, range: string)
535
589
  return callVisitorGoogle('getSheetRange', { spreadsheetId, range });
536
590
  }
537
591
  `;
592
+ const VISITOR_GCP_BYO_COMPONENT = `'use client';
593
+
594
+ /**
595
+ * End-user BYO Web OAuth upload UI (phase 7b).
596
+ * Generated by @egdesk/next-api-plugin — customize styling in your app; do not post JSON through your server.
597
+ */
598
+
599
+ import { useCallback, useState } from 'react';
600
+ import {
601
+ forgetVisitorGcp,
602
+ getStoredVisitorGcpHandle,
603
+ registerVisitorGcp,
604
+ resolveEgdeskPublicUrl,
605
+ setStoredVisitorGcpHandle,
606
+ startVisitorGoogleLogin,
607
+ } from '@/egdesk-visitor-google';
608
+
609
+ export function VisitorGcpByoPanel() {
610
+ const [handle, setHandle] = useState(() => getStoredVisitorGcpHandle() || '');
611
+ const [message, setMessage] = useState<string | null>(null);
612
+ const [busy, setBusy] = useState(false);
613
+
614
+ const onUpload = useCallback(async (file: File) => {
615
+ setBusy(true);
616
+ setMessage(null);
617
+ try {
618
+ const text = await file.text();
619
+ const json = JSON.parse(text);
620
+ const result = await registerVisitorGcp({
621
+ oauthClientJson: json,
622
+ handle: handle.trim() || undefined,
623
+ egdeskPublicUrl: resolveEgdeskPublicUrl(),
624
+ });
625
+ const nextHandle = result.handle as string;
626
+ setHandle(nextHandle);
627
+ setStoredVisitorGcpHandle(nextHandle);
628
+ setMessage(
629
+ \`Registered \${result.clientIdMasked}. Redirect URI: \${result.redirectUriToRegister}\`,
630
+ );
631
+ } catch (err) {
632
+ setMessage(err instanceof Error ? err.message : String(err));
633
+ } finally {
634
+ setBusy(false);
635
+ }
636
+ }, [handle]);
637
+
638
+ const onSignIn = useCallback(async () => {
639
+ const h = handle.trim() || getStoredVisitorGcpHandle();
640
+ if (!h) {
641
+ setMessage('Register a Web client JSON first.');
642
+ return;
643
+ }
644
+ await startVisitorGoogleLogin({ gcp: 'self', handle: h });
645
+ }, [handle]);
646
+
647
+ const onForget = useCallback(async () => {
648
+ const h = handle.trim();
649
+ if (!h) return;
650
+ setBusy(true);
651
+ try {
652
+ await forgetVisitorGcp(h);
653
+ setStoredVisitorGcpHandle(null);
654
+ setHandle('');
655
+ setMessage('Forgot GCP profile on this site.');
656
+ } catch (err) {
657
+ setMessage(err instanceof Error ? err.message : String(err));
658
+ } finally {
659
+ setBusy(false);
660
+ }
661
+ }, [handle]);
662
+
663
+ return (
664
+ <section style={{ maxWidth: 480, margin: '1rem 0', fontFamily: 'system-ui, sans-serif' }}>
665
+ <h2 style={{ fontSize: '1.1rem' }}>Bring your own Google Cloud project</h2>
666
+ <p style={{ fontSize: '0.9rem', color: '#444' }}>
667
+ Upload a Web application OAuth client JSON. Secrets stay on the operator&apos;s EGDesk PC, not this site&apos;s server.
668
+ </p>
669
+ <label style={{ display: 'block', marginBottom: 8 }}>
670
+ Handle (optional)
671
+ <input
672
+ value={handle}
673
+ onChange={(e) => setHandle(e.target.value)}
674
+ placeholder="auto-generated if empty"
675
+ style={{ display: 'block', width: '100%', marginTop: 4 }}
676
+ />
677
+ </label>
678
+ <input
679
+ type="file"
680
+ accept=".json,application/json"
681
+ disabled={busy}
682
+ onChange={(e) => {
683
+ const f = e.target.files?.[0];
684
+ if (f) void onUpload(f);
685
+ }}
686
+ />
687
+ <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
688
+ <button type="button" disabled={busy} onClick={() => void onSignIn()}>
689
+ Sign in with my GCP
690
+ </button>
691
+ <button type="button" disabled={busy || !handle.trim()} onClick={() => void onForget()}>
692
+ Forget my GCP
693
+ </button>
694
+ </div>
695
+ {message && <p style={{ fontSize: '0.85rem', marginTop: 12 }}>{message}</p>}
696
+ </section>
697
+ );
698
+ }
699
+ `;
538
700
  function ensureVisitorAuthConfig(projectPath) {
539
701
  const configPath = path.join(projectPath, 'egdesk.visitor-auth.ts');
540
702
  if (fs.existsSync(configPath))
@@ -548,6 +710,7 @@ function generateVisitorAuth(projectPath) {
548
710
  ensureVisitorAuthConfig(projectPath);
549
711
  writeGenerated(path.join(appDir, 'auth', 'callback', 'page.tsx'), CALLBACK_PAGE);
550
712
  writeGenerated(path.join(projectPath, 'egdesk-visitor-google.ts'), VISITOR_HELPERS);
713
+ writeGenerated(path.join(projectPath, 'egdesk-visitor-gcp-byo.tsx'), VISITOR_GCP_BYO_COMPONENT);
551
714
  removeIfExists(path.join(appDir, 'api', 'visitor-google', 'route.ts'));
552
715
  removeIfExists(path.join(appDir, 'api', 'visitor-google', 'route.js'));
553
716
  }
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.111";
11
+ export declare const COMPATIBLE_APP_VERSION = "1.4.115";
12
12
  export interface SetupOptions {
13
13
  egdeskUrl?: string;
14
14
  /** Production EGDesk server URL — written to .env.production.local. Falls back to egdeskUrl. */
package/dist/index.js CHANGED
@@ -46,7 +46,7 @@ exports.setupNextApiPlugin = setupNextApiPlugin;
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.111';
49
+ exports.COMPATIBLE_APP_VERSION = '1.4.115';
50
50
  const fs = __importStar(require("fs"));
51
51
  const path = __importStar(require("path"));
52
52
  const setup_userdata_1 = require("./setup-userdata");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@egdesk/next-api-plugin",
3
- "version": "1.5.106",
3
+ "version": "1.5.110",
4
4
  "description": "Next.js plugin for EGDesk database proxy integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",