pinokiod 8.3.2 → 8.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server/index.js CHANGED
@@ -29,6 +29,7 @@ const serveIndex = require('./serveIndex')
29
29
  const registerFileRoutes = require('./routes/files')
30
30
  const registerAppRoutes = require('./routes/apps')
31
31
  const registerConnectRoutes = require('./routes/connect')
32
+ const registerGithubAuthRoutes = require('./routes/github_auth')
32
33
  const ServerAutolaunch = require('./autolaunch')
33
34
  const Git = require("../kernel/git")
34
35
  const TerminalApi = require('../kernel/api/terminal')
@@ -1622,144 +1623,9 @@ class Server {
1622
1623
  const connection = await this.get_github_connection()
1623
1624
  return connection.display
1624
1625
  }
1625
- async get_legacy_github_hosts() {
1626
- let hosts = ""
1627
- let hosts_file = this.kernel.path("config/gh/hosts.yml")
1628
- let e = await this.exists(hosts_file)
1629
- if (e) {
1630
- hosts = await fs.promises.readFile(hosts_file, "utf8")
1631
- if (hosts.startsWith("{}")) {
1632
- hosts = ""
1633
- }
1634
- }
1635
- return hosts
1636
- }
1637
- github_command_env(interactive = false) {
1638
- const env = this.kernel && this.kernel.envs
1639
- ? { ...this.kernel.envs }
1640
- : (this.kernel && this.kernel.bin && typeof this.kernel.bin.envs === 'function'
1641
- ? this.kernel.bin.envs(process.env)
1642
- : { ...process.env })
1643
-
1644
- if (interactive) {
1645
- delete env.GCM_INTERACTIVE
1646
- delete env.GIT_TERMINAL_PROMPT
1647
- delete env.GIT_ASKPASS
1648
- delete env.SSH_ASKPASS
1649
- } else {
1650
- Object.assign(env, NON_INTERACTIVE_GIT_ENV)
1651
- }
1652
-
1653
- return env
1654
- }
1655
- async github_gcm(args, options = {}) {
1656
- return new Promise((resolve, reject) => {
1657
- execFile(
1658
- 'git',
1659
- ['credential-manager', 'github', ...args],
1660
- {
1661
- cwd: this.kernel.homedir,
1662
- env: this.github_command_env(Boolean(options.interactive)),
1663
- timeout: Number.isFinite(options.timeout) ? options.timeout : 15000,
1664
- maxBuffer: 1024 * 1024,
1665
- },
1666
- (error, stdout, stderr) => {
1667
- if (error) {
1668
- error.stderr = stderr
1669
- reject(error)
1670
- return
1671
- }
1672
- resolve(stdout || "")
1673
- }
1674
- )
1675
- })
1676
- }
1626
+ // GitHub login state, read from the token Pinokio stored (kernel/github_auth.js).
1677
1627
  async get_github_connection(options = {}) {
1678
- if (this._githubConnectionPromise) {
1679
- return this._githubConnectionPromise
1680
- }
1681
-
1682
- this._githubConnectionPromise = (async () => {
1683
- const legacyHosts = await this.get_legacy_github_hosts()
1684
- let accounts = []
1685
- let gcmError = null
1686
-
1687
- try {
1688
- const stdout = await this.github_gcm(['list'], {
1689
- timeout: Number.isFinite(options.timeout) ? options.timeout : 10000
1690
- })
1691
- accounts = stdout
1692
- .split(/\r?\n/)
1693
- .map((line) => line.trim())
1694
- .filter(Boolean)
1695
- } catch (error) {
1696
- gcmError = error && (error.stderr || error.message) ? String(error.stderr || error.message).trim() : String(error)
1697
- }
1698
-
1699
- const display = accounts.length > 0
1700
- ? accounts.map((account) => `github.com: ${account}`).join("\n")
1701
- : ""
1702
-
1703
- return {
1704
- accounts,
1705
- legacyHosts,
1706
- display,
1707
- connected: accounts.length > 0,
1708
- provider: accounts.length > 0 ? "gcm" : null,
1709
- gcmError,
1710
- }
1711
- })()
1712
-
1713
- try {
1714
- return await this._githubConnectionPromise
1715
- } finally {
1716
- this._githubConnectionPromise = null
1717
- }
1718
- }
1719
- github_login_params() {
1720
- const doneMarker = "PINOKIO_GITHUB_LOGIN_DONE"
1721
- const delimiter = this.kernel.platform === "win32" ? " && " : " ; "
1722
- const doneCommand = this.kernel.platform === "win32"
1723
- ? "echo P^INOKIO_GITHUB_LOGIN_DONE"
1724
- : "(GCM_DONE=INOKIO_GITHUB_LOGIN_DONE; printf 'P%s\\n' \"$GCM_DONE\")"
1725
- const loginCommand = [
1726
- "git credential-manager github login --device --force",
1727
- doneCommand
1728
- ].join(" && ")
1729
-
1730
- return {
1731
- doneMarker,
1732
- message: [
1733
- "git config --global --replace-all credential.helper manager",
1734
- "git config --global --replace-all credential.gitHubAuthModes oauth",
1735
- "git config --global --replace-all credential.namespace pinokio",
1736
- "git config --global --replace-all credential.https://github.com.helper manager",
1737
- "git config --global --replace-all credential.https://github.com.provider github",
1738
- loginCommand
1739
- ].join(delimiter)
1740
- }
1741
- }
1742
- github_logout_command(connection) {
1743
- const accounts = connection && Array.isArray(connection.accounts) ? connection.accounts : []
1744
- const safeAccounts = accounts.filter((account) => /^[A-Za-z0-9._-]+$/.test(account))
1745
- if (safeAccounts.length === 0) {
1746
- return null
1747
- }
1748
- const delimiter = this.kernel.platform === "win32" ? " && " : " ; "
1749
- return safeAccounts.map((account) => `git credential-manager github logout ${account}`).join(delimiter)
1750
- }
1751
- async github_logout_params(connection) {
1752
- const hadLegacyAuth = Boolean(connection && connection.legacyHosts && connection.legacyHosts.length > 0)
1753
- if (hadLegacyAuth) {
1754
- await this.clear_legacy_github_auth()
1755
- }
1756
- return {
1757
- hadLegacyAuth,
1758
- message: this.github_logout_command(connection)
1759
- }
1760
- }
1761
- async clear_legacy_github_auth() {
1762
- await fs.promises.rm(this.kernel.path("config/gh/hosts.yml"), { force: true }).catch(() => {})
1628
+ return this.kernel.githubAuth.connection(options)
1763
1629
  }
1764
1630
  async current_urls(current_path) {
1765
1631
  return {}
@@ -12904,6 +12770,18 @@ class Server {
12904
12770
  getProviderConnection: (provider, options) => this.kernel.connect.connected(provider, options)
12905
12771
  })
12906
12772
  /*
12773
+ GET /github/login => GitHub device login page (replaces Git Credential Manager)
12774
+ */
12775
+ registerGithubAuthRoutes(this.app, {
12776
+ auth: this.kernel.githubAuth,
12777
+ getPageContext: (req) => ({
12778
+ portal: this.portal,
12779
+ logo: this.logo,
12780
+ theme: this.theme,
12781
+ agent: req.agent
12782
+ })
12783
+ })
12784
+ /*
12907
12785
  * GET /connect/x
12908
12786
  * GET /connect/discord
12909
12787
  */
@@ -13565,8 +13443,8 @@ class Server {
13565
13443
  let hosts = githubConnection.display
13566
13444
 
13567
13445
  let items
13568
- if (githubConnection.connected) {
13569
- // logged in => display logout
13446
+ if (githubConnection.saved) {
13447
+ // Pinokio has a login saved => display logout (a login from outside Pinokio cannot be removed here)
13570
13448
  items = [{
13571
13449
  icon: "fa-solid fa-circle-xmark",
13572
13450
  title: "Logout",
@@ -13637,57 +13515,7 @@ class Server {
13637
13515
  res.json({ success: true })
13638
13516
 
13639
13517
  }))
13640
- this.app.get("/github/status", ex(async (req, res) => {
13641
- let id = "gh_status"
13642
- let params = new URLSearchParams()
13643
- let message = "git credential-manager github list"
13644
- params.set("message", encodeURIComponent(message))
13645
- params.set("path", this.kernel.homedir)
13646
- // params.set("kill", "/Logged in/i")
13647
- params.set("kill_message", "Click to return home")
13648
- params.set("callback", encodeURIComponent("/github"))
13649
- params.set("target", "_top")
13650
- params.set("id", id)
13651
- let url = `/shell/${id}?${params.toString()}`
13652
- res.redirect(url)
13653
- }))
13654
- this.app.get("/github/logout", ex(async (req, res) => {
13655
- let id = "gh_logout"
13656
- let params = new URLSearchParams()
13657
- const githubConnection = await this.get_github_connection()
13658
- let { hadLegacyAuth, message } = await this.github_logout_params(githubConnection)
13659
- if (!message && hadLegacyAuth) {
13660
- res.redirect("/github")
13661
- return
13662
- }
13663
- if (!message) {
13664
- message = "git credential-manager github list"
13665
- }
13666
- params.set("message", encodeURIComponent(message))
13667
- params.set("path", this.kernel.homedir)
13668
- // params.set("kill", "/Logged in/i")
13669
- // params.set("kill_message", "Click to return home")
13670
- params.set("callback", encodeURIComponent("/github"))
13671
- params.set("id", id)
13672
- params.set("target", "_top")
13673
- let url = `/shell/${id}?${params.toString()}`
13674
- res.redirect(url)
13675
- }))
13676
- this.app.get("/github/login", ex(async (req, res) => {
13677
- let id = "gh_login"
13678
- this.kernel.shell.kill({ id: `shell/${id}` })
13679
- let params = new URLSearchParams()
13680
- const { doneMarker, message } = this.github_login_params()
13681
- params.set("message", encodeURIComponent(message))
13682
- params.set("input", true)
13683
- params.set("path", this.kernel.homedir)
13684
- params.set("kill", `/${doneMarker}/`)
13685
- params.set("callback", encodeURIComponent("/github"))
13686
- params.set("id", id)
13687
- params.set("target", "_top")
13688
- let url = `/shell/${id}?${params.toString()}`
13689
- res.redirect(url)
13690
- }))
13518
+ // /github/login and /github/logout are served by routes/github_auth.js
13691
13519
  this.app.get("/terminals/gemini/fork", ex(async (req, res) => {
13692
13520
  const source = typeof req.query.source === "string" ? req.query.source.trim() : ""
13693
13521
  const expectedSessionId = typeof req.query.expected_session_id === "string" ? req.query.expected_session_id.trim() : ""
@@ -0,0 +1,43 @@
1
+ // GitHub login routes (device flow), backed by kernel/github_auth.js.
2
+ //
3
+ // GET /github/login login page: shows the device code and waits
4
+ // POST /github/login/start asks GitHub for a device code and starts polling
5
+ // GET /github/login/status { connected, saved, login, display, source, session }
6
+ // GET /github/logout removes the stored token and returns to /github
7
+ module.exports = function registerGithubAuthRoutes(app, options = {}) {
8
+ const auth = options.auth
9
+ const getPageContext = options.getPageContext || (() => ({}))
10
+ const noStore = (res) => res.set("Cache-Control", "no-store")
11
+
12
+ app.get("/github/login", (req, res) => {
13
+ res.render("github_login", getPageContext(req))
14
+ })
15
+
16
+ app.post("/github/login/start", async (req, res) => {
17
+ noStore(res)
18
+ try {
19
+ const session = await auth.startLogin()
20
+ res.json({ status: "ok", login: session })
21
+ } catch (error) {
22
+ res.json({ status: "error", error: error && error.message ? error.message : String(error) })
23
+ }
24
+ })
25
+
26
+ app.get("/github/login/status", async (req, res) => {
27
+ noStore(res)
28
+ try {
29
+ res.json(await auth.status())
30
+ } catch (error) {
31
+ res.json({ connected: false, error: error && error.message ? error.message : String(error) })
32
+ }
33
+ })
34
+
35
+ app.get("/github/logout", async (req, res) => {
36
+ try {
37
+ await auth.logout()
38
+ res.redirect("/github")
39
+ } catch (error) {
40
+ res.status(500).type("text").send(`GitHub logout failed: ${error && error.message ? error.message : error}`)
41
+ }
42
+ })
43
+ }
@@ -155,7 +155,7 @@
155
155
  const connectionLabel = isGithubConnected ? "Connected" : "Not connected";
156
156
  const connectionIcon = isGithubConnected ? "fa-solid fa-circle-check" : "fa-regular fa-circle";
157
157
  const connectionDetail = isGithubConnected
158
- ? "Git Credential Manager is ready for GitHub operations inside Pinokio."
158
+ ? "Git and gh inside Pinokio use this login for GitHub operations."
159
159
  : "Connect GitHub to clone private repositories and publish from Pinokio.";
160
160
  %>
161
161
  <body class="<%= theme %> main-sidebar-page task-launcher-page task-page setup-page github-page" data-agent="<%= agent %>" data-page="github-config">
@@ -172,7 +172,7 @@
172
172
  <p class="task-description">Connect GitHub for private repositories and publishing, then set the identity Git writes on commits.</p>
173
173
  <div class="task-badge-row task-header-badges">
174
174
  <span class="task-badge <%= isGithubConnected ? 'task-badge-accent' : 'task-badge-neutral' %>"><%= connectionLabel %></span>
175
- <span class="task-badge task-badge-neutral">Git Credential Manager</span>
175
+ <span class="task-badge task-badge-neutral">GitHub device login</span>
176
176
  <span class="task-badge task-badge-neutral">~/pinokio/gitconfig</span>
177
177
  </div>
178
178
  </div>
@@ -0,0 +1,390 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>GitHub Login</title>
7
+ <link href="/css/fontawesome.min.css" rel="stylesheet">
8
+ <link href="/css/solid.min.css" rel="stylesheet">
9
+ <link href="/css/regular.min.css" rel="stylesheet">
10
+ <link href="/css/brands.min.css" rel="stylesheet">
11
+ <link href="/noty.css" rel="stylesheet">
12
+ <link href="/style.css" rel="stylesheet">
13
+ <link href="/task-launcher.css" rel="stylesheet">
14
+ <% if (agent === "electron") { %>
15
+ <link href="/electron.css" rel="stylesheet"/>
16
+ <% } %>
17
+ <style>
18
+ .gh-login-shell {
19
+ max-width: 980px;
20
+ }
21
+ .gh-state-panel {
22
+ display: flex;
23
+ align-items: flex-start;
24
+ gap: 14px;
25
+ }
26
+ .gh-state-icon {
27
+ width: 36px;
28
+ height: 36px;
29
+ border-radius: 8px;
30
+ display: inline-flex;
31
+ align-items: center;
32
+ justify-content: center;
33
+ flex: 0 0 auto;
34
+ background: var(--task-chip-bg, var(--task-soft));
35
+ border: 1px solid var(--task-border);
36
+ color: var(--task-text);
37
+ }
38
+ .gh-state-copy {
39
+ min-width: 0;
40
+ }
41
+ .gh-state-title {
42
+ margin: 0;
43
+ color: var(--task-text);
44
+ font-size: 18px;
45
+ font-weight: 800;
46
+ line-height: 1.25;
47
+ letter-spacing: 0;
48
+ }
49
+ .gh-state-detail {
50
+ margin: 8px 0 0;
51
+ color: var(--task-muted);
52
+ font-size: 14px;
53
+ line-height: 1.55;
54
+ }
55
+ .gh-action-row {
56
+ display: flex;
57
+ flex-wrap: wrap;
58
+ gap: 10px;
59
+ margin-top: 20px;
60
+ }
61
+ .gh-code-panel {
62
+ display: grid;
63
+ gap: 10px;
64
+ max-width: 520px;
65
+ margin-top: 18px;
66
+ padding: 14px;
67
+ border: 1px solid var(--task-border);
68
+ border-radius: 8px;
69
+ background: var(--task-panel);
70
+ }
71
+ .gh-code-panel.hidden {
72
+ display: none;
73
+ }
74
+ .gh-code-label {
75
+ margin: 0;
76
+ color: var(--task-muted);
77
+ font-size: 13px;
78
+ line-height: 1.45;
79
+ }
80
+ .gh-code-row {
81
+ display: flex;
82
+ flex-wrap: wrap;
83
+ align-items: center;
84
+ gap: 10px;
85
+ }
86
+ .gh-code-value {
87
+ display: inline-flex;
88
+ align-items: center;
89
+ padding: 9px 11px;
90
+ border: 1px solid var(--task-border);
91
+ border-radius: 6px;
92
+ color: var(--task-text);
93
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
94
+ font-size: 15px;
95
+ font-weight: 800;
96
+ letter-spacing: 0.08em;
97
+ }
98
+ .gh-code-link {
99
+ margin: 0;
100
+ color: var(--task-muted);
101
+ font-size: 12px;
102
+ line-height: 1.45;
103
+ overflow-wrap: anywhere;
104
+ }
105
+ .gh-error {
106
+ margin-top: 16px;
107
+ }
108
+ </style>
109
+ </head>
110
+ <%
111
+ const selected = "connect";
112
+ %>
113
+ <body class="<%= theme %> main-sidebar-page task-launcher-page task-page setup-page" data-agent="<%= agent %>" data-page="github-login">
114
+ <%- include('partials/app_navheader', { agent }) %>
115
+ <main>
116
+ <div class="task-container">
117
+ <section class="task-shell gh-login-shell">
118
+ <header class="task-shell-header">
119
+ <div class="task-shell-header-main">
120
+ <div class="task-shell-topline">
121
+ <p class="task-eyebrow">Login / GitHub</p>
122
+ </div>
123
+ <h1 class="task-title">Authorize GitHub</h1>
124
+ <p class="task-description">Copy the device code, open GitHub, then approve the login. Pinokio will continue when the token is saved.</p>
125
+ <div class="task-badge-row task-header-badges">
126
+ <span class="task-badge task-badge-accent" id="gh-badge">Starting</span>
127
+ <span class="task-badge task-badge-neutral">Works from any device</span>
128
+ </div>
129
+ </div>
130
+ </header>
131
+
132
+ <div class="task-shell-body">
133
+ <section class="task-section task-section-subtle">
134
+ <div class="gh-state-panel">
135
+ <div class="gh-state-icon" aria-hidden="true">
136
+ <i class="fa-solid fa-circle-notch fa-spin" id="gh-icon"></i>
137
+ </div>
138
+ <div class="gh-state-copy">
139
+ <h2 class="gh-state-title" id="gh-title">Checking GitHub login</h2>
140
+ <p class="gh-state-detail" id="gh-detail">Pinokio is checking whether a GitHub token is already saved.</p>
141
+ <div class="gh-action-row">
142
+ <button class="task-button primary hidden" id="gh-login" type="button">
143
+ <i class="fa-solid fa-key" aria-hidden="true"></i>
144
+ <span>Log In</span>
145
+ </button>
146
+ <a class="task-button hidden" id="gh-done" href="/github">
147
+ <i class="fa-solid fa-check" aria-hidden="true"></i>
148
+ <span>Done</span>
149
+ </a>
150
+ </div>
151
+ <div class="gh-code-panel hidden" id="gh-code">
152
+ <p class="gh-code-label">GitHub is asking for this device code.</p>
153
+ <div class="gh-code-row">
154
+ <div class="gh-code-value" id="gh-code-value"></div>
155
+ <button class="task-button primary" id="gh-open" type="button">
156
+ <i class="fa-solid fa-arrow-up-right-from-square" aria-hidden="true"></i>
157
+ <span>Copy and Open GitHub</span>
158
+ </button>
159
+ </div>
160
+ <p class="gh-code-link">Or enter the code yourself at <a id="gh-code-href" href="https://github.com/login/device" target="_blank" rel="noopener">github.com/login/device</a>.</p>
161
+ </div>
162
+ <div class="task-status error hidden gh-error" id="gh-error"></div>
163
+ </div>
164
+ </div>
165
+ </section>
166
+ </div>
167
+ </section>
168
+ </div>
169
+ <%- include('partials/main_sidebar', { selected }) %>
170
+ </main>
171
+
172
+ <script>
173
+ const START_URL = "/github/login/start"
174
+ const STATUS_URL = "/github/login/status"
175
+ const POLL_INTERVAL = 3000
176
+
177
+ const badgeElement = document.getElementById("gh-badge")
178
+ const iconElement = document.getElementById("gh-icon")
179
+ const titleElement = document.getElementById("gh-title")
180
+ const detailElement = document.getElementById("gh-detail")
181
+ const openButton = document.getElementById("gh-open")
182
+ const loginButton = document.getElementById("gh-login")
183
+ const doneLink = document.getElementById("gh-done")
184
+ const codeElement = document.getElementById("gh-code")
185
+ const codeValueElement = document.getElementById("gh-code-value")
186
+ const codeHrefElement = document.getElementById("gh-code-href")
187
+ const errorElement = document.getElementById("gh-error")
188
+
189
+ let loginUrl = null
190
+ let pollTimer = null
191
+ let polling = false // one status request at a time: each one may run git on the server
192
+
193
+ function setState({ badge, icon, title, detail, done = false }) {
194
+ if (badge) badgeElement.textContent = badge
195
+ if (icon) iconElement.className = icon
196
+ if (title) titleElement.textContent = title
197
+ if (detail) detailElement.textContent = detail
198
+ doneLink.classList.toggle("hidden", !done)
199
+ }
200
+
201
+ function setLoginLabel(label) {
202
+ const labelElement = loginButton.querySelector("span")
203
+ if (labelElement) labelElement.textContent = label
204
+ }
205
+
206
+ function hideCode() {
207
+ codeElement.classList.add("hidden")
208
+ codeValueElement.textContent = ""
209
+ loginUrl = null
210
+ }
211
+
212
+ function showError(message) {
213
+ stopPolling()
214
+ hideCode()
215
+ errorElement.textContent = message
216
+ errorElement.classList.remove("hidden")
217
+ setLoginLabel("Try Again")
218
+ loginButton.classList.remove("hidden")
219
+ setState({
220
+ badge: "Needs attention",
221
+ icon: "fa-solid fa-triangle-exclamation",
222
+ title: "Login needs attention",
223
+ detail: "Pinokio could not complete the GitHub login."
224
+ })
225
+ }
226
+
227
+ function clearError() {
228
+ errorElement.textContent = ""
229
+ errorElement.classList.add("hidden")
230
+ loginButton.classList.add("hidden")
231
+ }
232
+
233
+ function stopPolling() {
234
+ if (pollTimer) {
235
+ clearInterval(pollTimer)
236
+ pollTimer = null
237
+ }
238
+ }
239
+
240
+ // A login is saved. If a GH_TOKEN in the environment wins over it, say so.
241
+ function showConnected(status) {
242
+ stopPolling()
243
+ clearError()
244
+ hideCode()
245
+ const who = status.login ? ` as ${status.login}` : ""
246
+ setState({
247
+ badge: status.source === "pinokio" ? "Connected" : "Overridden",
248
+ icon: status.source === "pinokio" ? "fa-solid fa-circle-check" : "fa-solid fa-triangle-exclamation",
249
+ title: status.source === "pinokio" ? "GitHub connected" : "Pinokio login saved, but not in use",
250
+ detail: status.source === "pinokio"
251
+ ? `Pinokio is signed in${who}. Git and gh in Pinokio shells use this login.`
252
+ : `Pinokio saved the login${who}, but a GH_TOKEN in your environment overrides it for git and gh in Pinokio shells.`,
253
+ done: true
254
+ })
255
+ }
256
+
257
+ function showWaiting(session) {
258
+ loginUrl = session.verification_uri || "https://github.com/login/device"
259
+ codeHrefElement.href = loginUrl
260
+ codeHrefElement.textContent = loginUrl.replace(/^https?:\/\//, "")
261
+ codeValueElement.textContent = session.user_code || ""
262
+ codeElement.classList.remove("hidden")
263
+ setState({
264
+ badge: "Waiting",
265
+ icon: "fa-solid fa-circle-notch fa-spin",
266
+ title: "Authorize GitHub",
267
+ detail: "Use the button to copy the code and open GitHub, then approve the login there. Keep this page open while Pinokio waits."
268
+ })
269
+ }
270
+
271
+ async function postJSON(url, body = {}) {
272
+ const res = await fetch(url, {
273
+ method: "POST",
274
+ headers: { "Content-Type": "application/json" },
275
+ body: JSON.stringify(body)
276
+ })
277
+ return res.json()
278
+ }
279
+
280
+ async function fetchStatus() {
281
+ return fetch(STATUS_URL, { cache: "no-store" }).then((res) => res.json())
282
+ }
283
+
284
+ async function pollLoginStatus() {
285
+ if (polling) return
286
+ polling = true
287
+ let status
288
+ try {
289
+ status = await fetchStatus()
290
+ } catch (_) {
291
+ return
292
+ } finally {
293
+ polling = false
294
+ }
295
+ if (status.saved) {
296
+ showConnected(status)
297
+ return
298
+ }
299
+ const session = status.session
300
+ if (session && session.status === "error") {
301
+ showError(session.error || "GitHub login failed.")
302
+ }
303
+ }
304
+
305
+ function startPolling() {
306
+ stopPolling()
307
+ pollTimer = setInterval(pollLoginStatus, POLL_INTERVAL)
308
+ }
309
+
310
+ async function copyAndOpen() {
311
+ if (!loginUrl) return
312
+ let copied = false
313
+ const value = codeValueElement.textContent.trim()
314
+ if (value) {
315
+ try {
316
+ await navigator.clipboard.writeText(value)
317
+ copied = true
318
+ } catch (_) {}
319
+ }
320
+ // The Electron app opens the system browser; a browser client opens its own tab.
321
+ if (document.body.dataset.agent === "electron") {
322
+ await fetch("/pinokio/open", {
323
+ method: "POST",
324
+ headers: { "Content-Type": "application/json" },
325
+ body: JSON.stringify({ url: loginUrl, surface: "browser" })
326
+ }).catch(() => {})
327
+ } else {
328
+ window.open(loginUrl, "_blank", "noopener")
329
+ }
330
+ openButton.querySelector("span").textContent = copied ? "Copied and Opened" : "Opened"
331
+ setTimeout(() => {
332
+ openButton.querySelector("span").textContent = "Copy and Open GitHub"
333
+ }, 1500)
334
+ }
335
+
336
+ async function startLogin() {
337
+ stopPolling()
338
+ clearError()
339
+ hideCode()
340
+ setState({
341
+ badge: "Preparing",
342
+ icon: "fa-solid fa-circle-notch fa-spin",
343
+ title: "Preparing GitHub",
344
+ detail: "Pinokio is requesting a GitHub device code."
345
+ })
346
+
347
+ let response
348
+ try {
349
+ response = await postJSON(START_URL)
350
+ } catch (error) {
351
+ showError(error.message)
352
+ return
353
+ }
354
+ if (response.error || response.status === "error") {
355
+ showError(response.error || "Unknown GitHub login error.")
356
+ return
357
+ }
358
+ if (!response.login || !response.login.user_code) {
359
+ showError("GitHub did not return a device code.")
360
+ return
361
+ }
362
+ showWaiting(response.login)
363
+ startPolling()
364
+ }
365
+
366
+ openButton.addEventListener("click", copyAndOpen)
367
+ loginButton.addEventListener("click", startLogin)
368
+
369
+ window.addEventListener("load", async () => {
370
+ try {
371
+ const status = await fetchStatus()
372
+ if (status.saved) {
373
+ showConnected(status)
374
+ return
375
+ }
376
+ if (status.session && status.session.status === "pending") {
377
+ clearError()
378
+ showWaiting(status.session)
379
+ startPolling()
380
+ return
381
+ }
382
+ startLogin()
383
+ } catch (error) {
384
+ showError(error.message)
385
+ }
386
+ })
387
+ </script>
388
+ <%- include('partials/app_common_scripts') %>
389
+ </body>
390
+ </html>