@egdesk/next-api-plugin 1.5.114 → 1.5.116

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.
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Pure logic for canonical custom-domain redirects (middleware / proxy codegen).
3
+ * Unit-tested here; the same logic is embedded in generated middleware.ts / proxy.ts.
4
+ */
5
+ export type CanonicalRedirectHeaders = Record<string, string | undefined>;
6
+ export type CanonicalRedirectInput = {
7
+ method: string;
8
+ pathname: string;
9
+ search: string;
10
+ nextUrlHost: string;
11
+ headers: CanonicalRedirectHeaders;
12
+ getEnv: (key: string) => string | undefined;
13
+ };
14
+ export declare function originFromEnvValue(value?: string | null): string | null;
15
+ export declare function runtimeEnv(getEnv: (key: string) => string | undefined, key: string): string | undefined;
16
+ export declare function resolvePublicRequestOrigin(input: {
17
+ headers: CanonicalRedirectHeaders;
18
+ nextUrlHost: string;
19
+ }): string | null;
20
+ export declare function normalizeHostname(host: string): string;
21
+ export declare function isKnownTunnelHostname(hostname: string): boolean;
22
+ export declare function isWwwAlternateOfCanonical(requestHost: string, canonicalOrigin: string): boolean;
23
+ export declare function resolveCanonicalVisitorOrigin(input: CanonicalRedirectInput): string | null;
24
+ export declare function isCanonicalRedirectEnabled(input: CanonicalRedirectInput): boolean;
25
+ export declare function resolveEgdeskBasePathForRedirect(input: CanonicalRedirectInput): string;
26
+ export declare function stripBasePathFromPathname(pathname: string, basePath: string): string;
27
+ export declare function shouldSkipCanonicalRedirectPath(pathname: string, basePath?: string): boolean;
28
+ /** True when the URL is a shared-host tunnel coding path (/t/{id}/p/{project}/...). */
29
+ export declare function isTunnelPrefixedCodingUrl(pathname: string, basePath?: string): boolean;
30
+ export declare function isTunnelUrlCanonicalRedirectOptIn(input: CanonicalRedirectInput): boolean;
31
+ export type CanonicalVisitorRedirectResult = {
32
+ url: string;
33
+ /** 308 for permanent www → apex; 307 for other canonical redirects (avoid sticky 308 cache). */
34
+ status: number;
35
+ };
36
+ /**
37
+ * Returns redirect URL and HTTP status, or null if no redirect.
38
+ */
39
+ export declare function resolveCanonicalVisitorRedirect(input: CanonicalRedirectInput): CanonicalVisitorRedirectResult | null;
40
+ /** Returns absolute redirect URL, or null if no redirect. */
41
+ export declare function computeCanonicalVisitorRedirectTarget(input: CanonicalRedirectInput): string | null;
42
+ /** Source embedded into generated middleware.ts / proxy.ts (keep in sync with tests). */
43
+ export declare function canonicalVisitorRedirectMiddlewareSource(): string;
@@ -0,0 +1,413 @@
1
+ "use strict";
2
+ /**
3
+ * Pure logic for canonical custom-domain redirects (middleware / proxy codegen).
4
+ * Unit-tested here; the same logic is embedded in generated middleware.ts / proxy.ts.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.originFromEnvValue = originFromEnvValue;
8
+ exports.runtimeEnv = runtimeEnv;
9
+ exports.resolvePublicRequestOrigin = resolvePublicRequestOrigin;
10
+ exports.normalizeHostname = normalizeHostname;
11
+ exports.isKnownTunnelHostname = isKnownTunnelHostname;
12
+ exports.isWwwAlternateOfCanonical = isWwwAlternateOfCanonical;
13
+ exports.resolveCanonicalVisitorOrigin = resolveCanonicalVisitorOrigin;
14
+ exports.isCanonicalRedirectEnabled = isCanonicalRedirectEnabled;
15
+ exports.resolveEgdeskBasePathForRedirect = resolveEgdeskBasePathForRedirect;
16
+ exports.stripBasePathFromPathname = stripBasePathFromPathname;
17
+ exports.shouldSkipCanonicalRedirectPath = shouldSkipCanonicalRedirectPath;
18
+ exports.isTunnelPrefixedCodingUrl = isTunnelPrefixedCodingUrl;
19
+ exports.isTunnelUrlCanonicalRedirectOptIn = isTunnelUrlCanonicalRedirectOptIn;
20
+ exports.resolveCanonicalVisitorRedirect = resolveCanonicalVisitorRedirect;
21
+ exports.computeCanonicalVisitorRedirectTarget = computeCanonicalVisitorRedirectTarget;
22
+ exports.canonicalVisitorRedirectMiddlewareSource = canonicalVisitorRedirectMiddlewareSource;
23
+ const TUNNEL_HOST_SUFFIXES = ['.egdesk.cloud'];
24
+ const TUNNEL_HOSTS = new Set(['tunneling-service.onrender.com', 'egdesk.cloud', 'www.egdesk.cloud']);
25
+ function originFromEnvValue(value) {
26
+ const raw = (value || '').trim();
27
+ if (!raw)
28
+ return null;
29
+ try {
30
+ return new URL(raw).origin;
31
+ }
32
+ catch {
33
+ try {
34
+ return new URL(`https://${raw}`).origin;
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ }
41
+ function runtimeEnv(getEnv, key) {
42
+ try {
43
+ return getEnv(key);
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ }
49
+ function headerFirst(value) {
50
+ if (!value)
51
+ return undefined;
52
+ const first = value.split(',')[0]?.trim();
53
+ return first || undefined;
54
+ }
55
+ function resolvePublicRequestOrigin(input) {
56
+ const host = headerFirst(input.headers['x-forwarded-host']) ||
57
+ headerFirst(input.headers['host']) ||
58
+ input.nextUrlHost;
59
+ if (!host)
60
+ return null;
61
+ const proto = headerFirst(input.headers['x-forwarded-proto']) ||
62
+ (host.includes('localhost') || host.startsWith('127.0.0.1') ? 'http' : 'https');
63
+ try {
64
+ return new URL(`${proto}://${host}`).origin;
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ }
70
+ function normalizeHostname(host) {
71
+ return host.toLowerCase().replace(/:\d+$/, '');
72
+ }
73
+ function isKnownTunnelHostname(hostname) {
74
+ const h = normalizeHostname(hostname);
75
+ if (TUNNEL_HOSTS.has(h))
76
+ return true;
77
+ return TUNNEL_HOST_SUFFIXES.some((suffix) => h.endsWith(suffix));
78
+ }
79
+ function isWwwAlternateOfCanonical(requestHost, canonicalOrigin) {
80
+ try {
81
+ const canonicalHost = new URL(canonicalOrigin).hostname.toLowerCase();
82
+ if (canonicalHost.startsWith('www.'))
83
+ return false;
84
+ const bare = canonicalHost.replace(/^www\./, '');
85
+ const h = normalizeHostname(requestHost);
86
+ return h === `www.${bare}`;
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ }
92
+ function resolveCanonicalVisitorOrigin(input) {
93
+ const fromHeader = originFromEnvValue(input.headers['x-egdesk-canonical-visitor-origin']);
94
+ if (fromHeader)
95
+ return fromHeader;
96
+ const fromRuntime = runtimeEnv(input.getEnv, 'EGDESK_CANONICAL_VISITOR_ORIGIN') ||
97
+ runtimeEnv(input.getEnv, 'NEXT_PUBLIC_EGDESK_VISITOR_ORIGIN');
98
+ return originFromEnvValue(fromRuntime);
99
+ }
100
+ function isCanonicalRedirectEnabled(input) {
101
+ const fromHeader = (input.headers['x-egdesk-canonical-redirect-enabled'] || '').trim();
102
+ if (fromHeader === '1' || fromHeader.toLowerCase() === 'true')
103
+ return true;
104
+ return runtimeEnv(input.getEnv, 'EGDESK_CANONICAL_REDIRECT_ENABLED') === '1';
105
+ }
106
+ function isHtmlNavigation(input) {
107
+ const accept = input.headers['accept'] || '';
108
+ const secFetchDest = input.headers['sec-fetch-dest'];
109
+ if (accept.includes('text/html') || accept.includes('application/xhtml+xml'))
110
+ return true;
111
+ if (!secFetchDest)
112
+ return true;
113
+ return secFetchDest === 'document' || secFetchDest === 'iframe';
114
+ }
115
+ function resolveEgdeskBasePathForRedirect(input) {
116
+ const fromHeader = (input.headers['x-egdesk-base-path'] || '').trim();
117
+ if (fromHeader)
118
+ return fromHeader.replace(/\/$/, '');
119
+ return (runtimeEnv(input.getEnv, 'EGDESK_BASE_PATH') ||
120
+ runtimeEnv(input.getEnv, 'NEXT_PUBLIC_EGDESK_BASE_PATH') ||
121
+ '').replace(/\/$/, '');
122
+ }
123
+ function stripBasePathFromPathname(pathname, basePath) {
124
+ if (!basePath)
125
+ return pathname;
126
+ if (pathname === basePath || pathname.startsWith(`${basePath}/`)) {
127
+ return pathname.slice(basePath.length) || '/';
128
+ }
129
+ return pathname;
130
+ }
131
+ function shouldSkipCanonicalRedirectPath(pathname, basePath = '') {
132
+ const path = stripBasePathFromPathname(pathname, basePath);
133
+ if (path.startsWith('/api/'))
134
+ return true;
135
+ if (path.startsWith('/_next/'))
136
+ return true;
137
+ if (path.includes('__'))
138
+ return true;
139
+ return false;
140
+ }
141
+ /** True when the URL is a shared-host tunnel coding path (/t/{id}/p/{project}/...). */
142
+ function isTunnelPrefixedCodingUrl(pathname, basePath = '') {
143
+ if (/^\/t\/[^/]+\/p\/[^/]+(\/|$)/.test(pathname))
144
+ return true;
145
+ const stripped = stripBasePathFromPathname(pathname, basePath);
146
+ if (stripped !== pathname && /^\/t\/[^/]+\/p\/[^/]+(\/|$)/.test(stripped))
147
+ return true;
148
+ return false;
149
+ }
150
+ function isTunnelUrlCanonicalRedirectOptIn(input) {
151
+ const fromHeader = (input.headers['x-egdesk-canonical-redirect-tunnel-urls'] || '').trim();
152
+ if (fromHeader === '1' || fromHeader.toLowerCase() === 'true')
153
+ return true;
154
+ return runtimeEnv(input.getEnv, 'EGDESK_CANONICAL_REDIRECT_TUNNEL_URLS') === '1';
155
+ }
156
+ /**
157
+ * Returns redirect URL and HTTP status, or null if no redirect.
158
+ */
159
+ function resolveCanonicalVisitorRedirect(input) {
160
+ if (!isCanonicalRedirectEnabled(input))
161
+ return null;
162
+ const canonical = resolveCanonicalVisitorOrigin(input);
163
+ if (!canonical)
164
+ return null;
165
+ if (input.method !== 'GET')
166
+ return null;
167
+ const basePath = resolveEgdeskBasePathForRedirect(input);
168
+ if (shouldSkipCanonicalRedirectPath(input.pathname, basePath))
169
+ return null;
170
+ if (!isHtmlNavigation(input))
171
+ return null;
172
+ const publicOrigin = resolvePublicRequestOrigin({
173
+ headers: input.headers,
174
+ nextUrlHost: input.nextUrlHost,
175
+ });
176
+ if (publicOrigin && publicOrigin === canonical)
177
+ return null;
178
+ const requestHost = normalizeHostname(headerFirst(input.headers['x-forwarded-host']) ||
179
+ headerFirst(input.headers['host']) ||
180
+ input.nextUrlHost);
181
+ const canonicalHost = normalizeHostname(new URL(canonical).host);
182
+ if (requestHost === canonicalHost)
183
+ return null;
184
+ const wwwAlias = isWwwAlternateOfCanonical(requestHost, canonical);
185
+ if (wwwAlias) {
186
+ // www → apex on the same project (custom domain alias).
187
+ }
188
+ else if (isKnownTunnelHostname(requestHost)) {
189
+ if (isTunnelPrefixedCodingUrl(input.pathname, basePath) &&
190
+ !isTunnelUrlCanonicalRedirectOptIn(input)) {
191
+ return null;
192
+ }
193
+ }
194
+ else {
195
+ return null;
196
+ }
197
+ let path = stripBasePathFromPathname(input.pathname, basePath);
198
+ const url = new URL((path.startsWith('/') ? path : `/${path}`) + (input.search || ''), canonical).toString();
199
+ if (publicOrigin) {
200
+ try {
201
+ const current = new URL((path.startsWith('/') ? path : `/${path}`) + (input.search || ''), publicOrigin).toString();
202
+ if (current === url)
203
+ return null;
204
+ }
205
+ catch {
206
+ // ignore
207
+ }
208
+ }
209
+ return { url, status: wwwAlias ? 308 : 307 };
210
+ }
211
+ /** Returns absolute redirect URL, or null if no redirect. */
212
+ function computeCanonicalVisitorRedirectTarget(input) {
213
+ return resolveCanonicalVisitorRedirect(input)?.url ?? null;
214
+ }
215
+ /** Source embedded into generated middleware.ts / proxy.ts (keep in sync with tests). */
216
+ function canonicalVisitorRedirectMiddlewareSource() {
217
+ return `
218
+ function originFromEnvValue(value?: string | null): string | null {
219
+ const raw = (value || '').trim();
220
+ if (!raw) return null;
221
+ try {
222
+ return new URL(raw).origin;
223
+ } catch {
224
+ try {
225
+ return new URL(\`https://\${raw}\`).origin;
226
+ } catch {
227
+ return null;
228
+ }
229
+ }
230
+ }
231
+
232
+ function runtimeEnv(key: string): string | undefined {
233
+ try {
234
+ if (typeof process === 'undefined' || !process.env) return undefined;
235
+ return process.env[key];
236
+ } catch {
237
+ return undefined;
238
+ }
239
+ }
240
+
241
+ function headerFirst(value?: string | null): string | undefined {
242
+ if (!value) return undefined;
243
+ const first = value.split(',')[0]?.trim();
244
+ return first || undefined;
245
+ }
246
+
247
+ function resolvePublicRequestOrigin(request: NextRequest): string | null {
248
+ const host =
249
+ headerFirst(request.headers.get('x-forwarded-host')) ||
250
+ headerFirst(request.headers.get('host')) ||
251
+ request.nextUrl.host;
252
+ if (!host) return null;
253
+ const proto =
254
+ headerFirst(request.headers.get('x-forwarded-proto')) ||
255
+ (host.includes('localhost') || host.startsWith('127.0.0.1') ? 'http' : 'https');
256
+ try {
257
+ return new URL(\`\${proto}://\${host}\`).origin;
258
+ } catch {
259
+ return null;
260
+ }
261
+ }
262
+
263
+ function normalizeHostname(host: string): string {
264
+ return host.toLowerCase().replace(/:\\d+$/, '');
265
+ }
266
+
267
+ function isKnownTunnelHostname(hostname: string): boolean {
268
+ const h = normalizeHostname(hostname);
269
+ if (
270
+ h === 'tunneling-service.onrender.com' ||
271
+ h === 'egdesk.cloud' ||
272
+ h === 'www.egdesk.cloud'
273
+ ) {
274
+ return true;
275
+ }
276
+ return h.endsWith('.egdesk.cloud');
277
+ }
278
+
279
+ function isWwwAlternateOfCanonical(requestHost: string, canonicalOrigin: string): boolean {
280
+ try {
281
+ const canonicalHost = new URL(canonicalOrigin).hostname.toLowerCase();
282
+ if (canonicalHost.startsWith('www.')) return false;
283
+ const bare = canonicalHost.replace(/^www\\./, '');
284
+ const h = normalizeHostname(requestHost);
285
+ return h === \`www.\${bare}\`;
286
+ } catch {
287
+ return false;
288
+ }
289
+ }
290
+
291
+ function resolveCanonicalVisitorOrigin(request: NextRequest): string | null {
292
+ const fromHeader = originFromEnvValue(request.headers.get('x-egdesk-canonical-visitor-origin'));
293
+ if (fromHeader) return fromHeader;
294
+ const fromRuntime =
295
+ runtimeEnv('EGDESK_CANONICAL_VISITOR_ORIGIN') ||
296
+ runtimeEnv('NEXT_PUBLIC_EGDESK_VISITOR_ORIGIN');
297
+ return originFromEnvValue(fromRuntime);
298
+ }
299
+
300
+ function isCanonicalRedirectEnabled(request: NextRequest): boolean {
301
+ const fromHeader = (request.headers.get('x-egdesk-canonical-redirect-enabled') || '').trim();
302
+ if (fromHeader === '1' || fromHeader.toLowerCase() === 'true') return true;
303
+ return runtimeEnv('EGDESK_CANONICAL_REDIRECT_ENABLED') === '1';
304
+ }
305
+
306
+ function isHtmlNavigation(request: NextRequest): boolean {
307
+ const accept = request.headers.get('accept') || '';
308
+ const secFetchDest = request.headers.get('sec-fetch-dest');
309
+ if (accept.includes('text/html') || accept.includes('application/xhtml+xml')) return true;
310
+ if (!secFetchDest) return true;
311
+ return secFetchDest === 'document' || secFetchDest === 'iframe';
312
+ }
313
+
314
+ function resolveEgdeskBasePathForRedirect(request: NextRequest): string {
315
+ const fromHeader = (request.headers.get('x-egdesk-base-path') || '').trim();
316
+ if (fromHeader) return fromHeader.replace(/\\/$/, '');
317
+ return (
318
+ runtimeEnv('EGDESK_BASE_PATH') || runtimeEnv('NEXT_PUBLIC_EGDESK_BASE_PATH') || ''
319
+ ).replace(/\\/$/, '');
320
+ }
321
+
322
+ function stripBasePathFromPathname(pathname: string, basePath: string): string {
323
+ if (!basePath) return pathname;
324
+ if (pathname === basePath || pathname.startsWith(basePath + '/')) {
325
+ return pathname.slice(basePath.length) || '/';
326
+ }
327
+ return pathname;
328
+ }
329
+
330
+ function shouldSkipCanonicalRedirectPath(pathname: string, basePath = ''): boolean {
331
+ const path = stripBasePathFromPathname(pathname, basePath);
332
+ if (path.startsWith('/api/')) return true;
333
+ if (path.startsWith('/_next/')) return true;
334
+ if (path.includes('__')) return true;
335
+ return false;
336
+ }
337
+
338
+ function isTunnelPrefixedCodingUrl(pathname: string, basePath = ''): boolean {
339
+ if (/^\\/t\\/[^/]+\\/p\\/[^/]+(\\/|$)/.test(pathname)) return true;
340
+ const stripped = stripBasePathFromPathname(pathname, basePath);
341
+ if (stripped !== pathname && /^\\/t\\/[^/]+\\/p\\/[^/]+(\\/|$)/.test(stripped)) return true;
342
+ return false;
343
+ }
344
+
345
+ function isTunnelUrlCanonicalRedirectOptIn(request: NextRequest): boolean {
346
+ const fromHeader = (request.headers.get('x-egdesk-canonical-redirect-tunnel-urls') || '').trim();
347
+ if (fromHeader === '1' || fromHeader.toLowerCase() === 'true') return true;
348
+ return runtimeEnv('EGDESK_CANONICAL_REDIRECT_TUNNEL_URLS') === '1';
349
+ }
350
+
351
+ function resolveCanonicalVisitorRedirect(request: NextRequest): { url: string; status: number } | null {
352
+ if (!isCanonicalRedirectEnabled(request)) return null;
353
+ const canonical = resolveCanonicalVisitorOrigin(request);
354
+ if (!canonical) return null;
355
+ if (request.method !== 'GET') return null;
356
+ const { pathname, search } = request.nextUrl;
357
+ const basePath = resolveEgdeskBasePathForRedirect(request);
358
+ if (shouldSkipCanonicalRedirectPath(pathname, basePath)) return null;
359
+ if (!isHtmlNavigation(request)) return null;
360
+
361
+ const publicOrigin = resolvePublicRequestOrigin(request);
362
+ if (publicOrigin && publicOrigin === canonical) return null;
363
+
364
+ const requestHost = normalizeHostname(
365
+ headerFirst(request.headers.get('x-forwarded-host')) ||
366
+ headerFirst(request.headers.get('host')) ||
367
+ request.nextUrl.host,
368
+ );
369
+ const canonicalHost = normalizeHostname(new URL(canonical).host);
370
+ if (requestHost === canonicalHost) return null;
371
+
372
+ const wwwAlias = isWwwAlternateOfCanonical(requestHost, canonical);
373
+ if (wwwAlias) {
374
+ // www → apex on the same project (custom domain alias).
375
+ } else if (isKnownTunnelHostname(requestHost)) {
376
+ if (
377
+ isTunnelPrefixedCodingUrl(pathname, basePath) &&
378
+ !isTunnelUrlCanonicalRedirectOptIn(request)
379
+ ) {
380
+ return null;
381
+ }
382
+ } else {
383
+ return null;
384
+ }
385
+
386
+ let path = stripBasePathFromPathname(pathname, basePath);
387
+ const url = new URL(
388
+ (path.startsWith('/') ? path : \`/\${path}\`) + search,
389
+ canonical,
390
+ ).toString();
391
+
392
+ if (publicOrigin) {
393
+ try {
394
+ const current = new URL(
395
+ (path.startsWith('/') ? path : \`/\${path}\`) + search,
396
+ publicOrigin,
397
+ ).toString();
398
+ if (current === url) return null;
399
+ } catch {
400
+ // ignore
401
+ }
402
+ }
403
+
404
+ return { url, status: wwwAlias ? 308 : 307 };
405
+ }
406
+
407
+ function maybeRedirectToCanonicalVisitorSite(request: NextRequest): NextResponse | null {
408
+ const resolved = resolveCanonicalVisitorRedirect(request);
409
+ if (!resolved) return null;
410
+ return NextResponse.redirect(resolved.url, resolved.status);
411
+ }
412
+ `.trim();
413
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const strict_1 = __importDefault(require("node:assert/strict"));
7
+ const node_test_1 = __importDefault(require("node:test"));
8
+ const canonical_visitor_redirect_1 = require("./canonical-visitor-redirect");
9
+ const CANON = 'https://shop.example.com';
10
+ const TUNNEL = 'tunneling-service.onrender.com';
11
+ function baseInput(overrides = {}) {
12
+ const env = {
13
+ EGDESK_CANONICAL_REDIRECT_ENABLED: '1',
14
+ EGDESK_CANONICAL_VISITOR_ORIGIN: CANON,
15
+ EGDESK_BASE_PATH: '/t/demo/p/MyApp',
16
+ };
17
+ const getEnv = overrides.getEnv ?? ((key) => env[key]);
18
+ const { getEnv: _drop, ...rest } = overrides;
19
+ return {
20
+ method: 'GET',
21
+ pathname: '/t/demo/p/MyApp/dashboard',
22
+ search: '',
23
+ nextUrlHost: 'localhost:3000',
24
+ headers: {
25
+ accept: 'text/html',
26
+ 'x-forwarded-host': TUNNEL,
27
+ 'x-forwarded-proto': 'https',
28
+ },
29
+ getEnv,
30
+ ...rest,
31
+ };
32
+ }
33
+ (0, node_test_1.default)('GET HTML on /t/.../p/... tunnel URL does not redirect without opt-in', () => {
34
+ const target = (0, canonical_visitor_redirect_1.computeCanonicalVisitorRedirectTarget)(baseInput());
35
+ strict_1.default.equal(target, null);
36
+ });
37
+ (0, node_test_1.default)('GET HTML on tunnel host redirects when tunnel URL opt-in is set', () => {
38
+ const target = (0, canonical_visitor_redirect_1.computeCanonicalVisitorRedirectTarget)(baseInput({
39
+ getEnv: (key) => {
40
+ const env = {
41
+ EGDESK_CANONICAL_REDIRECT_ENABLED: '1',
42
+ EGDESK_CANONICAL_VISITOR_ORIGIN: CANON,
43
+ EGDESK_BASE_PATH: '/t/demo/p/MyApp',
44
+ EGDESK_CANONICAL_REDIRECT_TUNNEL_URLS: '1',
45
+ };
46
+ return env[key];
47
+ },
48
+ }));
49
+ strict_1.default.equal(target, 'https://shop.example.com/dashboard');
50
+ });
51
+ (0, node_test_1.default)('canonical host via x-forwarded-host never redirects (loop guard)', () => {
52
+ const target = (0, canonical_visitor_redirect_1.computeCanonicalVisitorRedirectTarget)(baseInput({
53
+ headers: {
54
+ accept: 'text/html',
55
+ 'x-forwarded-host': 'shop.example.com',
56
+ 'x-forwarded-proto': 'https',
57
+ },
58
+ }));
59
+ strict_1.default.equal(target, null);
60
+ });
61
+ (0, node_test_1.default)('runtime canonical from gateway header does not redirect /t/.../p/... without opt-in', () => {
62
+ const target = (0, canonical_visitor_redirect_1.computeCanonicalVisitorRedirectTarget)(baseInput({
63
+ getEnv: () => undefined,
64
+ headers: {
65
+ accept: 'text/html',
66
+ 'x-forwarded-host': TUNNEL,
67
+ 'x-egdesk-canonical-visitor-origin': CANON,
68
+ 'x-egdesk-canonical-redirect-enabled': '1',
69
+ 'x-egdesk-base-path': '/t/demo/p/MyApp',
70
+ },
71
+ }));
72
+ strict_1.default.equal(target, null);
73
+ });
74
+ (0, node_test_1.default)('POST does not redirect', () => {
75
+ const target = (0, canonical_visitor_redirect_1.computeCanonicalVisitorRedirectTarget)(baseInput({ method: 'POST' }));
76
+ strict_1.default.equal(target, null);
77
+ });
78
+ (0, node_test_1.default)('/api does not redirect', () => {
79
+ const target = (0, canonical_visitor_redirect_1.computeCanonicalVisitorRedirectTarget)(baseInput({ pathname: '/t/demo/p/MyApp/api/agent/gas-bridge' }));
80
+ strict_1.default.equal(target, null);
81
+ });
82
+ (0, node_test_1.default)('/_next does not redirect', () => {
83
+ const target = (0, canonical_visitor_redirect_1.computeCanonicalVisitorRedirectTarget)(baseInput({ pathname: '/t/demo/p/MyApp/_next/static/chunk.js' }));
84
+ strict_1.default.equal(target, null);
85
+ });
86
+ (0, node_test_1.default)('__proxy paths do not redirect', () => {
87
+ const target = (0, canonical_visitor_redirect_1.computeCanonicalVisitorRedirectTarget)(baseInput({ pathname: '/t/demo/p/MyApp/__user_data_proxy' }));
88
+ strict_1.default.equal(target, null);
89
+ });
90
+ (0, node_test_1.default)('redirect disabled (tunnel-only) does not redirect', () => {
91
+ const target = (0, canonical_visitor_redirect_1.computeCanonicalVisitorRedirectTarget)(baseInput({
92
+ getEnv: (key) => (key === 'EGDESK_CANONICAL_VISITOR_ORIGIN' ? CANON : undefined),
93
+ headers: { accept: 'text/html', 'x-forwarded-host': TUNNEL },
94
+ }));
95
+ strict_1.default.equal(target, null);
96
+ });
97
+ (0, node_test_1.default)('www alternate redirects to apex canonical', () => {
98
+ const target = (0, canonical_visitor_redirect_1.computeCanonicalVisitorRedirectTarget)(baseInput({
99
+ headers: {
100
+ accept: 'text/html',
101
+ 'x-forwarded-host': 'www.shop.example.com',
102
+ 'x-forwarded-proto': 'https',
103
+ },
104
+ }));
105
+ strict_1.default.equal(target, 'https://shop.example.com/dashboard');
106
+ });
107
+ (0, node_test_1.default)('www alternate uses 308 (permanent apex)', () => {
108
+ const resolved = (0, canonical_visitor_redirect_1.resolveCanonicalVisitorRedirect)(baseInput({
109
+ headers: {
110
+ accept: 'text/html',
111
+ 'x-forwarded-host': 'www.shop.example.com',
112
+ 'x-forwarded-proto': 'https',
113
+ },
114
+ }));
115
+ strict_1.default.equal(resolved?.status, 308);
116
+ });
117
+ (0, node_test_1.default)('tunnel opt-in canonical redirect uses 307 (not sticky 308)', () => {
118
+ const resolved = (0, canonical_visitor_redirect_1.resolveCanonicalVisitorRedirect)(baseInput({
119
+ getEnv: (key) => {
120
+ const env = {
121
+ EGDESK_CANONICAL_REDIRECT_ENABLED: '1',
122
+ EGDESK_CANONICAL_VISITOR_ORIGIN: CANON,
123
+ EGDESK_BASE_PATH: '/t/demo/p/MyApp',
124
+ EGDESK_CANONICAL_REDIRECT_TUNNEL_URLS: '1',
125
+ };
126
+ return env[key];
127
+ },
128
+ }));
129
+ strict_1.default.equal(resolved?.url, 'https://shop.example.com/dashboard');
130
+ strict_1.default.equal(resolved?.status, 307);
131
+ });
132
+ (0, node_test_1.default)('untrusted random host does not redirect (open-redirect guard)', () => {
133
+ const target = (0, canonical_visitor_redirect_1.computeCanonicalVisitorRedirectTarget)(baseInput({
134
+ headers: {
135
+ accept: 'text/html',
136
+ 'x-forwarded-host': 'evil.example.net',
137
+ 'x-forwarded-proto': 'https',
138
+ },
139
+ }));
140
+ strict_1.default.equal(target, null);
141
+ });
@@ -89,6 +89,12 @@ function generateApiWrapper(projectPath) {
89
89
  */
90
90
 
91
91
  export { apiFetch, getEgdeskBasePath } from '${helpersImport}';
92
+
93
+ /** NextAuth SessionProvider basePath (EGDesk tunnel prefix + /api/auth). */
94
+ export function getNextAuthBasePath(): string {
95
+ const root = getEgdeskBasePath();
96
+ return root ? \`\${root}/api/auth\` : '/api/auth';
97
+ }
92
98
  `;
93
99
  fs.writeFileSync(apiPath, apiContent.replace(/\r?\n/g, os.EOL), 'utf-8');
94
100
  console.log(`✅ Generated ${apiPath}`);
@@ -32,4 +32,6 @@ export interface GenerateHelpersOptions {
32
32
  /** Google/Gemini API key names saved in EGDesk AI Keys Manager */
33
33
  apiKeyNames?: string[];
34
34
  }
35
+ /** Bump when generated helper/middleware behavior changes; EGDesk regenerates stale projects. */
36
+ export declare const EGDESK_HELPERS_GENERATION_VERSION = "3";
35
37
  export declare function generateHelpers(projectPath: string, options?: GenerateHelpersOptions): void;
@@ -38,6 +38,7 @@ var __importStar = (this && this.__importStar) || (function () {
38
38
  };
39
39
  })();
40
40
  Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.EGDESK_HELPERS_GENERATION_VERSION = void 0;
41
42
  exports.formatEgdeskSchemaFileContent = formatEgdeskSchemaFileContent;
42
43
  exports.generateSchemaFile = generateSchemaFile;
43
44
  exports.ensureSchemaFile = ensureSchemaFile;
@@ -132,11 +133,15 @@ function ensureSchemaFile(projectPath, tables) {
132
133
  tableCount: userTables.length,
133
134
  };
134
135
  }
136
+ /** Bump when generated helper/middleware behavior changes; EGDesk regenerates stale projects. */
137
+ exports.EGDESK_HELPERS_GENERATION_VERSION = '3';
135
138
  function generateHelpers(projectPath, options = {}) {
136
139
  const helperPath = path.join(projectPath, 'egdesk-helpers.ts');
137
140
  const helperContent = `/**
138
141
  * EGDesk Helper Functions for Next.js
139
142
  *
143
+ * Generation version: ${exports.EGDESK_HELPERS_GENERATION_VERSION} (EGDesk regenerates when stale)
144
+ *
140
145
  * Type-safe helpers for EGDesk user data, Google Workspace (Sheets / Drive / Docs / Slides MCP + sync, Gmail, Apps Script),
141
146
  * FinanceHub (banks, cards, Hometax, promissory notes),
142
147
  * internal knowledge / business identity / company research (MCP), company research docs (cited tool-result blocks), Korean law (MCP), Bizinfo grants (MCP), NPS workplace headcount (MCP), and browser recorder replay / live browse.
@@ -159,10 +164,25 @@ function generateHelpers(projectPath, options = {}) {
159
164
 
160
165
  import { EGDESK_CONFIG } from './egdesk.config';
161
166
 
167
+ /** @internal Used by EGDesk to detect stale generated helpers. */
168
+ export const EGDESK_HELPERS_GENERATION_VERSION = '${exports.EGDESK_HELPERS_GENERATION_VERSION}';
169
+
162
170
  /**
163
171
  * Resolve EGDesk tunnel basePath for client-side fetch.
164
172
  * Next.js basePath does NOT apply to raw fetch() — prepend manually in production.
165
173
  */
174
+ function detectEgdeskBasePathFromPathname(pathname: string): string {
175
+ const parts = pathname.split('/').filter(Boolean);
176
+ if (parts[0] === 't' && parts.length >= 4 && parts[2] === 'p') {
177
+ return \`/\${parts.slice(0, 4).join('/')}\`;
178
+ }
179
+ return '';
180
+ }
181
+
182
+ function isLoopbackDevHost(hostname: string): boolean {
183
+ return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]';
184
+ }
185
+
166
186
  export function getEgdeskBasePath(): string {
167
187
  if (typeof window === 'undefined') {
168
188
  return (
@@ -172,18 +192,26 @@ export function getEgdeskBasePath(): string {
172
192
  );
173
193
  }
174
194
 
195
+ const fromPath = detectEgdeskBasePathFromPathname(window.location.pathname);
196
+ if (fromPath) return fromPath;
197
+
175
198
  const fromEnv =
176
199
  (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_BASE_PATH) || '';
177
- if (fromEnv) return fromEnv;
178
-
179
- // Fallback: detect /t/{tunnelId}/p/{projectName} from the current URL
180
- const parts = window.location.pathname.split('/').filter(Boolean);
181
- if (parts[0] === 't' && parts.length >= 4 && parts[2] === 'p') {
182
- return \`/\${parts.slice(0, 4).join('/')}\`;
200
+ if (fromEnv) {
201
+ if (isLoopbackDevHost(window.location.hostname)) {
202
+ return '';
203
+ }
204
+ return fromEnv;
183
205
  }
184
206
  return '';
185
207
  }
186
208
 
209
+ /** NextAuth SessionProvider basePath (includes /api/auth suffix). */
210
+ export function getNextAuthBasePath(): string {
211
+ const root = getEgdeskBasePath();
212
+ return root ? \`\${root}/api/auth\` : '/api/auth';
213
+ }
214
+
187
215
  /**
188
216
  * Fetch wrapper that prepends EGDesk basePath to relative URLs.
189
217
  * Use for /api/* routes and /__*_proxy paths in client components.
@@ -263,14 +291,18 @@ function originFromValue(value?: string | null): string | null {
263
291
  }
264
292
  }
265
293
 
266
- /** Browser origin, then visitorOrigin, then NEXT_PUBLIC_EGDESK_VISITOR_ORIGIN / NEXT_PUBLIC_SITE_URL. */
294
+ /** Browser origin, then visitorOrigin, runtime canonical env, then NEXT_PUBLIC_* (build-time fallback). */
267
295
  function resolveVisitorSiteOrigin(options: WorkspaceVisitorCallOptions = {}): string | null {
268
296
  if (typeof window !== 'undefined') return window.location.origin;
269
- const fromEnv =
270
- (typeof process !== 'undefined' &&
271
- (process.env?.NEXT_PUBLIC_EGDESK_VISITOR_ORIGIN || process.env?.NEXT_PUBLIC_SITE_URL)) ||
272
- '';
273
- return originFromValue(options.visitorOrigin) || originFromValue(fromEnv);
297
+ const explicit = originFromValue(options.visitorOrigin);
298
+ if (explicit) return explicit;
299
+ const fromRuntime =
300
+ typeof process !== 'undefined'
301
+ ? process.env?.EGDESK_CANONICAL_VISITOR_ORIGIN ||
302
+ process.env?.NEXT_PUBLIC_EGDESK_VISITOR_ORIGIN ||
303
+ process.env?.NEXT_PUBLIC_SITE_URL
304
+ : '';
305
+ return originFromValue(fromRuntime);
274
306
  }
275
307
 
276
308
  function buildWorkspaceVisitorHeaders(options: WorkspaceVisitorCallOptions = {}): Record<string, string> {
@@ -288,11 +320,8 @@ function buildWorkspaceVisitorHeaders(options: WorkspaceVisitorCallOptions = {})
288
320
  if (origin) {
289
321
  headers['Origin'] = origin;
290
322
  headers['X-Visitor-Origin'] = origin;
291
- } else if (typeof window === 'undefined') {
292
- throw new Error(
293
- 'asVisitor is set but no site origin is available. Pass visitorOrigin matching startVisitorGoogleLogin, or set NEXT_PUBLIC_EGDESK_VISITOR_ORIGIN.',
294
- );
295
323
  }
324
+ // Server-side without Origin: EGDesk MCP binds the session from stored audience (token-only callers).
296
325
  return headers;
297
326
  }
298
327
 
@@ -783,7 +812,7 @@ function estimateBase64DecodedBytes(data: string): number {
783
812
  return Math.floor((trimmed.length * 3) / 4);
784
813
  }
785
814
 
786
- function base64ToUint8Array(data: string): Uint8Array {
815
+ function base64ToUint8Array(data: string): Uint8Array<ArrayBuffer> {
787
816
  const trimmed = String(data || '').replace(/^data:[^;]+;base64,/i, '').replace(/\\s/g, '');
788
817
  const bin = atob(trimmed);
789
818
  const out = new Uint8Array(bin.length);
@@ -1293,7 +1322,7 @@ export async function uploadVoiceTranscriptAudioFromBase64(
1293
1322
  ): Promise<VoiceTranscriptAudioUploadResult> {
1294
1323
  assertVoiceTranscriptFilename(filename);
1295
1324
  const bytes = base64ToUint8Array(data);
1296
- const blob = new Blob([bytes], { type: options.mimeType || 'application/octet-stream' });
1325
+ const blob = new Blob([Uint8Array.from(bytes)], { type: options.mimeType || 'application/octet-stream' });
1297
1326
  const file = new File([blob], filename, { type: options.mimeType || blob.type });
1298
1327
  return uploadVoiceTranscriptAudioChunked(file, options);
1299
1328
  }
@@ -1320,7 +1349,7 @@ export async function uploadFile(
1320
1349
  const decodedBytes = estimateBase64DecodedBytes(data);
1321
1350
  if (typeof window !== 'undefined' && decodedBytes > UPLOAD_CHUNKED_THRESHOLD_BYTES) {
1322
1351
  const bytes = base64ToUint8Array(data);
1323
- const blob = new Blob([bytes], { type: options.mimeType || 'application/octet-stream' });
1352
+ const blob = new Blob([Uint8Array.from(bytes)], { type: options.mimeType || 'application/octet-stream' });
1324
1353
  const file = new File([blob], filename, { type: options.mimeType || blob.type });
1325
1354
  return uploadFileChunked(tableName, rowId, columnName, file, options);
1326
1355
  }
@@ -4193,9 +4222,43 @@ export async function trashDriveFile(fileId: string, preferOAuth?: boolean) {
4193
4222
  return callDriveTool('drive_trash', { fileId, preferOAuth });
4194
4223
  }
4195
4224
 
4196
- /** Find or create the top-level EGDesk Drive folder */
4197
- export async function findOrCreateEgdeskFolder() {
4198
- return callDriveTool('drive_find_or_create_egdesk_folder', {});
4225
+ /**
4226
+ * Find or create the top-level EGDesk Drive folder.
4227
+ * When folderName is set, find or create that folder directly under EGDesk (OAuth).
4228
+ */
4229
+ export async function findOrCreateEgdeskFolder(folderName?: string) {
4230
+ const root = await callDriveTool('drive_find_or_create_egdesk_folder', {});
4231
+ if (!folderName?.trim()) {
4232
+ return root;
4233
+ }
4234
+ const name = folderName.trim();
4235
+ const egdeskFolderId =
4236
+ (root && typeof root === 'object' && 'folderId' in root && root.folderId) ||
4237
+ (root && typeof root === 'object' && 'id' in root && root.id) ||
4238
+ '';
4239
+ if (!egdeskFolderId) {
4240
+ throw new Error('findOrCreateEgdeskFolder: EGDesk root folder id missing');
4241
+ }
4242
+ const escapedName = name.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, "\\\\'");
4243
+ const preferOAuth = true;
4244
+ const listed = await callDriveTool(
4245
+ 'drive_list_files',
4246
+ {
4247
+ folderId: String(egdeskFolderId),
4248
+ query: \`name = '\${escapedName}' and mimeType = 'application/vnd.google-apps.folder'\`,
4249
+ preferOAuth,
4250
+ },
4251
+ { preferOAuth },
4252
+ );
4253
+ const files = listed?.files;
4254
+ if (Array.isArray(files) && files.length > 0 && files[0]?.id) {
4255
+ return files[0];
4256
+ }
4257
+ return callDriveTool('drive_create_folder', {
4258
+ name,
4259
+ parentId: String(egdeskFolderId),
4260
+ preferOAuth,
4261
+ });
4199
4262
  }
4200
4263
 
4201
4264
  /** Find or create EGDesk/Dev, Transactions, or Tax Invoices */
@@ -43,6 +43,7 @@ exports.generateMiddleware = generateMiddleware;
43
43
  const fs = __importStar(require("fs"));
44
44
  const path = __importStar(require("path"));
45
45
  const os = __importStar(require("os"));
46
+ const canonical_visitor_redirect_1 = require("./canonical-visitor-redirect");
46
47
  /**
47
48
  * Detect if project uses src/ directory structure
48
49
  */
@@ -121,6 +122,7 @@ function workspaceUpstreamHeaders(request: NextRequest): Record<string, string>
121
122
  const origin =
122
123
  request.headers.get('x-visitor-origin') ||
123
124
  request.headers.get('origin') ||
125
+ process.env.EGDESK_CANONICAL_VISITOR_ORIGIN ||
124
126
  process.env.NEXT_PUBLIC_EGDESK_VISITOR_ORIGIN ||
125
127
  process.env.NEXT_PUBLIC_SITE_URL ||
126
128
  request.nextUrl.origin;
@@ -172,7 +174,12 @@ function visitorAuthToolFromProxyBody(body: string): string {
172
174
  }
173
175
  }
174
176
 
177
+ ${(0, canonical_visitor_redirect_1.canonicalVisitorRedirectMiddlewareSource)()}
178
+
175
179
  export async function middleware(request: NextRequest) {
180
+ const canonicalRedirect = maybeRedirectToCanonicalVisitorSite(request);
181
+ if (canonicalRedirect) return canonicalRedirect;
182
+
176
183
  const { pathname } = request.nextUrl;
177
184
 
178
185
  // Intercept __user_data_proxy requests
@@ -45,6 +45,7 @@ exports.generateProxy = generateProxy;
45
45
  const fs = __importStar(require("fs"));
46
46
  const path = __importStar(require("path"));
47
47
  const os = __importStar(require("os"));
48
+ const canonical_visitor_redirect_1 = require("./canonical-visitor-redirect");
48
49
  /**
49
50
  * Detect if project uses src/ directory structure
50
51
  */
@@ -160,6 +161,8 @@ function visitorForwardHeaders(request: NextRequest): Record<string, string> {
160
161
  }
161
162
 
162
163
  /** Forward opt-in visitor session headers to Workspace MCP tool calls. */
164
+ ${(0, canonical_visitor_redirect_1.canonicalVisitorRedirectMiddlewareSource)()}
165
+
163
166
  function workspaceForwardHeaders(request: NextRequest): Record<string, string> {
164
167
  const headers = buildEgdeskHeaders();
165
168
  const authorization = request.headers.get('authorization');
@@ -170,6 +173,7 @@ function workspaceForwardHeaders(request: NextRequest): Record<string, string> {
170
173
  const origin =
171
174
  request.headers.get('x-visitor-origin') ||
172
175
  request.headers.get('origin') ||
176
+ process.env.EGDESK_CANONICAL_VISITOR_ORIGIN ||
173
177
  process.env.NEXT_PUBLIC_EGDESK_VISITOR_ORIGIN ||
174
178
  process.env.NEXT_PUBLIC_SITE_URL ||
175
179
  request.nextUrl.origin;
@@ -180,6 +184,9 @@ function workspaceForwardHeaders(request: NextRequest): Record<string, string> {
180
184
  }
181
185
 
182
186
  export async function proxy(request: NextRequest) {
187
+ const canonicalRedirect = maybeRedirectToCanonicalVisitorSite(request);
188
+ if (canonicalRedirect) return canonicalRedirect;
189
+
183
190
  const { pathname } = request.nextUrl;
184
191
 
185
192
  // Intercept __user_data_proxy requests
@@ -404,10 +404,78 @@ function resolveRemoteMcpRoot(configured: string, tunnelUrl: string): string {
404
404
  return '';
405
405
  }
406
406
 
407
+ function resolveLocalMcpRootFromEnv(configured: string, tunnelUrl: string): string {
408
+ if (configured && isLocalEgdeskUrl(configured)) return configured.replace(/\\/$/, '');
409
+ if (tunnelUrl && isLocalEgdeskUrl(tunnelUrl)) return tunnelUrl.replace(/\\/$/, '');
410
+ return 'http://localhost:8080';
411
+ }
412
+
413
+ function isKnownGatewayHostname(hostname: string): boolean {
414
+ return hostname === 'tunneling-service.onrender.com' || hostname.endsWith('.egdesk.cloud');
415
+ }
416
+
417
+ /** Keep in sync with visitor-auth-origin.ts sanitizeVisitorOAuthBase */
418
+ function sanitizeVisitorOAuthBase(returnTo: string, egdeskPublicUrl: string): string {
419
+ const base = egdeskPublicUrl.replace(/\\/$/, '');
420
+ try {
421
+ const publicUrl = new URL(base);
422
+ const site = new URL(returnTo);
423
+ if (isKnownGatewayHostname(publicUrl.hostname)) return base;
424
+ if (!/^\\/t\\/[^/]+/.test(publicUrl.pathname)) return base;
425
+ if (
426
+ (site.protocol === 'http:' || site.protocol === 'https:') &&
427
+ !isDevSiteHostname(site.hostname)
428
+ ) {
429
+ return site.origin;
430
+ }
431
+ return publicUrl.origin;
432
+ } catch {
433
+ return base;
434
+ }
435
+ }
436
+
437
+ function resolveLocalVisitorMcpRoot(egdeskPublicUrl: string): string {
438
+ const trimmed = egdeskPublicUrl.replace(/\\/$/, '');
439
+ try {
440
+ const parsed = new URL(trimmed);
441
+ if (isLoopbackHostname(parsed.hostname)) {
442
+ const port = parsed.port || '8080';
443
+ return \`http://localhost:\${port}\`;
444
+ }
445
+ } catch {
446
+ // ignore
447
+ }
448
+ return 'http://localhost:8080';
449
+ }
450
+
451
+ /**
452
+ * Authorized redirect URI for BYO visitor GCP (gateway mode). Not the Next dev port (:3000/:4000).
453
+ * Keep in sync with visitor-auth-origin.ts resolveOperatorVisitorWebCallbackUri (gateway).
454
+ */
455
+ export function resolveVisitorGcpRedirectUriToRegister(): string {
456
+ if (typeof window === 'undefined') {
457
+ throw new Error('resolveVisitorGcpRedirectUriToRegister() must run in the browser');
458
+ }
459
+ const returnTo = new URL(resolveVisitorAppPath('/auth/callback'), window.location.origin).toString();
460
+ const egdeskPublicUrl = resolveEgdeskPublicUrl();
461
+ if (isLoopbackHostname(new URL(returnTo).hostname)) {
462
+ return \`\${resolveLocalVisitorMcpRoot(egdeskPublicUrl)}/visitor-auth/callback\`;
463
+ }
464
+ if (isDevSiteHostname(new URL(returnTo).hostname)) {
465
+ const base = sanitizeVisitorOAuthBase(returnTo, egdeskPublicUrl);
466
+ if (isTunnelMcpRoot(base)) {
467
+ return \`\${base.replace(/\\/$/, '')}/visitor-auth/callback\`;
468
+ }
469
+ return \`\${resolveLocalVisitorMcpRoot(egdeskPublicUrl)}/visitor-auth/callback\`;
470
+ }
471
+ const sanitized = sanitizeVisitorOAuthBase(returnTo, egdeskPublicUrl);
472
+ return \`\${sanitized.replace(/\\/$/, '')}/visitor-auth/callback\`;
473
+ }
474
+
407
475
  /**
408
476
  * MCP root passed to visitor-auth start (egdeskPublicUrl).
409
477
  *
410
- * - Loopback dev → NEXT_PUBLIC_EGDESK_TUNNEL_URL when set, else local MCP (OAuth bounces via :54321).
478
+ * - Loopback dev → local MCP (:8080); platform OAuth still bounces via :54321 server-side.
411
479
  * - LAN IP → tunnel MCP root from NEXT_PUBLIC_EGDESK_TUNNEL_URL or non-local API URL (required).
412
480
  * - Tunnel/custom domain → tunnel MCP root; never window.location.origin on dev/LAN hosts.
413
481
  *
@@ -423,7 +491,7 @@ export function resolveEgdeskPublicUrl(): string {
423
491
  ''
424
492
  ).replace(/\\/$/, '');
425
493
  const remoteMcpRoot = resolveRemoteMcpRoot(configured, tunnelUrl);
426
- const localMcpRoot = configured || tunnelUrl || 'http://localhost:8080';
494
+ const localMcpRoot = resolveLocalMcpRootFromEnv(configured, tunnelUrl);
427
495
 
428
496
  if (typeof window === 'undefined') {
429
497
  return remoteMcpRoot || localMcpRoot;
@@ -449,7 +517,7 @@ export function resolveEgdeskPublicUrl(): string {
449
517
  );
450
518
  }
451
519
  if (isLoopbackHostname(hostname)) {
452
- return remoteMcpRoot || localMcpRoot;
520
+ return localMcpRoot;
453
521
  }
454
522
  if (remoteMcpRoot) return remoteMcpRoot;
455
523
  throw new Error(
@@ -530,6 +598,7 @@ export async function startVisitorGoogleLogin(options: {
530
598
  egdeskPublicUrl,
531
599
  forceConsent: options.forceConsent === true,
532
600
  scopes,
601
+ visitorOrigin: window.location.origin,
533
602
  };
534
603
  if (options.gcp?.trim()) startArgs.gcp = options.gcp.trim();
535
604
  if (options.handle?.trim()) startArgs.handle = options.handle.trim();
@@ -541,7 +610,11 @@ export async function startVisitorGoogleLogin(options: {
541
610
  }
542
611
 
543
612
  export async function exchangeVisitorAuthCode(code: string) {
544
- const result = await callVisitorAuth('exchange', { code });
613
+ const exchangeArgs: Record<string, unknown> = { code };
614
+ if (typeof window !== 'undefined') {
615
+ exchangeArgs.visitorOrigin = window.location.origin;
616
+ }
617
+ const result = await callVisitorAuth('exchange', exchangeArgs);
545
618
  if (!result?.sessionId) {
546
619
  throw new Error(result?.error || 'Failed to complete visitor login');
547
620
  }
@@ -596,7 +669,8 @@ export async function getVisitorGcpStatus(handle: string) {
596
669
  throw new Error('getVisitorGcpStatus() must run in the browser');
597
670
  }
598
671
  const sampleReturnTo = new URL(resolveVisitorAppPath('/auth/callback'), window.location.origin).toString();
599
- return callVisitorAuth('gcp_status', { handle, sampleReturnTo });
672
+ const egdeskPublicUrl = resolveEgdeskPublicUrl();
673
+ return callVisitorAuth('gcp_status', { handle, sampleReturnTo, egdeskPublicUrl });
600
674
  }
601
675
 
602
676
  export async function forgetVisitorGcp(handle: string) {
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.119";
11
+ export declare const COMPATIBLE_APP_VERSION = "1.4.123";
12
12
  export interface SetupOptions {
13
13
  egdeskUrl?: string;
14
14
  /** Production EGDesk server URL — written to .env.production.local. Falls back to egdeskUrl. */
@@ -41,7 +41,7 @@ export { discoverTables, generateConfigFile, loadTablesFromSchemaFile, updateEnv
41
41
  export { generateMiddleware } from './generate-middleware';
42
42
  export { generateProxy } from './generate-proxy';
43
43
  export { generateChunkedUploadRoutes, generateVoiceTranscriptChunkedUploadRoutes, } from './generate-chunked-upload-routes';
44
- export { generateHelpers, generateSchemaFile, ensureSchemaFile, formatEgdeskSchemaFileContent } from './generate-helpers';
44
+ export { generateHelpers, generateSchemaFile, ensureSchemaFile, formatEgdeskSchemaFileContent, EGDESK_HELPERS_GENERATION_VERSION, } from './generate-helpers';
45
45
  export type { SchemaTableDefinition, EnsureSchemaFileResult, GenerateHelpersOptions } from './generate-helpers';
46
46
  export { generateApiWrapper } from './generate-api-wrapper';
47
47
  export { generateVisitorAuth, ensureVisitorAuthConfig } 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.ensureVisitorAuthConfig = exports.generateVisitorAuth = exports.generateApiWrapper = exports.formatEgdeskSchemaFileContent = exports.ensureSchemaFile = exports.generateSchemaFile = exports.generateHelpers = exports.generateVoiceTranscriptChunkedUploadRoutes = exports.generateChunkedUploadRoutes = exports.generateProxy = exports.generateMiddleware = exports.updateEnvFiles = exports.loadTablesFromSchemaFile = exports.generateConfigFile = exports.discoverTables = exports.COMPATIBLE_APP_VERSION = void 0;
42
+ exports.ensureVisitorAuthConfig = exports.generateVisitorAuth = exports.generateApiWrapper = exports.EGDESK_HELPERS_GENERATION_VERSION = exports.formatEgdeskSchemaFileContent = exports.ensureSchemaFile = exports.generateSchemaFile = exports.generateHelpers = exports.generateVoiceTranscriptChunkedUploadRoutes = exports.generateChunkedUploadRoutes = 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.119';
49
+ exports.COMPATIBLE_APP_VERSION = '1.4.123';
50
50
  const fs = __importStar(require("fs"));
51
51
  const path = __importStar(require("path"));
52
52
  const setup_userdata_1 = require("./setup-userdata");
@@ -250,6 +250,7 @@ Object.defineProperty(exports, "generateHelpers", { enumerable: true, get: funct
250
250
  Object.defineProperty(exports, "generateSchemaFile", { enumerable: true, get: function () { return generate_helpers_2.generateSchemaFile; } });
251
251
  Object.defineProperty(exports, "ensureSchemaFile", { enumerable: true, get: function () { return generate_helpers_2.ensureSchemaFile; } });
252
252
  Object.defineProperty(exports, "formatEgdeskSchemaFileContent", { enumerable: true, get: function () { return generate_helpers_2.formatEgdeskSchemaFileContent; } });
253
+ Object.defineProperty(exports, "EGDESK_HELPERS_GENERATION_VERSION", { enumerable: true, get: function () { return generate_helpers_2.EGDESK_HELPERS_GENERATION_VERSION; } });
253
254
  var generate_api_wrapper_2 = require("./generate-api-wrapper");
254
255
  Object.defineProperty(exports, "generateApiWrapper", { enumerable: true, get: function () { return generate_api_wrapper_2.generateApiWrapper; } });
255
256
  var generate_visitor_auth_2 = require("./generate-visitor-auth");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@egdesk/next-api-plugin",
3
- "version": "1.5.114",
3
+ "version": "1.5.116",
4
4
  "description": "Next.js plugin for EGDesk database proxy integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -16,6 +16,7 @@
16
16
  },
17
17
  "scripts": {
18
18
  "build": "tsc",
19
+ "test": "npm run build && node --test dist/canonical-visitor-redirect.test.js",
19
20
  "dev": "tsc --watch",
20
21
  "prepublishOnly": "npm run build"
21
22
  },