@egdesk/next-api-plugin 1.5.84 → 1.5.100

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
@@ -75,12 +75,25 @@ Published sites do **not** receive `SUPABASE_URL` or the anon key. Visitor Googl
75
75
 
76
76
  Add the **EGDesk** callback (not each site origin) to **Supabase → Authentication → URL Configuration → Redirect URLs**:
77
77
 
78
- - Local (owner and localhost visitor): `http://localhost:54321/auth/callback` exactly. Do not add a path or `?vid=` — Supabase will fall back to the Site URL (`egdesk.cloud`).
78
+ - Local (owner and loopback visitor): `http://localhost:54321/auth/callback` exactly. Do not add a path or `?vid=` — Supabase will fall back to the Site URL (`egdesk.cloud`).
79
79
  - Tunnel: `https://tunneling-service.onrender.com/t/{tunnelId}/visitor-auth/callback/**` or `https://tunneling-service.onrender.com/**`
80
80
 
81
81
  Do not put the pending id in a query string (`?vid=`) — extra query params make Supabase fall back to the Site URL (`egdesk.cloud`).
82
82
 
83
- On a published host, `NEXT_PUBLIC_EGDESK_API_URL` must be the tunnel MCP root (`https://…/t/{id}`), not `http://localhost:8080`. The generated helper will refuse that localhost fallback in the browser.
83
+ ### OAuth bounce by site type
84
+
85
+ | Where the visitor opens the site | Google `redirectTo` (allowlisted) |
86
+ |----------------------------------|-----------------------------------|
87
+ | `localhost` / `127.0.0.1` (:4000 dev, :3000 prod) | `http://localhost:54321/auth/callback` |
88
+ | LAN IP (`192.168.x.x`, etc.) + tunnel env | `{tunnel MCP root}/visitor-auth/callback/{pendingId}` |
89
+ | LAN IP, no tunnel (same PC as EGDesk only) | `http://localhost:54321/auth/callback` |
90
+ | Tunnel URL or custom domain | `{MCP root}/visitor-auth/callback/{pendingId}` |
91
+
92
+ Hosted-coding **prod** (`:3000`) is built with `basePath` `/t/{tunnelId}/p/{project}` — use that prefix in URLs (e.g. `http://localhost:3000/t/{id}/p/my-app/visitor-auth`). EGDesk injects `NEXT_PUBLIC_EGDESK_API_URL` and `NEXT_PUBLIC_EGDESK_API_KEY` at build and `next start` so the client bundle and middleware proxy agree.
93
+
94
+ `localhost` and `127.0.0.1` on the same port are treated as the same site for session checks, but remain distinct origin strings in storage.
95
+
96
+ On a published host, `NEXT_PUBLIC_EGDESK_API_URL` must be the tunnel MCP root (`https://…/t/{id}`), not `http://localhost:8080`. The generated helper will refuse that localhost fallback in the browser on non-dev hosts.
84
97
 
85
98
  Owner MCP (`startDriveAuthLogin`) is a separate credential on the EGDesk machine. Visitor login does not overwrite it.
86
99
 
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Generate Next.js App Router handlers that proxy chunked uploads to EGDesk MCP.
3
+ * Browser → these routes (tunnel-safe small chunks) → localhost MCP /user-data/uploads/*
4
+ */
5
+ export declare function generateChunkedUploadRoutes(projectPath: string): void;
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ /**
3
+ * Generate Next.js App Router handlers that proxy chunked uploads to EGDesk MCP.
4
+ * Browser → these routes (tunnel-safe small chunks) → localhost MCP /user-data/uploads/*
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.generateChunkedUploadRoutes = generateChunkedUploadRoutes;
41
+ const fs = __importStar(require("fs"));
42
+ const path = __importStar(require("path"));
43
+ const os = __importStar(require("os"));
44
+ function usesSrcDirectory(projectPath) {
45
+ const srcAppPath = path.join(projectPath, 'src', 'app');
46
+ return fs.existsSync(srcAppPath);
47
+ }
48
+ function writeFile(filePath, content) {
49
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
50
+ fs.writeFileSync(filePath, content.replace(/\r?\n/g, os.EOL), 'utf-8');
51
+ console.log(`✅ Generated ${filePath}`);
52
+ }
53
+ const SHARED_HELPER = `import { NextRequest, NextResponse } from 'next/server';
54
+
55
+ function resolveEgdeskMcpApiUrl(): string {
56
+ const internal = process.env.EGDESK_MCP_INTERNAL_URL;
57
+ if (internal && internal.trim()) return internal.replace(/\\/$/, '');
58
+ return (process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080').replace(/\\/$/, '');
59
+ }
60
+
61
+ function buildEgdeskHeaders(extra?: HeadersInit): HeadersInit {
62
+ const headers: Record<string, string> = {};
63
+ const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
64
+ const projectId = process.env.NEXT_PUBLIC_EGDESK_PROJECT_ID;
65
+ const egdeskEnv = process.env.NEXT_PUBLIC_EGDESK_ENV;
66
+ if (apiKey) headers['X-Api-Key'] = apiKey;
67
+ if (projectId) headers['X-EGDesk-Project-Id'] = projectId;
68
+ if (egdeskEnv) headers['X-EGDesk-Env'] = egdeskEnv;
69
+ if (extra) {
70
+ const e = new Headers(extra);
71
+ e.forEach((v, k) => {
72
+ headers[k] = v;
73
+ });
74
+ }
75
+ return headers;
76
+ }
77
+
78
+ export async function proxyJson(pathname: string, init?: RequestInit) {
79
+ const apiUrl = resolveEgdeskMcpApiUrl();
80
+ const response = await fetch(\`\${apiUrl}\${pathname}\`, {
81
+ ...init,
82
+ headers: buildEgdeskHeaders(init?.headers),
83
+ cache: 'no-store',
84
+ });
85
+ const text = await response.text();
86
+ let body: any = text;
87
+ try {
88
+ body = text ? JSON.parse(text) : {};
89
+ } catch {
90
+ body = { success: false, error: text || \`HTTP \${response.status}\` };
91
+ }
92
+ return NextResponse.json(body, { status: response.status });
93
+ }
94
+
95
+ export async function proxyRaw(
96
+ pathname: string,
97
+ method: string,
98
+ body: ArrayBuffer | null,
99
+ headers?: HeadersInit,
100
+ ) {
101
+ const apiUrl = resolveEgdeskMcpApiUrl();
102
+ const response = await fetch(\`\${apiUrl}\${pathname}\`, {
103
+ method,
104
+ headers: buildEgdeskHeaders(headers),
105
+ body: body && body.byteLength > 0 ? body : undefined,
106
+ // @ts-expect-error duplex required for streaming bodies in some runtimes
107
+ duplex: 'half',
108
+ cache: 'no-store',
109
+ });
110
+ const text = await response.text();
111
+ let parsed: any = text;
112
+ try {
113
+ parsed = text ? JSON.parse(text) : {};
114
+ } catch {
115
+ parsed = { success: false, error: text || \`HTTP \${response.status}\` };
116
+ }
117
+ return NextResponse.json(parsed, { status: response.status });
118
+ }
119
+ `;
120
+ function generateChunkedUploadRoutes(projectPath) {
121
+ const hasSrc = usesSrcDirectory(projectPath);
122
+ const appRoot = hasSrc ? path.join(projectPath, 'src', 'app') : path.join(projectPath, 'app');
123
+ const base = path.join(appRoot, 'api', 'user', 'files', 'uploads');
124
+ writeFile(path.join(base, '_proxy.ts'), SHARED_HELPER);
125
+ writeFile(path.join(base, 'route.ts'), `import { NextRequest } from 'next/server';
126
+ import { proxyJson } from './_proxy';
127
+
128
+ /** POST /api/user/files/uploads — init chunked upload */
129
+ export async function POST(request: NextRequest) {
130
+ const body = await request.text();
131
+ return proxyJson('/user-data/uploads', {
132
+ method: 'POST',
133
+ headers: { 'Content-Type': 'application/json' },
134
+ body,
135
+ });
136
+ }
137
+ `);
138
+ writeFile(path.join(base, '[id]', 'route.ts'), `import { NextRequest } from 'next/server';
139
+ import { proxyJson } from '../_proxy';
140
+
141
+ /** GET /api/user/files/uploads/:id — status */
142
+ export async function GET(
143
+ _request: NextRequest,
144
+ ctx: { params: Promise<{ id: string }> | { id: string } },
145
+ ) {
146
+ const params = await Promise.resolve(ctx.params);
147
+ return proxyJson(\`/user-data/uploads/\${params.id}\`, { method: 'GET' });
148
+ }
149
+
150
+ /** DELETE /api/user/files/uploads/:id — abort */
151
+ export async function DELETE(
152
+ _request: NextRequest,
153
+ ctx: { params: Promise<{ id: string }> | { id: string } },
154
+ ) {
155
+ const params = await Promise.resolve(ctx.params);
156
+ return proxyJson(\`/user-data/uploads/\${params.id}\`, { method: 'DELETE' });
157
+ }
158
+ `);
159
+ writeFile(path.join(base, '[id]', 'chunks', '[index]', 'route.ts'), `import { NextRequest } from 'next/server';
160
+ import { proxyRaw } from '../../../_proxy';
161
+
162
+ /** PUT /api/user/files/uploads/:id/chunks/:index — raw octet-stream chunk */
163
+ export async function PUT(
164
+ request: NextRequest,
165
+ ctx: { params: Promise<{ id: string; index: string }> | { id: string; index: string } },
166
+ ) {
167
+ const params = await Promise.resolve(ctx.params);
168
+ const buf = await request.arrayBuffer();
169
+ const sha = request.headers.get('x-chunk-sha256');
170
+ return proxyRaw(
171
+ \`/user-data/uploads/\${params.id}/chunks/\${params.index}\`,
172
+ 'PUT',
173
+ buf,
174
+ {
175
+ 'Content-Type': 'application/octet-stream',
176
+ ...(sha ? { 'x-chunk-sha256': sha } : {}),
177
+ },
178
+ );
179
+ }
180
+ `);
181
+ writeFile(path.join(base, '[id]', 'complete', 'route.ts'), `import { NextRequest } from 'next/server';
182
+ import { proxyJson } from '../../_proxy';
183
+
184
+ /** POST /api/user/files/uploads/:id/complete */
185
+ export async function POST(
186
+ _request: NextRequest,
187
+ ctx: { params: Promise<{ id: string }> | { id: string } },
188
+ ) {
189
+ const params = await Promise.resolve(ctx.params);
190
+ return proxyJson(\`/user-data/uploads/\${params.id}/complete\`, {
191
+ method: 'POST',
192
+ headers: { 'Content-Type': 'application/json' },
193
+ body: '{}',
194
+ });
195
+ }
196
+ `);
197
+ }