@helloleo/plugins 0.2.17 → 0.2.20

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.
@@ -1,21 +1,821 @@
1
- import { mkdir } from "node:fs/promises";
1
+ import { mkdir, readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import type { Plugin } from "@opencode-ai/plugin";
4
4
  import { tool } from "@opencode-ai/plugin";
5
5
 
6
6
  /**
7
- * Adds NetSuite OAuth wiring on top of an existing scaffold: the netsuite
8
- * OAuth client, a NetSuite auth context (auth.tsx), and the AuthLayout /
9
- * LoginPage / SignInWithNetSuite components. It never overwrites a
10
- * scaffold file -- the one manual step is wrapping the root route's
11
- * <Outlet /> with <AuthLayout> (the tool's output shows the snippet).
12
- * All NetSuite-specific templates live in this file -- one place to read
13
- * or change anything NetSuite-related.
7
+ * NetSuite runtime OAuth (end-user LOGIN). Two variants, picked automatically
8
+ * from the project's scaffold -- never from env:
9
+ *
10
+ * - tanstack-start (SSR): the app IS the backend. Emits server routes
11
+ * (/auth/netsuite/* + /api/me), netsuite_flows + netsuite_sessions drizzle
12
+ * tables, and a same-origin client. The redirect URI registered on
13
+ * Integration Record #2 must be the APP's own /auth/netsuite/callback
14
+ * (read it from GET /auth/netsuite/config).
15
+ * - tanstack-router (SPA): client-only files; the OAuth backend is the
16
+ * per-project HelloLeo Cloud Worker (VITE_WORKER_URL), sign-in runs in
17
+ * a popup + postMessage so it works inside the HelloLeo preview iframe.
18
+ * The wizard registers the Worker's fixed /auth/netsuite/callback as the
19
+ * ONE redirect URI on Integration Record #2 (provision-first, see webapp
20
+ * netsuiteRuntimeSetup).
21
+ *
22
+ * Both variants share the same component names (AuthLayout / LoginPage /
23
+ * SignInWithNetSuite) and the same wiring step: wrap the root route's
24
+ * <Outlet /> with <AuthLayout>. LoginPage is a deliberately bare placeholder
25
+ * in both -- Leo designs it per app.
26
+ *
27
+ * This login uses NetSuite Integration Record #2 (scope: rest_webservices),
28
+ * a SEPARATE record from the MCP one (scope: mcp) used only to BUILD the app.
14
29
  *
15
30
  * Called AFTER `scaffold`, never instead of it.
16
31
  */
17
32
 
18
- function netsuiteTs(): string {
33
+ /**
34
+ * Scaffold id recorded by the scaffold tool in .leo/project.json, or null if
35
+ * the file is missing/unreadable (pre-project.json workspaces).
36
+ */
37
+ async function readScaffoldId(dir: string): Promise<string | null> {
38
+ try {
39
+ const meta = await Bun.file(path.join(dir, ".leo", "project.json")).json();
40
+ return typeof meta?.scaffold === "string" ? meta.scaffold : null;
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Is this project a tanstack-start (SSR) app? Primary signal: the scaffold id
48
+ * in .leo/project.json. Fallback for pre-project.json workspaces: only the
49
+ * start scaffold depends on @tanstack/react-start -- the router SPA ships
50
+ * @tanstack/react-router alone.
51
+ */
52
+ async function isStartScaffold(dir: string): Promise<boolean> {
53
+ const scaffoldId = await readScaffoldId(dir);
54
+ if (scaffoldId) return scaffoldId.startsWith("tanstack-start");
55
+ try {
56
+ const pkg = await Bun.file(path.join(dir, "package.json")).json();
57
+ return Boolean(
58
+ pkg?.dependencies?.["@tanstack/react-start"] ??
59
+ pkg?.devDependencies?.["@tanstack/react-start"],
60
+ );
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+
66
+ // --- emitted: src/db/schema.ts (appended) --------------------------------
67
+ function schemaAppend(): string {
68
+ return `
69
+ // --- NetSuite OAuth (added by setup_netsuite) ---
70
+ // Short-lived PKCE + return-to state between /auth/netsuite/start and its
71
+ // callback. Single-use: the callback deletes the row after reading it.
72
+ export const netsuiteFlows = sqliteTable('netsuite_flows', {
73
+ flowId: text('flow_id').primaryKey(),
74
+ codeVerifier: text('code_verifier').notNull(),
75
+ returnTo: text('return_to').notNull(),
76
+ createdAt: integer('created_at')
77
+ .notNull()
78
+ .default(sql\`(unixepoch())\`),
79
+ })
80
+
81
+ // Opaque session id -> NetSuite tokens. Tokens stay server-side; the browser
82
+ // only ever holds the sid (sent as a bearer).
83
+ export const netsuiteSessions = sqliteTable('netsuite_sessions', {
84
+ sid: text('sid').primaryKey(),
85
+ accountId: text('account_id').notNull(),
86
+ accessToken: text('access_token').notNull(),
87
+ refreshToken: text('refresh_token'),
88
+ expiresAt: integer('expires_at'),
89
+ userId: text('user_id'),
90
+ email: text('email'),
91
+ createdAt: integer('created_at')
92
+ .notNull()
93
+ .default(sql\`(unixepoch())\`),
94
+ })
95
+ `;
96
+ }
97
+
98
+ // --- emitted: src/lib/netsuite-server.ts ---------------------------------
99
+ function netsuiteServerTs(): string {
100
+ return `/*
101
+ * NetSuite runtime OAuth -- server side (TanStack Start server routes).
102
+ *
103
+ * Runs wherever the app runs: \`vite dev\` (workerd) in the Fly preview machine
104
+ * in dev, and the published Cloudflare Worker in prod. There is no separate
105
+ * backend Worker -- these helpers back the /auth/netsuite/* + /api/me routes.
106
+ *
107
+ * Config is read from the Cloudflare env binding via @helloleo/runtime.
108
+ * Set NETSUITE_ACCOUNT_ID / _CLIENT_ID / _CLIENT_SECRET (secret optional for a
109
+ * PKCE public client) and optional PUBLIC_APP_URL as HelloLeo Cloud secrets
110
+ * (prod) or dev vars (preview). They never reach the browser.
111
+ */
112
+ import { eq } from 'drizzle-orm'
113
+ import { env as runtimeEnv } from '@helloleo/runtime'
114
+ import { db } from '#/db'
115
+ import { netsuiteSessions } from '#/db/schema'
116
+
117
+ interface NsEnv {
118
+ NETSUITE_ACCOUNT_ID?: string
119
+ NETSUITE_CLIENT_ID?: string
120
+ NETSUITE_CLIENT_SECRET?: string
121
+ PUBLIC_APP_URL?: string
122
+ HELLOLEO_URL?: string
123
+ }
124
+ const nsEnv = runtimeEnv as unknown as NsEnv
125
+
126
+ // Runtime record scope. The app signs end-users in for REST/SuiteQL.
127
+ export const SCOPE = 'rest_webservices'
128
+ const REFRESH_LEEWAY_SECONDS = 60
129
+
130
+ export function requireConfig() {
131
+ const accountId = nsEnv.NETSUITE_ACCOUNT_ID
132
+ const clientId = nsEnv.NETSUITE_CLIENT_ID
133
+ if (!accountId || !clientId) {
134
+ throw new Error(
135
+ 'NetSuite not configured: set NETSUITE_ACCOUNT_ID and NETSUITE_CLIENT_ID (and NETSUITE_CLIENT_SECRET for a confidential client) as HelloLeo Cloud secrets / dev vars.',
136
+ )
137
+ }
138
+ return { accountId, clientId, clientSecret: nsEnv.NETSUITE_CLIENT_SECRET || '' }
139
+ }
140
+
141
+ // Account id -> DNS host form: lowercase, underscores to hyphens.
142
+ function host(accountId: string) {
143
+ return accountId.trim().toLowerCase().replace(/_/g, '-')
144
+ }
145
+ export function authorizeUrl(accountId: string) {
146
+ return \`https://\${host(accountId)}.app.netsuite.com/app/login/oauth2/authorize.nl\`
147
+ }
148
+ export function tokenUrl(accountId: string) {
149
+ return \`https://\${host(accountId)}.suitetalk.api.netsuite.com/services/rest/auth/oauth2/v1/token\`
150
+ }
151
+ export function restBase(accountId: string) {
152
+ return \`https://\${host(accountId)}.suitetalk.api.netsuite.com\`
153
+ }
154
+
155
+ function stripTrailingSlash(s: string) {
156
+ return s.endsWith('/') ? s.slice(0, -1) : s
157
+ }
158
+
159
+ // Public origin of THIS app, used to build the redirect URI. Prefer an explicit
160
+ // PUBLIC_APP_URL; else derive from the request (honouring the preview proxy's
161
+ // forwarded headers). Must match a redirect URI registered on the NetSuite
162
+ // Integration Record exactly.
163
+ export function appOrigin(request: Request) {
164
+ // 1) Explicit override wins (set by the platform per environment).
165
+ if (nsEnv.PUBLIC_APP_URL) return stripTrailingSlash(nsEnv.PUBLIC_APP_URL)
166
+ // 2) HELLOLEO_URL is injected on every deploy (the app's canonical origin,
167
+ // a bare host with no scheme), so it's set even when the NetSuite
168
+ // wizard's PUBLIC_APP_URL pin wasn't.
169
+ if (nsEnv.HELLOLEO_URL) return \`https://\${stripTrailingSlash(nsEnv.HELLOLEO_URL)}\`
170
+ // 3) Preview/prod proxies rewrite Host, so trust the forwarded/original host
171
+ // they set (HelloLeo's nginx sends X-Original-Host) — that's the public URL
172
+ // the browser loaded, not an internal upstream host.
173
+ const url = new URL(request.url)
174
+ const proto = request.headers.get('x-forwarded-proto') || url.protocol.replace(':', '')
175
+ const hostHeader =
176
+ request.headers.get('x-forwarded-host') ||
177
+ request.headers.get('x-original-host') ||
178
+ url.host
179
+ return \`\${proto}://\${hostHeader}\`
180
+ }
181
+ export function redirectUri(request: Request) {
182
+ return \`\${appOrigin(request)}/auth/netsuite/callback\`
183
+ }
184
+
185
+ // Coerce ?return_to= to our OWN origin. The callback appends the session bearer
186
+ // as a #nssid=... fragment; an off-origin return_to would leak that live
187
+ // credential to an attacker-controlled page (open-redirect -> token theft).
188
+ export function safeReturnTo(request: Request, raw: string | null): string {
189
+ const origin = appOrigin(request)
190
+ if (!raw) return origin
191
+ try {
192
+ const u = new URL(raw, origin)
193
+ return u.origin === origin ? u.toString() : origin
194
+ } catch {
195
+ return origin
196
+ }
197
+ }
198
+
199
+ // --- PKCE (Web Crypto: works on workerd and Node) ---
200
+ function b64url(bytes: Uint8Array) {
201
+ let s = ''
202
+ for (const b of bytes) s += String.fromCharCode(b)
203
+ return btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')
204
+ }
205
+ export async function pkce() {
206
+ const verifier = b64url(crypto.getRandomValues(new Uint8Array(48)))
207
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))
208
+ const challenge = b64url(new Uint8Array(digest))
209
+ return { verifier, challenge }
210
+ }
211
+
212
+ interface TokenResponse {
213
+ access_token?: string
214
+ refresh_token?: string
215
+ expires_in?: number
216
+ error?: string
217
+ error_description?: string
218
+ }
219
+
220
+ // Confidential client -> HTTP Basic. Public (PKCE-only) -> client_id in body.
221
+ function authHeaders(clientId: string, clientSecret: string, params: Record<string, string>) {
222
+ const headers: Record<string, string> = { 'Content-Type': 'application/x-www-form-urlencoded' }
223
+ if (clientSecret) headers.Authorization = 'Basic ' + btoa(\`\${clientId}:\${clientSecret}\`)
224
+ else params.client_id = clientId
225
+ return headers
226
+ }
227
+
228
+ // POST the token endpoint and parse tolerantly. NetSuite returns JSON for both
229
+ // success and OAuth errors, but a gateway (502/504) can return HTML -- never let
230
+ // res.json() throw into the route handler (that would surface as an opaque 500
231
+ // instead of a clean "token exchange failed").
232
+ async function postToken(
233
+ accountId: string,
234
+ params: Record<string, string>,
235
+ headers: Record<string, string>,
236
+ ): Promise<TokenResponse> {
237
+ let res: Response
238
+ try {
239
+ res = await fetch(tokenUrl(accountId), { method: 'POST', headers, body: new URLSearchParams(params) })
240
+ } catch (e) {
241
+ return { error: 'network_error', error_description: String(e) }
242
+ }
243
+ const text = await res.text()
244
+ let data: TokenResponse = {}
245
+ try {
246
+ data = JSON.parse(text) as TokenResponse
247
+ } catch {
248
+ // non-JSON body (e.g. gateway HTML) -- leave data empty, fall through
249
+ }
250
+ if (!res.ok && !data.error) {
251
+ data = { error: 'token_request_failed', error_description: 'HTTP ' + res.status }
252
+ }
253
+ return data
254
+ }
255
+
256
+ export async function exchangeCode(request: Request, code: string, verifier: string) {
257
+ const { accountId, clientId, clientSecret } = requireConfig()
258
+ const params: Record<string, string> = {
259
+ grant_type: 'authorization_code',
260
+ code,
261
+ redirect_uri: redirectUri(request),
262
+ code_verifier: verifier,
263
+ }
264
+ return postToken(accountId, params, authHeaders(clientId, clientSecret, params))
265
+ }
266
+
267
+ async function refreshToken(refresh: string) {
268
+ const { accountId, clientId, clientSecret } = requireConfig()
269
+ const params: Record<string, string> = { grant_type: 'refresh_token', refresh_token: refresh }
270
+ return postToken(accountId, params, authHeaders(clientId, clientSecret, params))
271
+ }
272
+
273
+ export interface NsSession {
274
+ sid: string
275
+ accountId: string
276
+ accessToken: string
277
+ refreshToken: string | null
278
+ expiresAt: number | null
279
+ userId: string | null
280
+ email: string | null
281
+ }
282
+
283
+ // Load a session by sid, transparently refreshing the access token when it's
284
+ // within the leeway of expiry. Returns null if unknown or unrefreshable.
285
+ export async function getSession(sid: string): Promise<NsSession | null> {
286
+ if (!sid) return null
287
+ const rows = await db.select().from(netsuiteSessions).where(eq(netsuiteSessions.sid, sid)).limit(1)
288
+ const s = rows[0]
289
+ if (!s) return null
290
+ const now = Math.floor(Date.now() / 1000)
291
+ // A missing expiry is treated as EXPIRED (force a refresh) rather than trusting
292
+ // the token forever -- NetSuite normally sends expires_in, so this is defensive.
293
+ const expired = s.expiresAt == null ? true : now + REFRESH_LEEWAY_SECONDS >= s.expiresAt
294
+ if (expired) {
295
+ // Token expired (or about to). It MUST refresh; if it can't, the session is
296
+ // dead — delete it and return null so /api/me reports signed-out and the user
297
+ // re-auths, rather than a "logged in" app whose every NetSuite call 401s.
298
+ if (!s.refreshToken) { await deleteSession(sid); return null }
299
+ const tok = await refreshToken(s.refreshToken)
300
+ if (!tok.access_token) { await deleteSession(sid); return null }
301
+ const expiresAt = now + (tok.expires_in || 3600)
302
+ const refreshTok = tok.refresh_token ?? s.refreshToken
303
+ await db
304
+ .update(netsuiteSessions)
305
+ .set({ accessToken: tok.access_token, refreshToken: refreshTok, expiresAt })
306
+ .where(eq(netsuiteSessions.sid, sid))
307
+ return { ...s, accessToken: tok.access_token, refreshToken: refreshTok, expiresAt }
308
+ }
309
+ return s
310
+ }
311
+
312
+ export async function deleteSession(sid: string) {
313
+ if (sid) await db.delete(netsuiteSessions).where(eq(netsuiteSessions.sid, sid))
314
+ }
315
+
316
+ export function bearer(request: Request) {
317
+ const h = request.headers.get('authorization') || ''
318
+ return h.startsWith('Bearer ') ? h.slice(7) : ''
319
+ }
320
+
321
+ /**
322
+ * Call NetSuite REST / SuiteQL for the signed-in session. Use this from your
323
+ * data routes (src/routes/api/*). \`path\` is relative to the account's
324
+ * suitetalk host, e.g. '/services/rest/query/v1/suiteql'. Returns the raw
325
+ * fetch Response (401 if the sid is unknown). Access token is auto-refreshed.
326
+ */
327
+ export async function netsuiteFetch(sid: string, path: string, init: RequestInit = {}): Promise<Response> {
328
+ const session = await getSession(sid)
329
+ if (!session) return new Response(JSON.stringify({ error: 'unauthorized' }), { status: 401 })
330
+ const url = path.startsWith('http') ? path : \`\${restBase(session.accountId)}\${path}\`
331
+ const headers = new Headers(init.headers)
332
+ headers.set('Authorization', \`Bearer \${session.accessToken}\`)
333
+ if (init.body && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json')
334
+ return fetch(url, { ...init, headers })
335
+ }
336
+ `;
337
+ }
338
+
339
+ // --- emitted: src/routes/auth/netsuite/start.ts --------------------------
340
+ function startRouteTs(): string {
341
+ return `import { createFileRoute } from '@tanstack/react-router'
342
+ import { db } from '#/db'
343
+ import { netsuiteFlows } from '#/db/schema'
344
+ import {
345
+ authorizeUrl,
346
+ pkce,
347
+ redirectUri,
348
+ requireConfig,
349
+ safeReturnTo,
350
+ SCOPE,
351
+ } from '#/lib/netsuite-server'
352
+
353
+ // GET /auth/netsuite/start -- begin the NetSuite OAuth (PKCE) flow.
354
+ export const Route = createFileRoute('/auth/netsuite/start')({
355
+ server: {
356
+ handlers: {
357
+ GET: async ({ request }) => {
358
+ const { accountId, clientId } = requireConfig()
359
+ const url = new URL(request.url)
360
+ // Same-origin only: the callback returns the bearer in a URL fragment.
361
+ const returnTo = safeReturnTo(request, url.searchParams.get('return_to'))
362
+
363
+ const { verifier, challenge } = await pkce()
364
+ const flowId = crypto.randomUUID()
365
+ await db.insert(netsuiteFlows).values({ flowId, codeVerifier: verifier, returnTo })
366
+
367
+ const authorize = new URL(authorizeUrl(accountId))
368
+ authorize.searchParams.set('response_type', 'code')
369
+ authorize.searchParams.set('client_id', clientId)
370
+ authorize.searchParams.set('redirect_uri', redirectUri(request))
371
+ authorize.searchParams.set('scope', SCOPE)
372
+ authorize.searchParams.set('state', flowId)
373
+ authorize.searchParams.set('code_challenge', challenge)
374
+ authorize.searchParams.set('code_challenge_method', 'S256')
375
+
376
+ return new Response(null, { status: 302, headers: { Location: authorize.toString() } })
377
+ },
378
+ },
379
+ },
380
+ })
381
+ `;
382
+ }
383
+
384
+ // --- emitted: src/routes/auth/netsuite/callback.ts -----------------------
385
+ function callbackRouteTs(): string {
386
+ return `import { createFileRoute } from '@tanstack/react-router'
387
+ import { eq } from 'drizzle-orm'
388
+ import { db } from '#/db'
389
+ import { netsuiteFlows, netsuiteSessions } from '#/db/schema'
390
+ import { exchangeCode, requireConfig } from '#/lib/netsuite-server'
391
+
392
+ // GET /auth/netsuite/callback -- exchange the code, mint a session, hand the
393
+ // bearer back to the SPA via the URL fragment (#nssid=...). The fragment
394
+ // survives the HelloLeo preview iframe, where third-party cookies are dropped.
395
+ export const Route = createFileRoute('/auth/netsuite/callback')({
396
+ server: {
397
+ handlers: {
398
+ GET: async ({ request }) => {
399
+ const url = new URL(request.url)
400
+ const err = url.searchParams.get('error')
401
+ if (err) return new Response(\`NetSuite authorization failed: \${err}\`, { status: 400 })
402
+
403
+ const code = url.searchParams.get('code')
404
+ const state = url.searchParams.get('state')
405
+ if (!code || !state) return new Response('Missing code or state', { status: 400 })
406
+
407
+ const rows = await db
408
+ .select()
409
+ .from(netsuiteFlows)
410
+ .where(eq(netsuiteFlows.flowId, state))
411
+ .limit(1)
412
+ const flow = rows[0]
413
+ if (!flow) return new Response('Unknown or expired flow -- start again', { status: 400 })
414
+ // Single-use: burn the flow row immediately.
415
+ await db.delete(netsuiteFlows).where(eq(netsuiteFlows.flowId, state))
416
+ // Reject stale flows: the PKCE verifier must not stay valid indefinitely
417
+ // for an abandoned or leaked authorize URL (createdAt is unixepoch seconds).
418
+ const nowSec = Math.floor(Date.now() / 1000)
419
+ if (flow.createdAt && nowSec - flow.createdAt > 600) {
420
+ return new Response('Flow expired -- start again', { status: 400 })
421
+ }
422
+
423
+ const tok = await exchangeCode(request, code, flow.codeVerifier)
424
+ if (!tok.access_token) {
425
+ return new Response(
426
+ \`Token exchange failed: \${tok.error_description || tok.error || 'unknown error'}\`,
427
+ { status: 400 },
428
+ )
429
+ }
430
+
431
+ const sid = crypto.randomUUID()
432
+ const now = Math.floor(Date.now() / 1000)
433
+ await db.insert(netsuiteSessions).values({
434
+ sid,
435
+ accountId: requireConfig().accountId,
436
+ accessToken: tok.access_token,
437
+ refreshToken: tok.refresh_token ?? null,
438
+ expiresAt: now + (tok.expires_in || 3600),
439
+ })
440
+
441
+ const dest = new URL(flow.returnTo)
442
+ dest.hash = \`nssid=\${sid}\`
443
+ return new Response(null, { status: 302, headers: { Location: dest.toString() } })
444
+ },
445
+ },
446
+ },
447
+ })
448
+ `;
449
+ }
450
+
451
+ // --- emitted: src/routes/auth/netsuite/logout.ts -------------------------
452
+ function logoutRouteTs(): string {
453
+ return `import { createFileRoute } from '@tanstack/react-router'
454
+ import { bearer, deleteSession } from '#/lib/netsuite-server'
455
+
456
+ // POST /auth/netsuite/logout -- destroy the current session.
457
+ export const Route = createFileRoute('/auth/netsuite/logout')({
458
+ server: {
459
+ handlers: {
460
+ POST: async ({ request }) => {
461
+ await deleteSession(bearer(request))
462
+ return Response.json({ ok: true })
463
+ },
464
+ },
465
+ },
466
+ })
467
+ `;
468
+ }
469
+
470
+ // --- emitted: src/routes/api/me.ts ---------------------------------------
471
+ function meRouteTs(): string {
472
+ return `import { createFileRoute } from '@tanstack/react-router'
473
+ import { bearer, getSession } from '#/lib/netsuite-server'
474
+
475
+ // GET /api/me -- resolve the bearer sid to a session. The ONLY authoritative
476
+ // auth check; the client must never trust sessionStorage on its own.
477
+ export const Route = createFileRoute('/api/me')({
478
+ server: {
479
+ handlers: {
480
+ GET: async ({ request }) => {
481
+ const session = await getSession(bearer(request))
482
+ if (!session) return Response.json({ authenticated: false })
483
+ return Response.json({
484
+ authenticated: true,
485
+ account_id: session.accountId,
486
+ })
487
+ },
488
+ },
489
+ },
490
+ })
491
+ `;
492
+ }
493
+
494
+ // --- emitted: src/routes/auth/netsuite/config.ts -------------------------
495
+ function configRouteTs(): string {
496
+ return `import { createFileRoute } from '@tanstack/react-router'
497
+ import { env as runtimeEnv } from '@helloleo/runtime'
498
+ import { appOrigin, redirectUri } from '#/lib/netsuite-server'
499
+
500
+ // GET /auth/netsuite/config -- single source of truth for the redirect URI.
501
+ // Whatever this returns is EXACTLY what /auth/netsuite/start sends NetSuite, so
502
+ // show the user THIS value to register on their Integration Record. Never
503
+ // hardcode or guess a callback URL.
504
+ export const Route = createFileRoute('/auth/netsuite/config')({
505
+ server: {
506
+ handlers: {
507
+ GET: async ({ request }) => {
508
+ const e = runtimeEnv as unknown as {
509
+ NETSUITE_ACCOUNT_ID?: string
510
+ NETSUITE_CLIENT_ID?: string
511
+ }
512
+ return Response.json({
513
+ redirect_uri: redirectUri(request),
514
+ origin: appOrigin(request),
515
+ configured: Boolean(e.NETSUITE_ACCOUNT_ID && e.NETSUITE_CLIENT_ID),
516
+ })
517
+ },
518
+ },
519
+ },
520
+ })
521
+ `;
522
+ }
523
+
524
+ // --- emitted: src/lib/netsuite.ts (client) -------------------------------
525
+ function netsuiteClientTs(): string {
526
+ return `/*
527
+ * NetSuite auth -- client (same-origin). The OAuth backend is THIS app's own
528
+ * server routes (src/routes/auth/netsuite/* + src/routes/api/me.ts), so every
529
+ * call is relative -- no separate Worker, no VITE_WORKER_URL.
530
+ *
531
+ * The browser only ever holds an opaque session id (sid), handed back in the
532
+ * callback's URL fragment (#nssid=...) so it survives the HelloLeo preview
533
+ * iframe (third-party cookies are partitioned/dropped there). The sid rides as
534
+ * Authorization: Bearer on every call; NetSuite tokens stay server-side. The
535
+ * only authoritative auth check is GET /api/me.
536
+ *
537
+ * NEVER use a password gate. NEVER trust sessionStorage as the auth state --
538
+ * it's just a cache of the bearer.
539
+ */
540
+ const TOKEN_KEY = 'nssid'
541
+
542
+ // Capture-and-strip #nssid=... as early as possible so URLs stay clean.
543
+ ;(function bootstrapTokenFromHash() {
544
+ if (typeof window === 'undefined') return
545
+ const hash = window.location.hash.replace(/^#/, '')
546
+ if (!hash) return
547
+ const params = new URLSearchParams(hash)
548
+ const sid = params.get(TOKEN_KEY)
549
+ if (sid) {
550
+ try {
551
+ sessionStorage.setItem(TOKEN_KEY, sid)
552
+ } catch {}
553
+ params.delete(TOKEN_KEY)
554
+ const rest = params.toString()
555
+ window.history.replaceState(
556
+ null,
557
+ '',
558
+ window.location.pathname + window.location.search + (rest ? '#' + rest : ''),
559
+ )
560
+ }
561
+ })()
562
+
563
+ export function getSessionToken(): string | null {
564
+ try {
565
+ return sessionStorage.getItem(TOKEN_KEY)
566
+ } catch {
567
+ return null
568
+ }
569
+ }
570
+
571
+ export function signInWithNetSuite(returnTo: string = window.location.href) {
572
+ const url = new URL('/auth/netsuite/start', window.location.origin)
573
+ url.searchParams.set('return_to', returnTo)
574
+ // The app renders inside the HelloLeo preview iframe; /start 302s to
575
+ // NetSuite, whose OAuth page sends X-Frame-Options: DENY. Navigate the TOP
576
+ // frame so the flow runs at top level and the callback lands there to read
577
+ // #nssid=. Assign .href (NOT .assign(): reading .assign off a cross-origin
578
+ // window.top.location throws, dropping us into the iframe fallback ->
579
+ // "refused to connect").
580
+ try {
581
+ if (window.top && window.top !== window) {
582
+ window.top.location.href = url.toString()
583
+ return
584
+ }
585
+ } catch {
586
+ /* top window unreachable -- fall through to same-frame navigation */
587
+ }
588
+ window.location.href = url.toString()
589
+ }
590
+
591
+ export interface NetSuiteSession {
592
+ authenticated: boolean
593
+ account_id?: string
594
+ }
595
+
596
+ export async function getNetSuiteSession(): Promise<NetSuiteSession> {
597
+ const sid = getSessionToken()
598
+ if (!sid) return { authenticated: false }
599
+ const res = await fetch('/api/me', { headers: { Authorization: 'Bearer ' + sid } })
600
+ if (!res.ok) return { authenticated: false }
601
+ // res.json() is \`unknown\` under workers-types -- assert the /api/me shape.
602
+ const data = (await res.json()) as NetSuiteSession
603
+ return { ...data, authenticated: Boolean(data?.authenticated) }
604
+ }
605
+
606
+ export async function signOutNetSuite(): Promise<void> {
607
+ const sid = getSessionToken()
608
+ if (sid) {
609
+ try {
610
+ await fetch('/auth/netsuite/logout', {
611
+ method: 'POST',
612
+ headers: { Authorization: 'Bearer ' + sid },
613
+ })
614
+ } catch {}
615
+ }
616
+ try {
617
+ sessionStorage.removeItem(TOKEN_KEY)
618
+ } catch {}
619
+ window.location.reload()
620
+ }
621
+
622
+ /**
623
+ * Fetch YOUR data routes (src/routes/api/*) with the bearer attached. Use this
624
+ * instead of bare fetch for authenticated calls.
625
+ */
626
+ export async function apiFetch(path: string, init: RequestInit = {}): Promise<Response> {
627
+ const sid = getSessionToken()
628
+ const headers = new Headers(init.headers)
629
+ if (sid) headers.set('Authorization', 'Bearer ' + sid)
630
+ return fetch(path, { ...init, headers })
631
+ }
632
+
633
+ /**
634
+ * The exact redirect URI this app will send NetSuite, read from the server so
635
+ * it can never drift from what /auth/netsuite/start actually uses. Show it to
636
+ * whoever registers the Integration Record; never hardcode a callback URL.
637
+ */
638
+ export async function getNetSuiteRedirectUri(): Promise<string | null> {
639
+ try {
640
+ const res = await fetch('/auth/netsuite/config')
641
+ if (!res.ok) return null
642
+ const data = (await res.json()) as { redirect_uri?: string }
643
+ return data?.redirect_uri ?? null
644
+ } catch {
645
+ return null
646
+ }
647
+ }
648
+ `;
649
+ }
650
+
651
+ // --- emitted: src/lib/auth.tsx (client) ----------------------------------
652
+ function startAuthTsx(): string {
653
+ return `import * as React from 'react'
654
+ import {
655
+ getNetSuiteSession,
656
+ signInWithNetSuite,
657
+ signOutNetSuite,
658
+ type NetSuiteSession,
659
+ } from './netsuite'
660
+
661
+ /**
662
+ * NetSuite auth context. Holds the session (resolved client-side from /api/me
663
+ * via getNetSuiteSession) and exposes sign-in / sign-out. /api/me is the only
664
+ * authoritative check -- never trust sessionStorage directly.
665
+ */
666
+ export interface NetSuiteAuthContextValue {
667
+ pending: boolean
668
+ isAuthenticated: boolean
669
+ session: NetSuiteSession | null
670
+ signIn: () => void
671
+ signOut: () => Promise<void>
672
+ refresh: () => Promise<void>
673
+ }
674
+
675
+ const NetSuiteAuthContext = React.createContext<NetSuiteAuthContextValue | null>(null)
676
+
677
+ export function NetSuiteAuthProvider({ children }: { children: React.ReactNode }) {
678
+ const [session, setSession] = React.useState<NetSuiteSession | null>(null)
679
+ // Start pending on BOTH server and client render so SSR and first paint match
680
+ // (a spinner), avoiding a hydration mismatch. The effect (client-only)
681
+ // resolves it.
682
+ const [pending, setPending] = React.useState(true)
683
+
684
+ const refresh = React.useCallback(async () => {
685
+ setPending(true)
686
+ try {
687
+ setSession(await getNetSuiteSession())
688
+ } finally {
689
+ setPending(false)
690
+ }
691
+ }, [])
692
+
693
+ React.useEffect(() => {
694
+ refresh()
695
+ }, [refresh])
696
+
697
+ const value: NetSuiteAuthContextValue = {
698
+ pending,
699
+ isAuthenticated: Boolean(session?.authenticated),
700
+ session,
701
+ signIn: () => signInWithNetSuite(),
702
+ signOut: signOutNetSuite,
703
+ refresh,
704
+ }
705
+
706
+ return <NetSuiteAuthContext.Provider value={value}>{children}</NetSuiteAuthContext.Provider>
707
+ }
708
+
709
+ export function useNetSuiteAuth(): NetSuiteAuthContextValue {
710
+ const ctx = React.useContext(NetSuiteAuthContext)
711
+ if (!ctx) {
712
+ throw new Error('useNetSuiteAuth must be used within <NetSuiteAuthProvider>')
713
+ }
714
+ return ctx
715
+ }
716
+ `;
717
+ }
718
+
719
+ // --- emitted: src/components/auth/AuthLayout.tsx --------------------------
720
+ function startAuthLayoutTsx(): string {
721
+ return `import type { ReactNode } from 'react'
722
+ import { NetSuiteAuthProvider, useNetSuiteAuth } from '../../lib/auth'
723
+ import { LoginPage } from './LoginPage'
724
+
725
+ /**
726
+ * NetSuite auth layout. The ONE manual wiring step: wrap the root route's
727
+ * <Outlet /> with it in src/routes/__root.tsx:
728
+ *
729
+ * import { AuthLayout } from '../components/auth/AuthLayout'
730
+ * ...
731
+ * function RootComponent() {
732
+ * return (
733
+ * <RootDocument>
734
+ * <AuthLayout>
735
+ * <Outlet />
736
+ * </AuthLayout>
737
+ * </RootDocument>
738
+ * )
739
+ * }
740
+ *
741
+ * It provides auth context and gates rendering: a spinner while the session
742
+ * resolves, <LoginPage /> for signed-out users, your routes once signed in.
743
+ * NEVER swap this for a password gate -- real OAuth is the only login.
744
+ */
745
+ export function AuthLayout({ children }: { children: ReactNode }) {
746
+ return (
747
+ <NetSuiteAuthProvider>
748
+ <Gate>{children}</Gate>
749
+ </NetSuiteAuthProvider>
750
+ )
751
+ }
752
+
753
+ function Gate({ children }: { children: ReactNode }) {
754
+ const { pending, isAuthenticated } = useNetSuiteAuth()
755
+
756
+ if (pending) {
757
+ return (
758
+ <div className="min-h-screen flex items-center justify-center bg-background">
759
+ <div className="h-8 w-8 rounded-full border-2 border-primary border-t-transparent animate-spin" />
760
+ </div>
761
+ )
762
+ }
763
+
764
+ if (!isAuthenticated) return <LoginPage />
765
+
766
+ return <>{children}</>
767
+ }
768
+ `;
769
+ }
770
+
771
+ // --- emitted: src/components/auth/LoginPage.tsx ---------------------------
772
+ function startLoginPageTsx(): string {
773
+ return `import { SignInWithNetSuite } from './SignInWithNetSuite'
774
+
775
+ /**
776
+ * Unauthenticated gate -- a deliberately bare placeholder. DESIGN THIS PAGE
777
+ * to match the app you are building: its real name, its brand, its layout
778
+ * language. Do NOT ship this default as-is.
779
+ *
780
+ * The only hard requirements:
781
+ * - keep <SignInWithNetSuite /> as the ONLY call-to-action (it starts the
782
+ * OAuth flow at /auth/netsuite/start)
783
+ * - never add a password form -- real OAuth is the only login
784
+ */
785
+ export function LoginPage() {
786
+ return (
787
+ <main className="min-h-screen flex items-center justify-center bg-background text-foreground p-4">
788
+ <div className="flex flex-col items-center gap-4 text-center">
789
+ <h1 className="text-2xl font-semibold">Sign in</h1>
790
+ <p className="text-sm text-muted-foreground">
791
+ Connect your NetSuite account to continue.
792
+ </p>
793
+ <SignInWithNetSuite />
794
+ </div>
795
+ </main>
796
+ )
797
+ }
798
+ `;
799
+ }
800
+
801
+ // --- emitted: src/components/auth/SignInWithNetSuite.tsx ------------------
802
+ function startSignInButtonTsx(): string {
803
+ return `import { signInWithNetSuite } from '../../lib/netsuite'
804
+
805
+ export function SignInWithNetSuite() {
806
+ return (
807
+ <button
808
+ onClick={() => signInWithNetSuite()}
809
+ className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
810
+ >
811
+ Sign in with NetSuite
812
+ </button>
813
+ )
814
+ }
815
+ `;
816
+ }
817
+
818
+ function spaNetsuiteTs(): string {
19
819
  return `/*
20
820
  * NetSuite OAuth client helper (bearer-token-in-fragment).
21
821
  *
@@ -173,7 +973,7 @@ export async function workerFetch(pathOrUrl: string, init: RequestInit = {}): Pr
173
973
  `;
174
974
  }
175
975
 
176
- function signInButtonTsx(): string {
976
+ function spaSignInButtonTsx(): string {
177
977
  return `import { signInWithNetSuite } from '../../lib/netsuite';
178
978
 
179
979
  export function SignInWithNetSuite() {
@@ -189,52 +989,36 @@ export function SignInWithNetSuite() {
189
989
  `;
190
990
  }
191
991
 
192
- function netsuiteLoginPageTsx(): string {
992
+ function spaLoginPageTsx(): string {
193
993
  return `import { SignInWithNetSuite } from './SignInWithNetSuite';
194
994
 
195
995
  /**
196
- * Default unauthenticated landing page. Replaces any password gate.
197
- * Customise copy / imagery freely but keep <SignInWithNetSuite /> as the
198
- * only call-to-action -- it points to the Worker's /auth/netsuite/start.
996
+ * Unauthenticated gate -- a deliberately bare placeholder. DESIGN THIS PAGE
997
+ * to match the app you are building: its real name, its brand, its layout
998
+ * language. Do NOT ship this default as-is.
999
+ *
1000
+ * The only hard requirements:
1001
+ * - keep <SignInWithNetSuite /> as the ONLY call-to-action (it starts the
1002
+ * OAuth flow on the Worker's /auth/netsuite/start)
1003
+ * - never add a password form -- real OAuth is the only login
199
1004
  */
200
1005
  export function LoginPage() {
201
1006
  return (
202
- <div className="min-h-screen bg-background text-foreground flex">
203
- <div className="hidden lg:flex lg:w-1/2 bg-primary text-primary-foreground p-12 flex-col justify-between">
204
- <div className="text-xl font-semibold">NetSuite App</div>
205
- <div>
206
- <h1 className="text-4xl font-bold leading-tight">
207
- Connect your NetSuite account
208
- </h1>
209
- <p className="mt-4 text-primary-foreground/80 max-w-md">
210
- Sign in with your NetSuite credentials to access your data securely.
211
- Tokens stay server-side on HelloLeo Cloud -- they never reach the
212
- browser.
213
- </p>
214
- </div>
215
- <div className="text-xs text-primary-foreground/60">
216
- Powered by HelloLeo
217
- </div>
218
- </div>
219
- <div className="flex-1 flex items-center justify-center px-6 py-12">
220
- <div className="w-full max-w-sm space-y-6">
221
- <div>
222
- <h2 className="text-2xl font-semibold">Welcome</h2>
223
- <p className="mt-2 text-sm text-muted-foreground">
224
- Use the button below to sign in. You'll be redirected to NetSuite
225
- to authorise access, then back here.
226
- </p>
227
- </div>
228
- <SignInWithNetSuite />
229
- </div>
1007
+ <main className="min-h-screen flex items-center justify-center bg-background text-foreground p-4">
1008
+ <div className="flex flex-col items-center gap-4 text-center">
1009
+ <h1 className="text-2xl font-semibold">Sign in</h1>
1010
+ <p className="text-sm text-muted-foreground">
1011
+ Connect your NetSuite account to continue.
1012
+ </p>
1013
+ <SignInWithNetSuite />
230
1014
  </div>
231
- </div>
1015
+ </main>
232
1016
  );
233
1017
  }
234
1018
  `;
235
1019
  }
236
1020
 
237
- function authTsx(): string {
1021
+ function spaAuthTsx(): string {
238
1022
  return `import * as React from 'react';
239
1023
  import {
240
1024
  getNetSuiteSession,
@@ -307,7 +1091,7 @@ export function useNetSuiteAuth(): NetSuiteAuthContextValue {
307
1091
  `;
308
1092
  }
309
1093
 
310
- function authLayoutTsx(): string {
1094
+ function spaAuthLayoutTsx(): string {
311
1095
  return `import type { ReactNode } from 'react';
312
1096
  import { NetSuiteAuthProvider, useNetSuiteAuth } from '../../lib/auth';
313
1097
  import { LoginPage } from './LoginPage';
@@ -362,65 +1146,207 @@ function Gate({ children }: { children: ReactNode }) {
362
1146
  `;
363
1147
  }
364
1148
 
1149
+ // --- variant: tanstack-start (in-app server routes) ----------------------
1150
+ async function executeStart(dir: string): Promise<string> {
1151
+ await mkdir(path.join(dir, "src", "lib"), { recursive: true });
1152
+ await mkdir(path.join(dir, "src", "components", "auth"), {
1153
+ recursive: true,
1154
+ });
1155
+ await mkdir(path.join(dir, "src", "routes", "auth", "netsuite"), {
1156
+ recursive: true,
1157
+ });
1158
+ await mkdir(path.join(dir, "src", "routes", "api"), { recursive: true });
1159
+
1160
+ // Append the NetSuite tables to the drizzle schema (single source of
1161
+ // truth; migrations are generated from it and applied automatically).
1162
+ // Idempotent -- skip if already present. The 2026-07-30 start template
1163
+ // ships schema.ts as comments only (no imports), so prepend the drizzle
1164
+ // imports whenever the file has no real (uncommented) import of its own.
1165
+ const schemaImports = `import { sql } from 'drizzle-orm'\nimport { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'\n`;
1166
+ const schemaPath = path.join(dir, "src", "db", "schema.ts");
1167
+ let schemaAppended = false;
1168
+ try {
1169
+ const current = await readFile(schemaPath, "utf8");
1170
+ if (!current.includes("netsuite_flows")) {
1171
+ const hasImports = /^import .*drizzle-orm/m.test(current);
1172
+ await Bun.write(
1173
+ schemaPath,
1174
+ (hasImports ? current : schemaImports + current) + schemaAppend(),
1175
+ );
1176
+ schemaAppended = true;
1177
+ }
1178
+ } catch {
1179
+ // No base schema.ts -- scaffold wasn't run. Write a minimal one.
1180
+ await Bun.write(schemaPath, schemaImports + schemaAppend());
1181
+ schemaAppended = true;
1182
+ }
1183
+
1184
+ const files: [string, string][] = [
1185
+ [path.join("src", "lib", "netsuite-server.ts"), netsuiteServerTs()],
1186
+ [
1187
+ path.join("src", "routes", "auth", "netsuite", "start.ts"),
1188
+ startRouteTs(),
1189
+ ],
1190
+ [
1191
+ path.join("src", "routes", "auth", "netsuite", "callback.ts"),
1192
+ callbackRouteTs(),
1193
+ ],
1194
+ [
1195
+ path.join("src", "routes", "auth", "netsuite", "logout.ts"),
1196
+ logoutRouteTs(),
1197
+ ],
1198
+ [
1199
+ path.join("src", "routes", "auth", "netsuite", "config.ts"),
1200
+ configRouteTs(),
1201
+ ],
1202
+ [path.join("src", "routes", "api", "me.ts"), meRouteTs()],
1203
+ [path.join("src", "lib", "netsuite.ts"), netsuiteClientTs()],
1204
+ [path.join("src", "lib", "auth.tsx"), startAuthTsx()],
1205
+ [
1206
+ path.join("src", "components", "auth", "AuthLayout.tsx"),
1207
+ startAuthLayoutTsx(),
1208
+ ],
1209
+ [
1210
+ path.join("src", "components", "auth", "LoginPage.tsx"),
1211
+ startLoginPageTsx(),
1212
+ ],
1213
+ [
1214
+ path.join("src", "components", "auth", "SignInWithNetSuite.tsx"),
1215
+ startSignInButtonTsx(),
1216
+ ],
1217
+ ];
1218
+
1219
+ for (const [filePath, content] of files) {
1220
+ await Bun.write(path.join(dir, filePath), content);
1221
+ }
1222
+
1223
+ return [
1224
+ `Wrote ${files.length} NetSuite files${schemaAppended ? " + appended src/db/schema.ts" : ""}:`,
1225
+ "DOCS -- the authoritative setup guide is https://docs.helloleo.dev/integrations/netsuite . When you tell the user what to do in NetSuite, follow and link these steps verbatim; do not invent steps.",
1226
+ " - Record #2 (runtime): https://docs.helloleo.dev/integrations/netsuite#step-4-%E2%80%94-create-integration-record-2-runtime",
1227
+ " - Send runtime creds to Leo: https://docs.helloleo.dev/integrations/netsuite#step-5-%E2%80%94-send-the-runtime-credentials-to-leo",
1228
+ "",
1229
+ " server (OAuth backend lives in the app -- no separate Worker):",
1230
+ " - src/lib/netsuite-server.ts (env, PKCE, token exchange, session refresh, netsuiteFetch)",
1231
+ " - src/routes/auth/netsuite/start.ts GET begin PKCE flow",
1232
+ " - src/routes/auth/netsuite/callback.ts GET code -> tokens -> session",
1233
+ " - src/routes/auth/netsuite/logout.ts POST destroy session",
1234
+ " - src/routes/auth/netsuite/config.ts GET the exact redirect URI to register",
1235
+ " - src/routes/api/me.ts GET bearer -> session (auth check)",
1236
+ " - src/db/schema.ts += netsuite_flows + netsuite_sessions",
1237
+ " client:",
1238
+ " - src/lib/netsuite.ts (same-origin: signIn, session, apiFetch)",
1239
+ " - src/lib/auth.tsx (NetSuiteAuthProvider + useNetSuiteAuth)",
1240
+ " - src/components/auth/{AuthLayout,LoginPage,SignInWithNetSuite}.tsx",
1241
+ "",
1242
+ "WIRE IT UP (one manual step): in src/routes/__root.tsx, wrap <Outlet /> with <AuthLayout>:",
1243
+ "",
1244
+ " import { AuthLayout } from '../components/auth/AuthLayout'",
1245
+ "",
1246
+ " <AuthLayout>",
1247
+ " <Outlet />",
1248
+ " </AuthLayout>",
1249
+ "",
1250
+ "Then:",
1251
+ "- DESIGN THE LOGIN PAGE: src/components/auth/LoginPage.tsx is a bare placeholder on purpose. Restyle it to match THIS app (name, brand, layout) as part of building the UI -- do not ship the default. Keep <SignInWithNetSuite /> as the only call-to-action; never add a password form.",
1252
+ "- Build your dashboard inside <AuthLayout>. Read the session with useNetSuiteAuth().",
1253
+ "- Data routes: add src/routes/api/*.ts and call netsuiteFetch(bearer(request), '/services/rest/query/v1/suiteql', {...}) from the handler.",
1254
+ "- MIGRATIONS: schema.ts changed (netsuite_flows + netsuite_sessions). Migrations are generated and applied automatically; if the dev server complains about missing tables, run `bun run db:generate` once (never hand-edit files under drizzle/).",
1255
+ "",
1256
+ "TWO INTEGRATION RECORDS -- do not confuse them:",
1257
+ "- Record #1 (scope: mcp): already connected, used ONLY to build the app (schema discovery). This login does NOT use it.",
1258
+ "- Record #2 (scope: rest_webservices): THIS login uses it -- the end user signs into NetSuite through it, and the redirect URI is registered on THIS record. If it doesn't exist yet, tell the user to create it (a second Integration Record, scope rest_webservices only).",
1259
+ "",
1260
+ "CONFIG -- NETSUITE_ACCOUNT_ID, NETSUITE_CLIENT_ID, NETSUITE_CLIENT_SECRET (secret optional for PKCE public clients). Never hardcode; never put in code. Same var names in every environment, different SOURCE:",
1261
+ "- DEV (Fly preview): read from the project .env. HelloLeo writes them there (the setup wizard, or the env tooling). In dev the app uses .env -- do NOT tell the user to use HelloLeo Cloud here.",
1262
+ "- PROD (published Worker): the SAME names live as HelloLeo Cloud secrets; the publish step promotes them from .env onto the Worker automatically. Same code path (@helloleo/runtime env), just a different source per environment.",
1263
+ "- PUBLIC_APP_URL / HELLOLEO_URL are set by the platform per environment; don't hardcode them.",
1264
+ "- REDIRECT URI -- never guess or hardcode it. It is derived server-side and auto-corrects behind the preview proxy. Read the exact value from GET /auth/netsuite/config (or getNetSuiteRedirectUri() on the client) and tell the user to register THAT on Integration Record #2 (scope: rest_webservices). ONE redirect URI per record: register exactly the value /auth/netsuite/config returns for the environment the user signs into. If login must work in BOTH the preview and the published app, use a separate Integration Record per environment (same env var names, different NETSUITE_CLIENT_ID/_SECRET values per environment) -- do not stack URLs on one record.",
1265
+ "- Never replace <AuthLayout> with a password gate. Real OAuth is the only supported login.",
1266
+ ].join("\n");
1267
+ }
1268
+
1269
+ // --- variant: SPA + HelloLeo Cloud Worker --------------------------------
1270
+ async function executeSpa(dir: string): Promise<string> {
1271
+ await mkdir(path.join(dir, "src", "components", "auth"), {
1272
+ recursive: true,
1273
+ });
1274
+
1275
+ // All additive -- nothing the base scaffold wrote is touched.
1276
+ const nsFiles: [string, string][] = [
1277
+ [path.join("src", "lib", "netsuite.ts"), spaNetsuiteTs()],
1278
+ [path.join("src", "lib", "auth.tsx"), spaAuthTsx()],
1279
+ [
1280
+ path.join("src", "components", "auth", "AuthLayout.tsx"),
1281
+ spaAuthLayoutTsx(),
1282
+ ],
1283
+ [
1284
+ path.join("src", "components", "auth", "LoginPage.tsx"),
1285
+ spaLoginPageTsx(),
1286
+ ],
1287
+ [
1288
+ path.join("src", "components", "auth", "SignInWithNetSuite.tsx"),
1289
+ spaSignInButtonTsx(),
1290
+ ],
1291
+ ];
1292
+
1293
+ for (const [filePath, content] of nsFiles) {
1294
+ await Bun.write(path.join(dir, filePath), content);
1295
+ }
1296
+
1297
+ return [
1298
+ `Wrote ${nsFiles.length} NetSuite OAuth files (all additive, nothing overwritten):`,
1299
+ " - src/lib/netsuite.ts (OAuth client: signIn, session, workerFetch)",
1300
+ " - src/lib/auth.tsx (NetSuiteAuthProvider and useNetSuiteAuth)",
1301
+ " - src/components/auth/AuthLayout.tsx (provider and auth gate)",
1302
+ " - src/components/auth/LoginPage.tsx (unauthenticated view)",
1303
+ " - src/components/auth/SignInWithNetSuite.tsx (sign-in button)",
1304
+ "",
1305
+ "Notes:",
1306
+ "- DESIGN THE LOGIN PAGE: src/components/auth/LoginPage.tsx is a bare placeholder on purpose. Restyle it to match THIS app (name, brand, layout) as part of building the UI -- do not ship the default. Keep <SignInWithNetSuite /> as the only call-to-action; never add a password form.",
1307
+ "- AuthLayout shows LoginPage to signed-out users and renders the app's routes once they sign in with NetSuite.",
1308
+ "- Read the session anywhere with useNetSuiteAuth() from src/lib/auth.tsx.",
1309
+ "- Never replace AuthLayout with a password gate. Real OAuth is the only supported login.",
1310
+ "- The auth worker (deployed via the cloudflare-backend MCP) serves /auth/netsuite/start, /auth/netsuite/callback, /api/me and /auth/netsuite/logout. It reads env.NETSUITE_ACCOUNT_ID, _CLIENT_ID and _CLIENT_SECRET. VITE_WORKER_URL must be set (HelloLeo Cloud seeds it).",
1311
+ "- POPUP FLOW (required so login works inside the HelloLeo preview iframe): the client opens /auth/netsuite/start in a popup with ?popup=1. The worker MUST carry that flag through OAuth (persist it on the flow row in /start, read it back in /callback via state). In /auth/netsuite/callback, when the flow was popup, DO NOT redirect to return_to#nssid — instead return an HTML page whose script does: window.opener.postMessage({ type: 'netsuite-auth', nssid: SID }, '*'); window.close(); (fall back to the return_to#nssid redirect only when there is no opener / not a popup). Without this, the preview iframe (partitioned sessionStorage) keeps showing the login after sign-in.",
1312
+ "",
1313
+ "Next: in src/routes/__root.tsx, import AuthLayout and wrap <Outlet /> with it. Keep any existing providers.",
1314
+ "",
1315
+ " import { AuthLayout } from '../components/auth/AuthLayout'",
1316
+ "",
1317
+ " <AuthLayout>",
1318
+ " <Outlet />",
1319
+ " </AuthLayout>",
1320
+ ].join("\n");
1321
+ }
1322
+
365
1323
  export const setupNetsuite = tool({
366
1324
  description:
367
- "Add NetSuite OAuth wiring to an existing project. Call scaffold first, " +
368
- "then this. Writes the OAuth client, auth provider and login components. " +
369
- "All files are additive, nothing is overwritten. Real OAuth is wired " +
370
- "from day one, never replace <AuthLayout> with a password placeholder.",
1325
+ "Add NetSuite runtime OAuth (end-user LOGIN) to an existing project. " +
1326
+ "Call scaffold first, then this. Works on both scaffold types and " +
1327
+ "picks the variant automatically: on tanstack-start the app hosts " +
1328
+ "its own OAuth routes (/auth/netsuite/* + /api/me, same-origin " +
1329
+ "client); on tanstack-router (SPA) it writes the client + auth " +
1330
+ "components and the OAuth backend is the project's HelloLeo Cloud " +
1331
+ "Worker (VITE_WORKER_URL). This login uses NetSuite Integration " +
1332
+ "Record #2 (scope: rest_webservices) -- a SEPARATE record from the " +
1333
+ "MCP one (scope: mcp) that was used only to BUILD the app; do not " +
1334
+ "confuse them. Real OAuth from day one -- never replace <AuthLayout> " +
1335
+ "with a password placeholder. Setup guide (link the user to it): " +
1336
+ "https://docs.helloleo.dev/integrations/netsuite",
371
1337
  args: {},
372
1338
  async execute(_args, context) {
373
1339
  const dir = context.directory;
374
-
375
- await mkdir(path.join(dir, "src", "components", "auth"), {
376
- recursive: true,
377
- });
378
-
379
- // All additive -- nothing the base scaffold wrote is touched.
380
- const nsFiles: [string, string][] = [
381
- [path.join("src", "lib", "netsuite.ts"), netsuiteTs()],
382
- [path.join("src", "lib", "auth.tsx"), authTsx()],
383
- [
384
- path.join("src", "components", "auth", "AuthLayout.tsx"),
385
- authLayoutTsx(),
386
- ],
387
- [
388
- path.join("src", "components", "auth", "LoginPage.tsx"),
389
- netsuiteLoginPageTsx(),
390
- ],
391
- [
392
- path.join("src", "components", "auth", "SignInWithNetSuite.tsx"),
393
- signInButtonTsx(),
394
- ],
395
- ];
396
-
397
- for (const [filePath, content] of nsFiles) {
398
- await Bun.write(path.join(dir, filePath), content);
1340
+ // The variant follows the scaffold, never an env flag: a start app has
1341
+ // a server (TanStack Start routes + D1) so it hosts the OAuth itself;
1342
+ // the router SPA has no server, so the per-project HelloLeo Cloud
1343
+ // Worker is the backend. The redirect URI registered on Integration
1344
+ // Record #2 must match: the app's own /auth/netsuite/callback for
1345
+ // start, the Worker's fixed callback for the SPA.
1346
+ if (await isStartScaffold(dir)) {
1347
+ return executeStart(dir);
399
1348
  }
400
-
401
- return [
402
- `Wrote ${nsFiles.length} NetSuite OAuth files (all additive, nothing overwritten):`,
403
- " - src/lib/netsuite.ts (OAuth client: signIn, session, workerFetch)",
404
- " - src/lib/auth.tsx (NetSuiteAuthProvider and useNetSuiteAuth)",
405
- " - src/components/auth/AuthLayout.tsx (provider and auth gate)",
406
- " - src/components/auth/LoginPage.tsx (unauthenticated view)",
407
- " - src/components/auth/SignInWithNetSuite.tsx (sign-in button)",
408
- "",
409
- "Notes:",
410
- "- AuthLayout shows LoginPage to signed-out users and renders the app's routes once they sign in with NetSuite.",
411
- "- Read the session anywhere with useNetSuiteAuth() from src/lib/auth.tsx.",
412
- "- Never replace AuthLayout with a password gate. Real OAuth is the only supported login.",
413
- "- The auth worker (deployed via the cloudflare-backend MCP) serves /auth/netsuite/start, /auth/netsuite/callback, /api/me and /auth/netsuite/logout. It reads env.NETSUITE_ACCOUNT_ID, _CLIENT_ID and _CLIENT_SECRET. VITE_WORKER_URL must be set (HelloLeo Cloud seeds it).",
414
- "- POPUP FLOW (required so login works inside the HelloLeo preview iframe): the client opens /auth/netsuite/start in a popup with ?popup=1. The worker MUST carry that flag through OAuth (persist it on the flow row in /start, read it back in /callback via state). In /auth/netsuite/callback, when the flow was popup, DO NOT redirect to return_to#nssid — instead return an HTML page whose script does: window.opener.postMessage({ type: 'netsuite-auth', nssid: SID }, '*'); window.close(); (fall back to the return_to#nssid redirect only when there is no opener / not a popup). Without this, the preview iframe (partitioned sessionStorage) keeps showing the login after sign-in.",
415
- "",
416
- "Next: in src/routes/__root.tsx, import AuthLayout and wrap <Outlet /> with it. Keep any existing providers.",
417
- "",
418
- " import { AuthLayout } from '../components/auth/AuthLayout'",
419
- "",
420
- " <AuthLayout>",
421
- " <Outlet />",
422
- " </AuthLayout>",
423
- ].join("\n");
1349
+ return executeSpa(dir);
424
1350
  },
425
1351
  });
426
1352