oda-engine 0.0.0-stage → 0.1.0

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.
Files changed (204) hide show
  1. package/README.md +151 -2
  2. package/bin/nowhere.mjs +352 -0
  3. package/lib/account.mjs +57 -0
  4. package/lib/agentModules.mjs +57 -0
  5. package/lib/devServer.mjs +351 -0
  6. package/lib/headless.mjs +231 -0
  7. package/lib/headlessPreview.mjs +212 -0
  8. package/lib/keys.mjs +517 -0
  9. package/lib/make.mjs +855 -0
  10. package/lib/mcp.mjs +537 -0
  11. package/lib/open.mjs +22 -0
  12. package/lib/preview.mjs +87 -0
  13. package/lib/previewRpc.mjs +134 -0
  14. package/lib/project.mjs +359 -0
  15. package/lib/publishFlow.mjs +90 -0
  16. package/lib/resources.mjs +50 -0
  17. package/lib/rules.mjs +60 -0
  18. package/lib/scaffold.mjs +42 -0
  19. package/lib/setup.mjs +59 -0
  20. package/lib/tools.mjs +668 -0
  21. package/package.json +51 -4
  22. package/template/game.config.json +9 -0
  23. package/template/scene.json +4 -0
  24. package/template/src/main.ts +11 -0
  25. package/vendor/DOCS.md +447 -0
  26. package/vendor/agent/appRun.mjs +520 -0
  27. package/vendor/agent/assets/brief.mjs +242 -0
  28. package/vendor/agent/assets/collider.mjs +531 -0
  29. package/vendor/agent/assets/environments/index.mjs +12 -0
  30. package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
  31. package/vendor/agent/assets/fetch.mjs +168 -0
  32. package/vendor/agent/assets/footprint.mjs +13 -0
  33. package/vendor/agent/assets/gltf.mjs +547 -0
  34. package/vendor/agent/assets/hdr.mjs +269 -0
  35. package/vendor/agent/assets/imageOps.mjs +171 -0
  36. package/vendor/agent/assets/images/codex.mjs +307 -0
  37. package/vendor/agent/assets/images/fal.mjs +75 -0
  38. package/vendor/agent/assets/images/gemini.mjs +84 -0
  39. package/vendor/agent/assets/images/index.mjs +25 -0
  40. package/vendor/agent/assets/images/openai.mjs +75 -0
  41. package/vendor/agent/assets/images/stability.mjs +71 -0
  42. package/vendor/agent/assets/images/views.mjs +31 -0
  43. package/vendor/agent/assets/import.mjs +1352 -0
  44. package/vendor/agent/assets/inspect.mjs +465 -0
  45. package/vendor/agent/assets/jobs.mjs +196 -0
  46. package/vendor/agent/assets/ktx2.mjs +290 -0
  47. package/vendor/agent/assets/ledger.mjs +466 -0
  48. package/vendor/agent/assets/net.mjs +254 -0
  49. package/vendor/agent/assets/prices.json +39 -0
  50. package/vendor/agent/assets/providers/fal.mjs +115 -0
  51. package/vendor/agent/assets/providers/index.mjs +22 -0
  52. package/vendor/agent/assets/providers/meshy.mjs +119 -0
  53. package/vendor/agent/assets/providers/tripo.mjs +188 -0
  54. package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
  55. package/vendor/agent/assets/sources/index.mjs +23 -0
  56. package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
  57. package/vendor/agent/assets/sources/polypizza.mjs +121 -0
  58. package/vendor/agent/assets/splat.mjs +631 -0
  59. package/vendor/agent/assets/targets.mjs +122 -0
  60. package/vendor/agent/assets/tile.mjs +261 -0
  61. package/vendor/agent/assets/unzip.mjs +180 -0
  62. package/vendor/agent/blender/cleanup.py +360 -0
  63. package/vendor/agent/blender/convert.py +167 -0
  64. package/vendor/agent/blender/find.mjs +192 -0
  65. package/vendor/agent/blender/nw_export.py +104 -0
  66. package/vendor/agent/blender/nw_rubric.py +426 -0
  67. package/vendor/agent/blender/run.mjs +193 -0
  68. package/vendor/agent/blender/runner.py +252 -0
  69. package/vendor/agent/blender/sheet.py +743 -0
  70. package/vendor/agent/depth.mjs +134 -0
  71. package/vendor/agent/director/board.mjs +451 -0
  72. package/vendor/agent/director/contracts.mjs +663 -0
  73. package/vendor/agent/director/director.mjs +2365 -0
  74. package/vendor/agent/director/estimate.mjs +200 -0
  75. package/vendor/agent/director/gate.mjs +802 -0
  76. package/vendor/agent/director/limits.json +16 -0
  77. package/vendor/agent/director/methods.mjs +457 -0
  78. package/vendor/agent/director/policy.json +33 -0
  79. package/vendor/agent/director/prompts.mjs +244 -0
  80. package/vendor/agent/director/reading.mjs +341 -0
  81. package/vendor/agent/director/router.mjs +184 -0
  82. package/vendor/agent/director/seams.mjs +243 -0
  83. package/vendor/agent/director/session.mjs +643 -0
  84. package/vendor/agent/director/store.mjs +119 -0
  85. package/vendor/agent/director/taskGate.mjs +110 -0
  86. package/vendor/agent/director/teamLedger.mjs +118 -0
  87. package/vendor/agent/director/triage.mjs +63 -0
  88. package/vendor/agent/downloads.cjs +363 -0
  89. package/vendor/agent/flow.mjs +78 -0
  90. package/vendor/agent/guard.mjs +613 -0
  91. package/vendor/agent/host.mjs +1736 -0
  92. package/vendor/agent/language.mjs +58 -0
  93. package/vendor/agent/ledger.mjs +360 -0
  94. package/vendor/agent/locale.cjs +186 -0
  95. package/vendor/agent/loop/capacity.mjs +74 -0
  96. package/vendor/agent/loop/compose.mjs +127 -0
  97. package/vendor/agent/loop/gate.mjs +205 -0
  98. package/vendor/agent/loop/judge.mjs +189 -0
  99. package/vendor/agent/loop/levels.mjs +273 -0
  100. package/vendor/agent/loop/state.mjs +358 -0
  101. package/vendor/agent/notes.cjs +278 -0
  102. package/vendor/agent/pace.mjs +258 -0
  103. package/vendor/agent/panels.mjs +431 -0
  104. package/vendor/agent/prompt.mjs +342 -0
  105. package/vendor/agent/reference/board.mjs +410 -0
  106. package/vendor/agent/reference/compose.mjs +364 -0
  107. package/vendor/agent/reference/decode.mjs +56 -0
  108. package/vendor/agent/reference/facts.mjs +1874 -0
  109. package/vendor/agent/reference/png.mjs +107 -0
  110. package/vendor/agent/reference/records.mjs +63 -0
  111. package/vendor/agent/reference/web.mjs +252 -0
  112. package/vendor/agent/roles/artist.mjs +69 -0
  113. package/vendor/agent/roles/builder.mjs +79 -0
  114. package/vendor/agent/roles/checks.mjs +223 -0
  115. package/vendor/agent/roles/common.mjs +188 -0
  116. package/vendor/agent/roles/critic.mjs +171 -0
  117. package/vendor/agent/roles/index.mjs +39 -0
  118. package/vendor/agent/roles/modeller.mjs +142 -0
  119. package/vendor/agent/roles/qa.mjs +58 -0
  120. package/vendor/agent/roles/rubrics.mjs +79 -0
  121. package/vendor/agent/roles/sound.mjs +69 -0
  122. package/vendor/agent/rounds.cjs +333 -0
  123. package/vendor/agent/shared.mjs +284 -0
  124. package/vendor/agent/stopGate.mjs +574 -0
  125. package/vendor/agent/subagents.mjs +129 -0
  126. package/vendor/agent/tools/assets.mjs +499 -0
  127. package/vendor/agent/tools/blender.mjs +754 -0
  128. package/vendor/agent/tools/cards.mjs +479 -0
  129. package/vendor/agent/tools/choices.mjs +479 -0
  130. package/vendor/agent/tools/compose.mjs +74 -0
  131. package/vendor/agent/tools/environment.mjs +488 -0
  132. package/vendor/agent/tools/eyes.mjs +733 -0
  133. package/vendor/agent/tools/generate.mjs +338 -0
  134. package/vendor/agent/tools/guide.mjs +46 -0
  135. package/vendor/agent/tools/harness.mjs +193 -0
  136. package/vendor/agent/tools/image.mjs +643 -0
  137. package/vendor/agent/tools/index.mjs +162 -0
  138. package/vendor/agent/tools/look.mjs +578 -0
  139. package/vendor/agent/tools/loop.mjs +858 -0
  140. package/vendor/agent/tools/others.mjs +123 -0
  141. package/vendor/agent/tools/pictures.mjs +535 -0
  142. package/vendor/agent/tools/reference.mjs +366 -0
  143. package/vendor/agent/transcripts.mjs +118 -0
  144. package/vendor/agent-loop.mjs +602 -0
  145. package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
  146. package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
  147. package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
  148. package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
  149. package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
  150. package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
  151. package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
  152. package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
  153. package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
  154. package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
  155. package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
  156. package/vendor/auth.cjs +570 -0
  157. package/vendor/build.cjs +953 -0
  158. package/vendor/catalog.json +455 -0
  159. package/vendor/connectors.cjs +688 -0
  160. package/vendor/eyes.mjs +733 -0
  161. package/vendor/gameExports.json +1390 -0
  162. package/vendor/git.cjs +222 -0
  163. package/vendor/models.json +57 -0
  164. package/vendor/publish.cjs +1018 -0
  165. package/vendor/refBoard.cjs +301 -0
  166. package/vendor/schema/dist/assets.d.ts +335 -0
  167. package/vendor/schema/dist/assets.js +439 -0
  168. package/vendor/schema/dist/brief.d.ts +357 -0
  169. package/vendor/schema/dist/brief.js +302 -0
  170. package/vendor/schema/dist/common.d.ts +9 -0
  171. package/vendor/schema/dist/common.js +13 -0
  172. package/vendor/schema/dist/config.d.ts +406 -0
  173. package/vendor/schema/dist/config.js +355 -0
  174. package/vendor/schema/dist/contract.d.ts +599 -0
  175. package/vendor/schema/dist/contract.js +1146 -0
  176. package/vendor/schema/dist/index.d.ts +14 -0
  177. package/vendor/schema/dist/index.js +21 -0
  178. package/vendor/schema/dist/look.d.ts +463 -0
  179. package/vendor/schema/dist/look.js +681 -0
  180. package/vendor/schema/dist/lookStats.d.ts +230 -0
  181. package/vendor/schema/dist/lookStats.js +768 -0
  182. package/vendor/schema/dist/pilot.d.ts +32 -0
  183. package/vendor/schema/dist/pilot.js +44 -0
  184. package/vendor/schema/dist/publish.d.ts +214 -0
  185. package/vendor/schema/dist/publish.js +291 -0
  186. package/vendor/schema/dist/scene.d.ts +75 -0
  187. package/vendor/schema/dist/scene.js +120 -0
  188. package/vendor/schema/dist/skyLight.d.ts +141 -0
  189. package/vendor/schema/dist/skyLight.js +436 -0
  190. package/vendor/schema/dist/style.d.ts +131 -0
  191. package/vendor/schema/dist/style.js +155 -0
  192. package/vendor/schema/package.json +1 -0
  193. package/vendor/selectionPrompt.mjs +51 -0
  194. package/vendor/useTools.mjs +195 -0
  195. package/vendor/userMessage.mjs +26 -0
  196. package/web-dist/assets/GaussianSplatUtils-CB77cP9U.js +1 -0
  197. package/web-dist/assets/KTX2Loader-6OIWUF7s.js +2 -0
  198. package/web-dist/assets/SPZLoader-zYj0Alfv.js +1 -0
  199. package/web-dist/assets/gaussianSplat-CJTI1sEh.js +1 -0
  200. package/web-dist/assets/index-CcjyyQco.css +1 -0
  201. package/web-dist/assets/index-DMyJcoZJ.js +693 -0
  202. package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
  203. package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
  204. package/web-dist/index.html +34 -0
@@ -0,0 +1,570 @@
1
+ const http = require('node:http')
2
+ const { createClient } = require('@supabase/supabase-js')
3
+
4
+ // The nowhere account, signed in from the main process. Publishing needs a
5
+ // user token; so do the account's coin balance and the game cards shared
6
+ // with the phone (cloud.cjs). Building needs none. The session (access +
7
+ // refresh token) lives in secrets.bin next to the connector keys, so it is
8
+ // encrypted by the OS keychain and never reaches the renderer: the page only
9
+ // ever sees { signedIn, email, name, uid, coins, handle }.
10
+ //
11
+ // Sign-in is Google via Supabase Auth with the PKCE flow. The studio has no
12
+ // web origin to redirect back to, so it listens on a loopback port for the one
13
+ // request the browser makes after Google, exchanges the code for a session,
14
+ // and closes the port again. The three ports below are on the project's
15
+ // redirect allowlist (WORLD supabase/config.toml); a fourth one would be
16
+ // refused by Supabase, so there is no dynamic fallback.
17
+ //
18
+ // `node auth.cjs --self-test` exercises the loopback half without Electron or
19
+ // a real Google login: see selfTest() at the bottom.
20
+
21
+ const SUPABASE_URL = 'https://pnbhqecnuyqammdpooec.supabase.co'
22
+ // The public anon key, the same one the nowhere web app ships in its bundle
23
+ // (WORLD .env.production VITE_SUPABASE_ANON_KEY). It only identifies the
24
+ // project; every privilege comes from the user's session and RLS.
25
+ const SUPABASE_ANON_KEY =
26
+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InBuYmhxZWNudXlxYW1tZHBvb2VjIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODYwNDg2MDMsImV4cCI6MjEwMTYyNDYwM30.cqQmHN67KlRuJvki4NJx8NOcEnMUCoKl4C1XaJwh8Gc'
27
+
28
+ const PORTS = [53682, 53683, 53684]
29
+ const CALLBACK_PATH = '/callback'
30
+ const SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000
31
+
32
+ // supabase-js stores the session under STORAGE_KEY and the PKCE verifiers
33
+ // under keys derived from it (`nowhere-code-verifier`, `nowhere-flow-<id>-code-verifier`,
34
+ // `nowhere-flows-code-verifier`). Two secrets hold all of that: the session on
35
+ // its own, and every other key in one JSON bag.
36
+ const STORAGE_KEY = 'nowhere'
37
+ const SESSION_SECRET = 'nowheresession'
38
+ const VERIFIER_SECRET = 'nowhereverifier'
39
+
40
+ // What the module needs from Electron, resolved lazily so the self-test can
41
+ // swap in an in-memory store and a no-op browser without touching the keychain.
42
+ let deps = null
43
+ function getDeps() {
44
+ if (!deps) {
45
+ const { shell } = require('electron')
46
+ deps = {
47
+ secrets: require('./credentials.cjs'),
48
+ openExternal: (url) => shell.openExternal(url),
49
+ }
50
+ }
51
+ return deps
52
+ }
53
+
54
+ /** Test seam: { secrets, openExternal }. Must be called before anything else. */
55
+ function configure(overrides) {
56
+ deps = { ...(deps ?? {}), ...overrides }
57
+ client = null
58
+ }
59
+
60
+ // ---------------------------------------------------------------- storage adapter
61
+
62
+ function readBag() {
63
+ const raw = getDeps().secrets.getSecret(VERIFIER_SECRET)
64
+ if (!raw) return {}
65
+ try {
66
+ const parsed = JSON.parse(raw)
67
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
68
+ } catch {
69
+ return {}
70
+ }
71
+ }
72
+
73
+ function writeBag(bag) {
74
+ const { secrets } = getDeps()
75
+ if (Object.keys(bag).length === 0) secrets.clearSecret(VERIFIER_SECRET)
76
+ else secrets.setSecret(VERIFIER_SECRET, JSON.stringify(bag))
77
+ }
78
+
79
+ // Synchronous, which supabase-js accepts. setItem throws when the OS cannot
80
+ // encrypt; signIn() checks for that up front so the failure has a sentence
81
+ // rather than a stack trace.
82
+ const secretsAdapter = {
83
+ getItem(key) {
84
+ if (key === STORAGE_KEY) return getDeps().secrets.getSecret(SESSION_SECRET)
85
+ const value = readBag()[key]
86
+ return typeof value === 'string' ? value : null
87
+ },
88
+ setItem(key, value) {
89
+ if (key === STORAGE_KEY) {
90
+ getDeps().secrets.setSecret(SESSION_SECRET, value)
91
+ return
92
+ }
93
+ writeBag({ ...readBag(), [key]: value })
94
+ },
95
+ removeItem(key) {
96
+ if (key === STORAGE_KEY) {
97
+ getDeps().secrets.clearSecret(SESSION_SECRET)
98
+ return
99
+ }
100
+ const bag = readBag()
101
+ if (!(key in bag)) return
102
+ delete bag[key]
103
+ writeBag(bag)
104
+ },
105
+ }
106
+
107
+ // ---------------------------------------------------------------- client
108
+
109
+ let client = null
110
+ const listeners = new Set()
111
+ let lastStatus = null
112
+
113
+ // What the account holds on the server, read with the account's own session
114
+ // (row level security lets an owner read their balance and anyone read a
115
+ // profile): the coin balance the phone builder spends and the name others
116
+ // see. Kept for the uid it was read for, so a status for another account
117
+ // never carries these.
118
+ let held = { uid: null, coins: undefined, handle: undefined, at: 0 }
119
+ const HELD_FRESH_MS = 30 * 1000
120
+ const HELD_EVERY_MS = 90 * 1000
121
+ let heldTimer = null
122
+ let heldReading = null
123
+
124
+ function statusFrom(session) {
125
+ const user = session?.user
126
+ if (!user) return { signedIn: false }
127
+ const meta = user.user_metadata ?? {}
128
+ const name = [meta.full_name, meta.name].find((v) => typeof v === 'string' && v.trim() !== '')
129
+ const mine = held.uid === user.id
130
+ return {
131
+ signedIn: true,
132
+ email: typeof user.email === 'string' ? user.email : undefined,
133
+ name: name ? name.trim() : undefined,
134
+ uid: user.id,
135
+ // Undefined until the first read answers, or when it never could.
136
+ coins: mine ? held.coins : undefined,
137
+ handle: mine ? held.handle : undefined,
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Reads the balance and the profile name again and announces the status when
143
+ * either changed. Never throws; one read at a time. A failed read keeps what
144
+ * was there: an offline studio shows the last balance rather than none.
145
+ */
146
+ function refreshHeld() {
147
+ if (heldReading) return heldReading
148
+ heldReading = (async () => {
149
+ try {
150
+ const { data } = await getClient().auth.getSession()
151
+ const session = data?.session
152
+ const uid = session?.user?.id
153
+ if (!uid) return
154
+ const db = getClient()
155
+ const [coins, profile] = await Promise.all([
156
+ db.from('coin_balances').select('balance').eq('owner', uid).maybeSingle(),
157
+ db.from('profiles').select('display_name').eq('id', uid).maybeSingle(),
158
+ ])
159
+ const same = held.uid === uid
160
+ const next = { uid, coins: same ? held.coins : undefined, handle: same ? held.handle : undefined, at: Date.now() }
161
+ // No row is a balance of nothing: the server makes the row with the
162
+ // first coins it gives.
163
+ if (!coins.error) {
164
+ const balance = Number(coins.data?.balance ?? 0)
165
+ next.coins = Number.isFinite(balance) ? balance : 0
166
+ }
167
+ if (!profile.error && typeof profile.data?.display_name === 'string') next.handle = profile.data.display_name
168
+ // Signed out (or into another account) while this was reading: drop it.
169
+ const { data: after } = await getClient().auth.getSession()
170
+ if (after?.session?.user?.id !== uid) return
171
+ held = next
172
+ notify(statusFrom(after.session))
173
+ } catch (err) {
174
+ console.warn('[auth] reading the balance failed:', err?.message ?? err)
175
+ } finally {
176
+ heldReading = null
177
+ }
178
+ })()
179
+ return heldReading
180
+ }
181
+
182
+ /** Keeps the balance current while someone is signed in; stops when nobody is. */
183
+ function keepHeld(signedIn) {
184
+ if (signedIn && !heldTimer) {
185
+ heldTimer = setInterval(() => void refreshHeld(), HELD_EVERY_MS)
186
+ heldTimer.unref?.()
187
+ } else if (!signedIn && heldTimer) {
188
+ clearInterval(heldTimer)
189
+ heldTimer = null
190
+ }
191
+ }
192
+
193
+ function notify(status) {
194
+ const before = JSON.stringify(lastStatus)
195
+ lastStatus = status
196
+ if (before === JSON.stringify(status)) return
197
+ for (const fn of listeners) {
198
+ try {
199
+ fn(status)
200
+ } catch (err) {
201
+ console.warn('[auth] listener failed:', err?.message ?? err)
202
+ }
203
+ }
204
+ }
205
+
206
+ function getClient() {
207
+ if (client) return client
208
+ client = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
209
+ auth: {
210
+ flowType: 'pkce',
211
+ persistSession: true,
212
+ autoRefreshToken: true,
213
+ // No page URL to read a code from: the loopback server hands it over.
214
+ detectSessionInUrl: false,
215
+ storageKey: STORAGE_KEY,
216
+ storage: secretsAdapter,
217
+ },
218
+ })
219
+ // Kept to reading the session it is handed: calling back into the client
220
+ // from inside this callback is what supabase-js warns deadlocks. The
221
+ // balance is read on the next turn of the loop, outside it.
222
+ client.auth.onAuthStateChange((_event, session) => {
223
+ if (!session?.user) held = { uid: null, coins: undefined, handle: undefined, at: 0 }
224
+ notify(statusFrom(session))
225
+ keepHeld(!!session?.user)
226
+ if (session?.user && held.uid !== session.user.id) setTimeout(() => void refreshHeld(), 0)
227
+ })
228
+ return client
229
+ }
230
+
231
+ /** Current account, refreshing an expired token if there is one to refresh.
232
+ * Answers at once with the last balance it read; a newer one, when it was
233
+ * due, follows as a change. */
234
+ async function status() {
235
+ try {
236
+ const { data } = await getClient().auth.getSession()
237
+ const next = statusFrom(data?.session)
238
+ notify(next)
239
+ keepHeld(next.signedIn)
240
+ if (next.signedIn && (held.uid !== next.uid || Date.now() - held.at > HELD_FRESH_MS)) void refreshHeld()
241
+ return next
242
+ } catch (err) {
243
+ console.warn('[auth] status failed:', err?.message ?? err)
244
+ return lastStatus ?? { signedIn: false }
245
+ }
246
+ }
247
+
248
+ /** Subscribes to account changes; returns the unsubscribe function. */
249
+ function onChange(handler) {
250
+ listeners.add(handler)
251
+ return () => listeners.delete(handler)
252
+ }
253
+
254
+ /** The bearer token for the publish function, or null when signed out. */
255
+ async function getAccessToken() {
256
+ const { data, error } = await getClient().auth.getSession()
257
+ if (error) return null
258
+ return data?.session?.access_token ?? null
259
+ }
260
+
261
+ // ---------------------------------------------------------------- loopback server
262
+
263
+ // The first free port of the three, or null. Ports are tried in order so the
264
+ // same one is used run after run unless something else is sitting on it.
265
+ function listenOnAllowed() {
266
+ return new Promise((resolve) => {
267
+ const tryPort = (index) => {
268
+ if (index >= PORTS.length) return resolve(null)
269
+ const server = http.createServer()
270
+ server.once('error', () => tryPort(index + 1))
271
+ server.listen(PORTS[index], '127.0.0.1', () => resolve({ server, port: PORTS[index] }))
272
+ }
273
+ tryPort(0)
274
+ })
275
+ }
276
+
277
+ function page(title, body) {
278
+ return `<!doctype html><meta charset="utf-8"><title>${title}</title>
279
+ <style>body{font:15px/1.6 system-ui,sans-serif;background:#0b0d14;color:#e6e8ef;display:grid;place-items:center;min-height:100vh;margin:0}main{max-width:26em;padding:2em;text-align:center}h1{font-size:1.15em;font-weight:600;margin:0 0 .4em}p{color:#9aa0ad;margin:0}</style>
280
+ <main><h1>${title}</h1><p>${body}</p></main>`
281
+ }
282
+
283
+ function closeServer(server) {
284
+ return new Promise((resolve) => {
285
+ server.closeAllConnections?.()
286
+ server.close(() => resolve())
287
+ })
288
+ }
289
+
290
+ // One sign-in at a time: a second click while the browser is open would bind
291
+ // another port and leave the first tab pointing at a dead one.
292
+ let current = null
293
+
294
+ /**
295
+ * Starts a sign-in: binds the loopback port, builds the OAuth URL, opens it
296
+ * in the browser, and returns before the user has done anything. `done`
297
+ * resolves with the new status or rejects; either way the port is released.
298
+ * Split from signIn() so the self-test can inspect the URL and drive the
299
+ * callback itself.
300
+ */
301
+ async function beginSignIn({ open = true } = {}) {
302
+ if (current) {
303
+ throw new Error('A sign-in is already open in your browser. Finish it there, or wait for it to time out.')
304
+ }
305
+ const { secrets, openExternal } = getDeps()
306
+ if (!secrets.encryptionAvailable()) {
307
+ throw new Error('This system has no OS-level encryption available, so the account cannot be stored here.')
308
+ }
309
+
310
+ const bound = await listenOnAllowed()
311
+ if (!bound) {
312
+ throw new Error(`Ports ${PORTS[0]} to ${PORTS[PORTS.length - 1]} are all in use, so the browser cannot hand the sign-in back.`)
313
+ }
314
+ const { server, port } = bound
315
+ const redirectTo = `http://127.0.0.1:${port}${CALLBACK_PATH}`
316
+
317
+ let url
318
+ try {
319
+ const { data, error } = await getClient().auth.signInWithOAuth({
320
+ provider: 'google',
321
+ options: {
322
+ redirectTo,
323
+ skipBrowserRedirect: true,
324
+ queryParams: { prompt: 'select_account' },
325
+ },
326
+ })
327
+ if (error || !data?.url) throw new Error(error?.message ?? 'Supabase returned no sign-in URL.')
328
+ url = data.url
329
+ } catch (err) {
330
+ await closeServer(server)
331
+ throw err
332
+ }
333
+
334
+ let settle
335
+ const done = new Promise((resolve, reject) => {
336
+ settle = { resolve, reject }
337
+ })
338
+ let finished = false
339
+ const finish = async (outcome) => {
340
+ if (finished) return
341
+ finished = true
342
+ clearTimeout(timer)
343
+ await closeServer(server)
344
+ if (outcome.ok) settle.resolve(outcome.status)
345
+ else {
346
+ // A verifier from a flow that never completed is worthless; drop it so
347
+ // the bag does not accumulate one per abandoned attempt.
348
+ try {
349
+ writeBag({})
350
+ } catch {
351
+ // Nothing to clean or nothing to clean it with.
352
+ }
353
+ settle.reject(outcome.error)
354
+ }
355
+ }
356
+
357
+ const timer = setTimeout(
358
+ () => void finish({ ok: false, error: new Error('Sign-in timed out after 5 minutes. Try again.') }),
359
+ SIGN_IN_TIMEOUT_MS,
360
+ )
361
+
362
+ server.on('request', (req, res) => {
363
+ const target = new URL(req.url ?? '/', `http://127.0.0.1:${port}`)
364
+ if (target.pathname !== CALLBACK_PATH) {
365
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }).end('Not found')
366
+ return
367
+ }
368
+ // Same page in every case: the browser tab is not where a failure gets
369
+ // explained, the studio is.
370
+ const reply = (code) =>
371
+ res
372
+ .writeHead(code, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' })
373
+ .end(page('Oda Studio', 'You can return to the studio.'))
374
+
375
+ if (finished) {
376
+ reply(200)
377
+ return
378
+ }
379
+ const code = target.searchParams.get('code')
380
+ const oauthError = target.searchParams.get('error')
381
+ if (!code) {
382
+ reply(200)
383
+ const detail = target.searchParams.get('error_description') ?? oauthError ?? 'no code in the callback'
384
+ void finish({ ok: false, error: new Error(`Sign-in was not completed (${detail}).`) })
385
+ return
386
+ }
387
+ void getClient()
388
+ .auth.exchangeCodeForSession(code)
389
+ .then(({ data, error }) => {
390
+ reply(200)
391
+ if (error) return finish({ ok: false, error: new Error(error.message) })
392
+ const status = statusFrom(data?.session)
393
+ notify(status)
394
+ return finish({ ok: true, status })
395
+ })
396
+ .catch((err) => {
397
+ reply(200)
398
+ return finish({ ok: false, error: err instanceof Error ? err : new Error(String(err)) })
399
+ })
400
+ })
401
+
402
+ if (open) {
403
+ try {
404
+ await openExternal(url)
405
+ } catch (err) {
406
+ await finish({ ok: false, error: new Error(`The browser could not be opened (${err?.message ?? err}).`) })
407
+ }
408
+ }
409
+
410
+ const attempt = {
411
+ port,
412
+ url,
413
+ done,
414
+ cancel: () => finish({ ok: false, error: new Error('Sign-in was cancelled.') }),
415
+ }
416
+ current = attempt
417
+ const clear = () => {
418
+ if (current === attempt) current = null
419
+ }
420
+ done.then(clear, clear)
421
+ return attempt
422
+ }
423
+
424
+ /** { ok, status } or { ok: false, error }: never throws. */
425
+ async function signIn() {
426
+ try {
427
+ const attempt = await beginSignIn()
428
+ const status = await attempt.done
429
+ return { ok: true, status }
430
+ } catch (err) {
431
+ return { ok: false, error: err?.message ?? String(err) }
432
+ }
433
+ }
434
+
435
+ /** Removes the session here and revokes it server-side when reachable. */
436
+ async function signOut() {
437
+ try {
438
+ const { error } = await getClient().auth.signOut()
439
+ // supabase-js drops the local session even when the revoke call fails,
440
+ // so an offline sign-out still signs out; only say so.
441
+ if (error) console.warn('[auth] server sign-out failed:', error.message)
442
+ } catch (err) {
443
+ // Never leave a session the user asked to remove: clear it by hand.
444
+ try {
445
+ getDeps().secrets.clearSecret(SESSION_SECRET)
446
+ writeBag({})
447
+ } catch {
448
+ return { ok: false, error: `The account could not be signed out (${err?.message ?? err}).` }
449
+ }
450
+ }
451
+ const next = { signedIn: false }
452
+ notify(next)
453
+ return { ok: true, status: next }
454
+ }
455
+
456
+ module.exports = {
457
+ SUPABASE_URL,
458
+ // For a call that needs no account (publish.cjs asks the publish function
459
+ // what it can do with it when nobody is signed in).
460
+ SUPABASE_ANON_KEY,
461
+ PORTS,
462
+ configure,
463
+ status,
464
+ onChange,
465
+ getAccessToken,
466
+ // The signed-in client, for the account's own rows (cloud.cjs). Every call
467
+ // through it carries the session; row level security does the rest.
468
+ client: () => getClient(),
469
+ // After something that spends or adds coins: read the balance now.
470
+ refreshCoins: () => refreshHeld(),
471
+ beginSignIn,
472
+ signIn,
473
+ signOut,
474
+ }
475
+
476
+ // ---------------------------------------------------------------- self-test
477
+
478
+ // `node apps/studio/electron/auth.cjs --self-test`: an in-memory secret store
479
+ // and a browser that records the URL instead of opening it. Checks the port
480
+ // binding, the shape of the OAuth URL, the callback server's replies, the
481
+ // one-at-a-time rule, and that the port is released afterwards. Nothing here
482
+ // talks to Supabase or Google.
483
+ async function selfTest() {
484
+ const net = require('node:net')
485
+ let failures = 0
486
+ const check = (label, pass, detail) => {
487
+ console.log(`${pass ? 'PASS' : 'FAIL'} ${label}`)
488
+ if (!pass) {
489
+ failures++
490
+ if (detail !== undefined) console.log(' ', detail)
491
+ }
492
+ }
493
+
494
+ const store = new Map()
495
+ const memorySecrets = {
496
+ encryptionAvailable: () => true,
497
+ getSecret: (id) => store.get(id) ?? null,
498
+ setSecret: (id, v) => void store.set(id, v),
499
+ clearSecret: (id) => void store.delete(id),
500
+ }
501
+ const opened = []
502
+ configure({ secrets: memorySecrets, openExternal: async (url) => void opened.push(url) })
503
+
504
+ const portOpen = (port) =>
505
+ new Promise((resolve) => {
506
+ const socket = net.connect(port, '127.0.0.1')
507
+ socket.once('connect', () => {
508
+ socket.destroy()
509
+ resolve(true)
510
+ })
511
+ socket.once('error', () => resolve(false))
512
+ })
513
+
514
+ check('1. nothing signed in on an empty store', (await status()).signedIn === false)
515
+
516
+ const attempt = await beginSignIn()
517
+ check('2. bound one of the allowed ports', PORTS.includes(attempt.port), attempt.port)
518
+ check('3. browser was handed the URL', opened.length === 1 && opened[0] === attempt.url)
519
+ check('4. URL is the project authorize endpoint', attempt.url.startsWith(`${SUPABASE_URL}/auth/v1/authorize?`), attempt.url)
520
+ check('5. URL carries the loopback redirect', attempt.url.includes('redirect_to=http%3A%2F%2F127.0.0.1%3A5368'), attempt.url)
521
+ check('6. URL carries a PKCE challenge', /[?&]code_challenge=[^&]+/.test(attempt.url) && attempt.url.includes('code_challenge_method=s256'))
522
+ check('7. URL asks Google for the account picker', attempt.url.includes('prompt=select_account'))
523
+ check('8. URL carries no token or key', !/access_token|apikey/i.test(attempt.url))
524
+ check('9. verifier is stored in the secrets bag', store.has(VERIFIER_SECRET) && !store.has(SESSION_SECRET))
525
+
526
+ const second = await signIn()
527
+ check('10. a second sign-in is refused while one is open', second.ok === false && /already open/.test(second.error), second)
528
+ const others = await Promise.all(PORTS.filter((p) => p !== attempt.port).map(portOpen))
529
+ check('10b. the refusal bound no extra port', others.every((open) => open === false))
530
+
531
+ const base = `http://127.0.0.1:${attempt.port}`
532
+ const other = await fetch(`${base}/somewhere-else`)
533
+ check('11. unknown paths answer 404', other.status === 404)
534
+
535
+ const denied = await fetch(`${base}${CALLBACK_PATH}?error=access_denied&error_description=User+said+no`)
536
+ const html = await denied.text()
537
+ check('12. callback without a code answers the return page', denied.status === 200 && html.includes('You can return to the studio.'))
538
+ let outcome = null
539
+ try {
540
+ await attempt.done
541
+ } catch (err) {
542
+ outcome = err
543
+ }
544
+ check('13. the attempt settles with the provider error', outcome instanceof Error && /User said no/.test(outcome.message), outcome?.message)
545
+ await new Promise((r) => setTimeout(r, 50))
546
+ check('14. port is released afterwards', (await portOpen(attempt.port)) === false)
547
+ check('15. abandoned verifier was dropped', !store.has(VERIFIER_SECRET))
548
+
549
+ // A second, fresh attempt binds again and can be cancelled from our side.
550
+ const again = await beginSignIn({ open: false })
551
+ check('16. a new attempt binds a port again', PORTS.includes(again.port))
552
+ let cancelled = null
553
+ again.done.catch((err) => (cancelled = err))
554
+ await again.cancel()
555
+ await new Promise((r) => setTimeout(r, 20))
556
+ check('17. cancel settles the attempt and frees the port', /cancelled/.test(cancelled?.message ?? '') && (await portOpen(again.port)) === false)
557
+
558
+ check('18. still nothing signed in', (await status()).signedIn === false)
559
+ check('19. signOut on a signed-out store is a clean no-op', (await signOut()).ok === true)
560
+
561
+ console.log(failures === 0 ? '\nall checks passed' : `\n${failures} check(s) failed`)
562
+ process.exit(failures === 0 ? 0 : 1)
563
+ }
564
+
565
+ if (require.main === module && process.argv.includes('--self-test')) {
566
+ selfTest().catch((err) => {
567
+ console.error(err)
568
+ process.exit(1)
569
+ })
570
+ }