← Files Flows by plugin.spaceARCHIVED FILE

lib/cloud-proxy.mjs

12.3 KB · Nov 30, 2026 · 00:17 UTC

↓ Download file

import { createHash, randomBytes } from 'node:crypto';
const random = () => randomBytes(32).toString('base64url');
const pattern = /^[A-Za-z0-9_-]{43}$/;
const cookie = (request, name) => request.headers.cookie?.split(';').map(value => value.trim()).find(value => value.startsWith(`${name}=`))?.slice(name.length + 1);
function json(response, status, value) { response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' }); response.end(JSON.stringify(value)); }
async function bounded(response, limit = 4.5 * 1024 * 1024) {
  let bytes = 0; const chunks = [];
  for await (const chunk of response.body || []) { bytes += chunk.length; if (bytes > limit) throw new Error('Account response exceeds the supported size.'); chunks.push(chunk); }
  return Buffer.concat(chunks);
}
export function createCloudProxy(address, fetcher = fetch, localAccess) {
  const base = address ? new URL(address) : null;
  if (base && (base.username || base.password || base.search || base.hash || base.pathname !== '/' || (base.protocol !== 'https:' && !(base.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(base.hostname))))) throw new Error('FLOWS_CLOUD_URL must be an HTTPS origin (or a local development origin).');
  const sessions = new Map(); const pending = new Map();
  let loginGeneration = 0;
  // Callbacks finish one at a time: a stale attempt is detected and cleaned up
  // before a newer attempt can write its local receipt, so cleanup never
  // touches a newer identity.
  let callbacks = Promise.resolve();
  const serialized = action => { const next = callbacks.then(action, action); callbacks = next.catch(() => {}); return next; };
  const prune = () => { for (const map of [sessions, pending]) for (const [key, value] of map) if (value.expires <= Date.now()) map.delete(key); };
  async function upstream(path, token, body) {
    const response = await fetcher(new URL(path, base), { method: body === undefined ? 'GET' : 'POST', headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) }, body: body === undefined ? undefined : JSON.stringify(body), redirect: 'error', signal: AbortSignal.timeout(20000) });
    const value = JSON.parse((await bounded(response, 16384)).toString('utf8'));
    if (!response.ok) throw Object.assign(new Error(value.error || 'Could not connect your account.'), { status: response.status });
    return value;
  }
  return {
    origin: base?.origin,
    async handle(request, response) {
      if (!base) return json(response, 503, { error: 'Account storage is not configured yet.' });
      prune();
      const url = new URL(request.url, 'http://localhost');
      const port = response.socket.localPort;
      const sessionCookie = `flows-session-${port}`, loginCookie = `flows-login-${port}`;
      const id = cookie(request, sessionCookie), session = sessions.get(id);
      const changed = () => json(response, 409, { error: 'Your account connection changed. Refresh Flows and review the connected account before trying again.', code: 'account_changed' });
      const matches = () => sessions.get(id) === session;
      const expectedAccount = request.headers['x-flows-account'], expectedConnection = request.headers['x-flows-connection'];
      const bound = () => session && expectedAccount === session.accountId && expectedConnection === session.binding;
      const clearSession = async () => { if (session && !matches()) return; if (session?.connectionId) await localAccess?.disconnect(session.connectionId); sessions.delete(id); response.setHeader('Set-Cookie', `${sessionCookie}=; HttpOnly; SameSite=Strict; Path=/api; Max-Age=0`); };
      if (url.pathname === '/api/auth/connect' && request.method === 'POST') {
        if (request.headers.host !== `127.0.0.1:${port}`) return json(response, 400, { error: 'Open the viewer at 127.0.0.1 before connecting your account.' });
        if (pending.size >= 1000 || sessions.size >= 1000) return json(response, 503, { error: 'Too many connections. Restart this viewer and try again.' });
        pending.delete(cookie(request, loginCookie));
        const login = random(), state = random(), verifier = random();
        const redirect = `http://127.0.0.1:${port}/api/auth/callback`;
        pending.set(login, { generation: ++loginGeneration, state, verifier, redirect, expires: Date.now() + 5 * 60000 });
        response.setHeader('Set-Cookie', `${loginCookie}=${login}; HttpOnly; SameSite=Lax; Path=/api/auth; Max-Age=300`);
        const loginUrl = new URL('/plugin-login', base);
        loginUrl.searchParams.set('redirect_uri', redirect); loginUrl.searchParams.set('state', state);
        loginUrl.searchParams.set('code_challenge', createHash('sha256').update(verifier).digest('base64url'));
        return json(response, 200, { url: loginUrl.href });
      }
      if (url.pathname === '/api/auth/callback' && request.method === 'GET') {
        const login = cookie(request, loginCookie), attempt = pending.get(login);
        if (!attempt || url.searchParams.get('state') !== attempt.state || !pattern.test(url.searchParams.get('code') || '') || url.searchParams.getAll('state').length !== 1 || url.searchParams.getAll('code').length !== 1) return json(response, 400, { error: 'This sign-in request expired or belongs to a different browser. Start again from Flows.' });
        pending.delete(login);
        const outcome = await serialized(async () => {
          let grant, connectionId;
          const stale = () => attempt.generation !== loginGeneration;
          try {
            grant = await upstream('/api/plugin-auth/token', undefined, { code: url.searchParams.get('code'), code_verifier: attempt.verifier, redirect_uri: attempt.redirect });
            if (!pattern.test(grant.access_token || '') || grant.token_type !== 'Bearer' || !Number.isFinite(grant.expires_in) || grant.expires_in <= 0 || grant.user?.emailVerified !== true || typeof grant.user?.id !== 'string' || !grant.user.id || grant.user.id.length > 500) throw new Error('Invalid account connection response.');
            if (stale()) throw new Error('A newer sign-in has started or the account was disconnected.');
            connectionId = await localAccess?.connect(grant.user.id);
            try { if (localAccess) await localAccess.verify(connectionId, grant.user.id, await upstream('/api/cloud/entitlement', grant.access_token)); }
            catch { /* Connecting still works on older/offline entitlement services; Free is the safe default. */ }
            if (stale()) throw new Error('A newer sign-in has started or the account was disconnected.');
            const localId = random();
            // Only the local Node process receives the bearer token. Browser JavaScript
            // sees an opaque HttpOnly cookie and the public account identity.
            sessions.delete(id);
            sessions.set(localId, { connectionId, binding: random(), accountId: grant.user.id, token: grant.access_token, expires: Date.now() + Math.min(grant.expires_in, 86400) * 1000 });
            return { localId };
          } catch {
            // Undo only this abandoned attempt: its receipt (a no-op once another
            // connection owns the receipt) and its remote token.
            if (connectionId) await localAccess?.disconnect(connectionId).catch(() => {});
            if (pattern.test(grant?.access_token || '')) await upstream('/api/plugin-auth/revoke', grant.access_token, {}).catch(() => {});
            // The browser's still-valid earlier connection keeps its local receipt.
            if (connectionId && session && sessions.get(id) === session && localAccess) {
              try {
                session.connectionId = await localAccess.connect(session.accountId);
                await localAccess.verify(session.connectionId, session.accountId, await upstream('/api/cloud/entitlement', session.token));
              } catch { /* The next session check refreshes or clears it. */ }
            }
            return {};
          }
        });
        if (!outcome.localId) return json(response, 401, { error: 'Could not complete the connection. Start again from Flows.' });
        response.setHeader('Set-Cookie', [`${sessionCookie}=${outcome.localId}; HttpOnly; SameSite=Strict; Path=/api; Max-Age=86400`, `${loginCookie}=; HttpOnly; SameSite=Lax; Path=/api/auth; Max-Age=0`]);
        response.writeHead(303, { Location: '/auth/connected', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' }); response.end(); return;
      }
      if (url.pathname === '/api/auth/get-session' && request.method === 'GET') {
        if (!session) return json(response, 200, null);
        try {
          const value = await upstream('/api/plugin-auth/session', session.token);
          if (value.user?.id !== session.accountId || value.user?.emailVerified !== true) { await clearSession(); return json(response, 200, null); }
          try { if (localAccess) await localAccess.verify(session.connectionId, session.accountId, await upstream('/api/cloud/entitlement', session.token)); }
          catch (error) { if ([401, 403].includes(error.status)) await localAccess?.disconnect(session.connectionId); }
          if (!matches()) return changed();
          return json(response, 200, { user: { ...value.user, connection: session.binding } });
        }
        catch (error) { if ([401, 403].includes(error.status)) { await clearSession(); return json(response, 200, null); } return json(response, 503, { error: 'Account connection is temporarily unavailable.' }); }
      }
      if (url.pathname === '/api/auth/sign-out' && request.method === 'POST') {
        if (session && !bound()) return changed();
        // Cancel sign-ins before anything asynchronous: a callback still in
        // flight becomes stale and is undone (its grant revoked) instead of
        // completing after this disconnect.
        loginGeneration++; pending.clear();
        // Ordered after any in-flight callback, and before any callback for a
        // sign-in started later, so neither can survive or be wiped by this cleanup.
        const done = await serialized(async () => {
          // Keep the handle on a network failure so a user can retry revocation.
          if (session) { try { await upstream('/api/plugin-auth/revoke', session.token, {}); } catch { return false; } }
          else await localAccess?.disconnect();
          await clearSession(); return true;
        });
        return done ? json(response, 200, { success: true }) : json(response, 503, { error: 'Could not disconnect. Please try again.' });
      }
      // Credential entry, provider auth and billing are never proxied by a plugin.
      if (!/^\/api\/cloud\//.test(url.pathname) || !['GET', 'HEAD', 'POST', 'DELETE'].includes(request.method)) return json(response, 404, { error: 'Not found.' });
      if (!session) return json(response, 401, { error: 'Sign in on plugin.space to connect your account.' });
      if ((expectedAccount || expectedConnection || !['GET', 'HEAD'].includes(request.method)) && !bound()) return changed();
      let bytes = 0; const chunks = [];
      for await (const chunk of request) { bytes += chunk.length; if (bytes > 4 * 1024 * 1024) return json(response, 413, { error: 'Cloud snapshot exceeds 4 MB. Use smaller screenshot captures.' }); chunks.push(chunk); }
      try {
        if (!matches()) return changed();
        const headers = { Origin: base.origin, Authorization: `Bearer ${session.token}`, 'X-Flows-Account': session.accountId };
        if (request.headers['content-type']) headers['Content-Type'] = request.headers['content-type'];
        const remote = await fetcher(new URL(`${url.pathname}${url.search}`, base), { method: request.method, headers, body: ['GET', 'HEAD'].includes(request.method) ? undefined : Buffer.concat(chunks), redirect: 'error', signal: AbortSignal.timeout(20000) });
        const content = await bounded(remote);
        if (!matches()) return changed();
        if (remote.status === 401) await clearSession();
        const retryAfter = remote.headers.get('retry-after');
        response.writeHead(remote.status, { 'Content-Type': remote.headers.get('content-type') || 'application/json', 'Cache-Control': 'no-store', ...(retryAfter && /^\d{1,6}$/.test(retryAfter) ? { 'Retry-After': retryAfter } : {}) });
        response.end(request.method === 'HEAD' ? undefined : content);
      } catch { return json(response, 502, { error: 'Account storage is temporarily unavailable.' }); }
    },
  };
}

SHA-256: e94e765dc62e7151078ce847bd3125774843eabd5eea071baf2392e8ab0f89b5