import { startOAuth, getParState, clearParState, handleOAuthCallback, revokeSession } from '../lib/atproto-oauth.js'; import { saveHashForLogin, log } from '../main.js'; import { OAUTH_SCOPE_FULL } from '../generated/oauth-scope.js'; const OAUTH_QR_NSID = 'com.fedfork.atprotoOauthQR'; export class DkaOauthTransfer extends HTMLElement { connectedCallback() { this._state = 'init'; this._cliDid = this.getAttribute('cli-did') || ''; this._nonce = this.getAttribute('nonce') || ''; // Check if returning from OAuth redirect (code + state in URL query params) const qp = new URLSearchParams(window.location.search); const code = qp.get('code'); const iss = qp.get('iss'); const stateParam = qp.get('state'); if (code && stateParam && iss) { // State format: randomHex|cliDid|nonce — recover if sessionStorage lost const parts = stateParam.split('|'); if (parts.length === 3) { this._cliDid = parts[1]; this._nonce = parts[2]; } this._handleCallback(code, stateParam); return; } this.renderInit(); this._start(); } renderInit() { this.innerHTML = `

Session Transfer

Log in with your AT Protocol account to transfer your session back to the CLI that showed you the QR code.

CLI: ${this._escape(this._cliDid)}

`; } renderLogin() { this.innerHTML = `

Session Transfer

Login with the Atmosphere

Enter your handle to authenticate and transfer your session.

If you're a Bluesky user, you already have an Atmosphere account.

`; const doRedirect = async (handle) => { const btn = this.querySelector('#oauth-transfer-submit'); if (btn) { btn.setAttribute('aria-busy', 'true'); btn.textContent = 'Redirecting to PDS…'; } const errEl = this.querySelector('#oauth-transfer-error'); if (errEl) errEl.textContent = ''; try { // Save hash for restoration after OAuth redirect saveHashForLogin(); const clientId = `https://${window.location.host}/oauth-client-metadata.json`; const redirectUri = (window.location.origin + window.location.pathname).replace(/\/+$/, ''); const scope = OAUTH_SCOPE_FULL; const { authUrl } = await startOAuth(handle, clientId, redirectUri, scope, `${this._cliDid}|${this._nonce}`); log('info', 'oauth-transfer', 'redirecting', { handle, authUrl: authUrl.slice(0, 80) }); window.location.href = authUrl; } catch (err) { log('error', 'oauth-transfer', 'startOAuthError', { error: String(err) }); if (btn) { btn.removeAttribute('aria-busy'); btn.textContent = 'Login & Transfer'; } if (errEl) errEl.textContent = `Login error: ${err}`; } }; this.querySelector('#oauth-transfer-login-form').addEventListener('submit', (e) => { e.preventDefault(); doRedirect(e.target.username.value); }); this.querySelector('#oauth-transfer-bsky-btn').addEventListener('click', () => { doRedirect('https://bsky.social'); }); } renderTransferring() { this.innerHTML = `

Transferring session…

Sending your session back to the CLI.

`; } renderDone(handle) { // Mark parent so _onHashChange won't overwrite this success state. const app = this.closest('dka-app'); if (app) app._transferDone = true; this.innerHTML = `
✓

Session transferred

Your session (@${this._escape(handle)}) has been sent to ${this._escape(this._cliDid)}. You can close this page and return to your terminal.

`; } renderError(msg) { const app = this.closest('dka-app'); if (app) app._transferDone = true; this.innerHTML = `

Transfer failed

${this._escape(msg)}

`; } async _linkStatus() { const res = await fetch(`/xrpc/${OAUTH_QR_NSID}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cliDid: this._cliDid, nonce: this._nonce }), }); const body = await res.json().catch(() => ({})); return { ok: res.ok, error: body.error || '', message: body.message || `backend error: ${res.status}` }; } async _checkLink(retryUnknown) { for (let attempt = 0; ; attempt++) { let status; try { status = await this._linkStatus(); } catch (err) { log('error', 'oauth-transfer', 'linkStatusError', { error: String(err) }); return 'Could not reach qr.fedfork.com to check this sign-in link. Check your connection and scan the QR code again.'; } if (status.ok) return null; if (retryUnknown && status.error === 'LinkUnknown' && attempt < 4) { await new Promise((r) => setTimeout(r, 2000)); continue; } log('error', 'oauth-transfer', 'linkRejected', { error: status.error }); return status.message; } } _reject(msg) { clearParState(); this._state = 'rejected'; this.renderError(msg); } async _start() { const problem = await this._checkLink(true); if (problem) { this._reject(problem); return; } this._state = 'login'; this.renderLogin(); } async _revoke(session) { try { const revoked = await revokeSession(session); log('info', 'oauth-transfer', 'sessionRevoked', { revoked }); } catch (err) { log('error', 'oauth-transfer', 'revokeError', { error: String(err) }); } } async _handleCallback(code, stateParam) { this._state = 'transferring'; this.renderTransferring(); const par = getParState(); if (par && par.state === stateParam) { const problem = await this._checkLink(false); if (problem) { this._reject(problem); return; } } let session; try { session = await handleOAuthCallback(code, stateParam); } catch (err) { log('error', 'oauth-transfer', 'callbackError', { error: String(err) }); this._handleError(String(err)); return; } if (session.stateSuffix) { const parts = session.stateSuffix.split('|'); if (parts.length === 2) { this._cliDid = parts[0]; this._nonce = parts[1]; } } log('info', 'oauth-transfer', 'callbackComplete', { handle: session.handle, did: session.userDid }); let res; try { res = await fetch(`/xrpc/${OAUTH_QR_NSID}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ cliDid: this._cliDid, nonce: this._nonce, accessJwt: session.accessJwt, refreshJwt: session.refreshJwt, userDid: session.userDid, handle: session.handle, pds: session.pds, dpopPublicJwk: session.dpopPublicJwk, dpopPrivateJwk: session.dpopPrivateJwk, scope: session.scope, }), }); } catch (err) { log('error', 'oauth-transfer', 'transferError', { error: String(err) }); await this._revoke(session); this._reject('Could not reach qr.fedfork.com to finish the transfer. Scan a new QR code from the device.'); return; } const reply = await res.json().catch(() => ({})); if (!res.ok) { log('error', 'oauth-transfer', 'transferRejected', { error: reply.error || res.status }); await this._revoke(session); this._reject(reply.message || `backend error: ${res.status}`); return; } if (reply.did !== session.userDid) { log('error', 'oauth-transfer', 'transferDidMismatch', {}); await this._revoke(session); this._reject('The transfer could not be confirmed for your account. Scan a new QR code from the device.'); return; } log('info', 'oauth-transfer', 'sessionTransferred', { cliDid: this._cliDid, handle: session.handle }); this.renderDone(session.handle); } _handleError(msg) { log('error', 'oauth-transfer', 'error', { msg }); clearParState(); // Show login form so user can start fresh. this._state = 'login'; this.renderLogin(); } _escape(s) { const el = document.createElement('span'); el.textContent = String(s); return el.innerHTML; } } if (!customElements.get('dka-oauth-transfer')) { customElements.define('dka-oauth-transfer', DkaOauthTransfer); }