Spaces:
Sleeping
Sleeping
File size: 11,058 Bytes
f6266b9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 | /**
* Windsurf direct login โ Firebase auth + Codeium registration.
* Supports proxy tunneling and fingerprint randomization.
*/
import http from 'http';
import https from 'https';
import { log } from '../config.js';
const FIREBASE_API_KEY = 'AIzaSyDsOl-1XpT5err0Tcnx8FFod1H8gVGIycY';
const FIREBASE_AUTH_URL = `https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${FIREBASE_API_KEY}`;
const FIREBASE_REFRESH_URL = `https://securetoken.googleapis.com/v1/token?key=${FIREBASE_API_KEY}`;
const CODEIUM_REGISTER_URL = 'https://api.codeium.com/register_user/';
// โโโ Fingerprint randomization โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
const OS_VERSIONS = [
'Windows NT 10.0; Win64; x64',
'Windows NT 10.0; WOW64',
'Macintosh; Intel Mac OS X 10_15_7',
'Macintosh; Intel Mac OS X 11_6_0',
'Macintosh; Intel Mac OS X 12_3_1',
'Macintosh; Intel Mac OS X 13_4_1',
'Macintosh; Intel Mac OS X 14_2_1',
'X11; Linux x86_64',
'X11; Ubuntu; Linux x86_64',
];
const CHROME_VERSIONS = [
'120.0.0.0', '121.0.0.0', '122.0.0.0', '123.0.0.0', '124.0.0.0',
'125.0.0.0', '126.0.0.0', '127.0.0.0', '128.0.0.0', '129.0.0.0',
'130.0.0.0', '131.0.0.0', '132.0.0.0', '133.0.0.0', '134.0.0.0',
];
const ACCEPT_LANGUAGES = [
'en-US,en;q=0.9', 'en-GB,en;q=0.9', 'zh-TW,zh;q=0.9,en;q=0.8',
'zh-CN,zh;q=0.9,en;q=0.8', 'ja,en-US;q=0.9,en;q=0.8',
'ko,en-US;q=0.9,en;q=0.8', 'de,en-US;q=0.9,en;q=0.8',
'fr,en-US;q=0.9,en;q=0.8', 'es,en-US;q=0.9,en;q=0.8',
'pt-BR,pt;q=0.9,en;q=0.8',
];
function pick(arr) { return arr[Math.floor(Math.random() * arr.length)]; }
function generateFingerprint() {
const os = pick(OS_VERSIONS);
const chromeVer = pick(CHROME_VERSIONS);
const major = chromeVer.split('.')[0];
const ua = `Mozilla/5.0 (${os}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chromeVer} Safari/537.36`;
return {
'User-Agent': ua,
'Accept-Language': pick(ACCEPT_LANGUAGES),
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'identity',
'sec-ch-ua': `"Chromium";v="${major}", "Google Chrome";v="${major}", "Not-A.Brand";v="99"`,
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': os.includes('Windows') ? '"Windows"' : os.includes('Mac') ? '"macOS"' : '"Linux"',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'cross-site',
'Origin': 'https://windsurf.com',
'Referer': 'https://windsurf.com/',
};
}
// โโโ Proxy tunnel (HTTP CONNECT) โโโโโโโโโโโโโโโโโโโโโโโโโโ
function createProxyTunnel(proxy, targetHost, targetPort) {
return new Promise((resolve, reject) => {
const proxyHost = proxy.host.replace(/:\d+$/, '');
const proxyPort = proxy.port || 8080;
const authHeader = proxy.username
? `Proxy-Authorization: Basic ${Buffer.from(`${proxy.username}:${proxy.password || ''}`).toString('base64')}\r\n`
: '';
const connectReq = http.request({
host: proxyHost,
port: proxyPort,
method: 'CONNECT',
path: `${targetHost}:${targetPort}`,
headers: {
Host: `${targetHost}:${targetPort}`,
...(proxy.username ? { 'Proxy-Authorization': `Basic ${Buffer.from(`${proxy.username}:${proxy.password || ''}`).toString('base64')}` } : {}),
},
});
connectReq.on('connect', (res, socket) => {
if (res.statusCode === 200) {
resolve(socket);
} else {
socket.destroy();
reject(new Error(`Proxy CONNECT failed: ${res.statusCode}`));
}
});
connectReq.on('error', (err) => reject(new Error(`Proxy connection error: ${err.message}`)));
connectReq.setTimeout(15000, () => { connectReq.destroy(); reject(new Error('Proxy connection timeout')); });
connectReq.end();
});
}
// โโโ HTTPS request with optional proxy โโโโโโโโโโโโโโโโโโโโ
function httpsRequest(url, opts, postData, proxy) {
return new Promise(async (resolve, reject) => {
const parsed = new URL(url);
const requestOpts = {
hostname: parsed.hostname,
port: 443,
path: parsed.pathname + parsed.search,
method: opts.method || 'POST',
headers: opts.headers || {},
};
const handleResponse = (res) => {
const bufs = [];
res.on('data', d => bufs.push(d));
res.on('end', () => {
const raw = Buffer.concat(bufs).toString('utf8');
try {
resolve({ status: res.statusCode, data: JSON.parse(raw) });
} catch {
reject(new Error(`Parse error (status ${res.statusCode}, encoding ${res.headers['content-encoding'] || 'identity'}): ${raw.slice(0, 200)}`));
}
});
res.on('error', reject);
};
try {
let req;
if (proxy && proxy.host) {
const socket = await createProxyTunnel(proxy, parsed.hostname, 443);
requestOpts.socket = socket;
requestOpts.agent = false;
req = https.request(requestOpts, handleResponse);
} else {
req = https.request(requestOpts, handleResponse);
}
req.on('error', (err) => reject(new Error(`Request error: ${err.message}`)));
req.setTimeout(30000, () => { req.destroy(); reject(new Error('Request timeout')); });
if (postData) req.write(postData);
req.end();
} catch (err) {
reject(err);
}
});
}
// โโโ Login flow โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/**
* Full Windsurf login: Firebase auth โ Codeium register โ API key.
* @param {string} email
* @param {string} password
* @param {object} [proxy] - { host, port, username, password }
* @returns {{ apiKey, name, email, idToken }}
*/
export async function windsurfLogin(email, password, proxy = null) {
const fingerprint = generateFingerprint();
log.info(`Windsurf login: ${email} fp=${fingerprint['User-Agent'].slice(0, 40)}... proxy=${proxy?.host || 'none'}`);
// Step 1: Firebase sign in
const firebaseBody = JSON.stringify({
email,
password,
returnSecureToken: true,
});
const fbHeaders = {
...fingerprint,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(firebaseBody),
};
const fbRes = await httpsRequest(FIREBASE_AUTH_URL, { method: 'POST', headers: fbHeaders }, firebaseBody, proxy);
if (fbRes.data.error) {
const msg = fbRes.data.error.message || 'Unknown Firebase error';
const oauthHint = '่ฅไฝ ็จ Google/GitHub ๆณจๅ็ Windsurf ่ดฆๅท ๆญคๅคๅฏ็ ็ปๅฝไธ้็จ ่ฏท็จ้กต้ข้กถ้จ็ Google / GitHub ็ปๅฝๆ้ฎ ๆ่ฎฟ้ฎ https://windsurf.com/show-auth-token ๅคๅถ Auth Token ๅๅจใ่ดฆๅท็ฎก็ใ้กตๆๅจๆทปๅ ';
const friendly = {
'EMAIL_NOT_FOUND': `่ฏฅ้ฎ็ฎฑๆชๆณจๅ้ฎ็ฎฑๅฏ็ ็ปๅฝๆนๅผ๏ผ${oauthHint}๏ผ`,
'INVALID_PASSWORD': `ๅฏ็ ้่ฏฏ๏ผ${oauthHint}๏ผ`,
'INVALID_LOGIN_CREDENTIALS': `้ฎ็ฎฑๆๅฏ็ ้่ฏฏ๏ผ${oauthHint}๏ผ`,
'USER_DISABLED': '่ดฆๅทๅทฒ่ขซๅ็จ',
'TOO_MANY_ATTEMPTS_TRY_LATER': 'ๅฐ่ฏๅคชๅคๆฌก ่ฏท็จๅๅ่ฏ',
'INVALID_EMAIL': '้ฎ็ฎฑๆ ผๅผ้่ฏฏ',
}[msg] || msg;
const err = new Error(`Firebase ็ปๅ
ฅๅคฑ่ดฅ: ${friendly}`);
err.firebaseCode = msg;
err.isAuthFail = ['EMAIL_NOT_FOUND', 'INVALID_PASSWORD', 'INVALID_LOGIN_CREDENTIALS'].includes(msg);
throw err;
}
const idToken = fbRes.data.idToken;
if (!idToken) throw new Error('Firebase ๅๆ็ผบๅฐ idToken');
log.info(`Firebase login OK: ${email}, UID=${fbRes.data.localId}`);
// Step 2: Register with Codeium to get API key
const regBody = JSON.stringify({ firebase_id_token: idToken });
const regHeaders = {
...fingerprint,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(regBody),
};
const regRes = await httpsRequest(CODEIUM_REGISTER_URL, { method: 'POST', headers: regHeaders }, regBody, proxy);
if (regRes.status >= 400 || !regRes.data.api_key) {
throw new Error(`Codeium ่จปๅๅคฑๆ: ${JSON.stringify(regRes.data).slice(0, 200)}`);
}
log.info(`Codeium register OK: ${email} โ key=${regRes.data.api_key.slice(0, 12)}...`);
return {
apiKey: regRes.data.api_key,
name: regRes.data.name || email,
email,
idToken,
refreshToken: fbRes.data.refreshToken || '',
apiServerUrl: regRes.data.api_server_url || '',
};
}
/**
* Refresh a Firebase ID token using a stored refresh token.
* Returns a new { idToken, refreshToken, expiresIn } or throws.
*
* @param {string} refreshToken
* @param {object} [proxy]
* @returns {Promise<{idToken: string, refreshToken: string, expiresIn: number}>}
*/
export async function refreshFirebaseToken(refreshToken, proxy = null) {
if (!refreshToken) throw new Error('No refresh token available');
const postBody = `grant_type=refresh_token&refresh_token=${encodeURIComponent(refreshToken)}`;
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postBody),
'Referer': 'https://windsurf.com/',
'Origin': 'https://windsurf.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0.0.0 Safari/537.36',
};
const res = await httpsRequest(FIREBASE_REFRESH_URL, { method: 'POST', headers }, postBody, proxy);
if (res.data?.error) {
const msg = res.data.error.message || res.data.error.code || 'Unknown error';
throw new Error(`Firebase token refresh failed: ${msg}`);
}
const newIdToken = res.data?.id_token || res.data?.idToken;
const newRefreshToken = res.data?.refresh_token || res.data?.refreshToken || refreshToken;
const expiresIn = parseInt(res.data?.expires_in || res.data?.expiresIn || '3600', 10);
if (!newIdToken) {
throw new Error(`Firebase token refresh: no idToken in response: ${JSON.stringify(res.data).slice(0, 200)}`);
}
log.info(`Firebase token refreshed, expires in ${expiresIn}s`);
return { idToken: newIdToken, refreshToken: newRefreshToken, expiresIn };
}
/**
* Re-register with Codeium using a refreshed Firebase token.
* Returns a fresh API key (may be the same key if unchanged).
*
* @param {string} idToken - fresh Firebase ID token
* @param {object} [proxy]
* @returns {Promise<{apiKey: string, name: string}>}
*/
export async function reRegisterWithCodeium(idToken, proxy = null) {
const fingerprint = generateFingerprint();
const regBody = JSON.stringify({ firebase_id_token: idToken });
const regHeaders = {
...fingerprint,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(regBody),
};
const regRes = await httpsRequest(CODEIUM_REGISTER_URL, { method: 'POST', headers: regHeaders }, regBody, proxy);
if (regRes.status >= 400 || !regRes.data.api_key) {
throw new Error(`Codeium re-registration failed: ${JSON.stringify(regRes.data).slice(0, 200)}`);
}
return {
apiKey: regRes.data.api_key,
name: regRes.data.name || '',
};
}
|