@helloleo/plugins 0.2.16 → 0.2.19

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