()
| 138 | } |
| 139 | |
| 140 | export async function authenticate(): Promise<void> { |
| 141 | console.log("Starting Qwen authentication flow..."); |
| 142 | try { |
| 143 | const authManager = new QwenAuthManager(); |
| 144 | console.log("Checking for existing credentials..."); |
| 145 | const existingCredentials = await authManager.loadCredentials(); |
| 146 | if (existingCredentials && authManager.isTokenValid(existingCredentials)) { |
| 147 | console.log("\n✅ Valid credentials already exist!"); |
| 148 | console.log("Access token is still valid and will be used by the proxy server."); |
| 149 | console.log("\nYou can start the proxy server with: npm start"); |
| 150 | return; |
| 151 | } |
| 152 | |
| 153 | if (existingCredentials) { |
| 154 | console.log("Existing credentials found but they are expired or invalid."); |
| 155 | console.log("Attempting to refresh the access token..."); |
| 156 | try { |
| 157 | await authManager.refreshAccessToken(existingCredentials); |
| 158 | console.log("\n✅ Token refreshed successfully!"); |
| 159 | console.log("Access token has been updated and will be used by the proxy server."); |
| 160 | console.log("\nYou can start the proxy server with: npm start"); |
| 161 | return; |
| 162 | } catch (refreshError: any) { |
| 163 | console.log("Failed to refresh token:", refreshError.message); |
| 164 | console.log("Proceeding with new authentication flow..."); |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | console.log("\nInitiating device flow..."); |
| 169 | const deviceFlow = await authManager.initiateDeviceFlow(); |
| 170 | console.log("\n=== Qwen OAuth Device Authorization ==="); |
| 171 | console.log("Please visit the following URL to authenticate:"); |
| 172 | console.log(`\n${deviceFlow.verification_uri_complete}\n`); |
| 173 | console.log("Or scan the QR code below:"); |
| 174 | qrcode.generate(deviceFlow.verification_uri_complete, { small: true }, (qrCode: string) => { |
| 175 | console.log(qrCode); |
| 176 | }); |
| 177 | console.log("User code:", deviceFlow.user_code); |
| 178 | console.log("(Press Ctrl+C to cancel)"); |
| 179 | |
| 180 | try { |
| 181 | await open(deviceFlow.verification_uri_complete); |
| 182 | console.log("\nBrowser opened automatically. If not, please visit the URL above."); |
| 183 | } catch { |
| 184 | console.log("\nPlease visit the URL above in your browser to authenticate."); |
| 185 | } |
| 186 | |
| 187 | console.log("\nWaiting for authentication..."); |
| 188 | await authManager.pollForToken(deviceFlow.device_code, deviceFlow.code_verifier); |
| 189 | console.log("\n🎉 Authentication successful!"); |
| 190 | console.log("Access token saved to ~/.qwen/oauth_creds.json"); |
| 191 | console.log("\nYou can now start the proxy server with: npm start"); |
| 192 | } catch (error: any) { |
| 193 | console.error("Authentication failed:", error.message); |
| 194 | process.exit(1); |
| 195 | } |
| 196 | } |
| 197 |
no test coverage detected