superbrain-server 1.0.24 → 1.0.26

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/payload/api.py +79 -13
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "superbrain-server",
3
- "version": "1.0.24",
3
+ "version": "1.0.26",
4
4
  "description": "1-Line Auto-Installer and Server Execution wrapper for SuperBrain",
5
5
  "main": "index.js",
6
6
  "bin": {
package/payload/api.py CHANGED
@@ -1494,8 +1494,9 @@ class ProviderKeyUpdate(BaseModel):
1494
1494
  api_key: str
1495
1495
 
1496
1496
  class InstagramCredentials(BaseModel):
1497
- username: str
1498
- password: str
1497
+ username: Optional[str] = None
1498
+ password: Optional[str] = None
1499
+ sessionid: Optional[str] = None
1499
1500
 
1500
1501
  def get_config_path(filename: str) -> Path:
1501
1502
  """Get path to config directory files."""
@@ -1548,16 +1549,36 @@ async def set_ai_provider_key(
1548
1549
  - provider: groq, gemini, or openrouter
1549
1550
  """
1550
1551
  from core.model_router import get_router
1552
+ import httpx
1551
1553
 
1552
1554
  valid_providers = ["groq", "gemini", "openrouter"]
1553
- if data.provider.lower() not in valid_providers:
1555
+ provider_slug = data.provider.lower()
1556
+ if provider_slug not in valid_providers:
1554
1557
  raise HTTPException(
1555
1558
  status_code=400,
1556
1559
  detail=f"Invalid provider. Must be one of: {', '.join(valid_providers)}"
1557
1560
  )
1558
1561
 
1559
1562
  if not data.api_key or len(data.api_key.strip()) < 5:
1560
- raise HTTPException(status_code=400, detail="Invalid API key")
1563
+ raise HTTPException(status_code=400, detail="Invalid API key format")
1564
+
1565
+ # Validate API key explicitly
1566
+ try:
1567
+ async with httpx.AsyncClient(timeout=10.0) as client:
1568
+ if provider_slug == "groq":
1569
+ resp = await client.get("https://api.groq.com/openai/v1/models", headers={"Authorization": f"Bearer {data.api_key.strip()}"})
1570
+ if resp.status_code != 200:
1571
+ raise HTTPException(status_code=401, detail="Invalid Groq API Key")
1572
+ elif provider_slug == "gemini":
1573
+ resp = await client.get(f"https://generativelanguage.googleapis.com/v1beta/models?key={data.api_key.strip()}")
1574
+ if resp.status_code != 200:
1575
+ raise HTTPException(status_code=401, detail="Invalid Gemini API Key")
1576
+ elif provider_slug == "openrouter":
1577
+ resp = await client.get("https://openrouter.ai/api/v1/auth/key", headers={"Authorization": f"Bearer {data.api_key.strip()}"})
1578
+ if resp.status_code != 200:
1579
+ raise HTTPException(status_code=401, detail="Invalid OpenRouter API Key")
1580
+ except httpx.RequestError as e:
1581
+ raise HTTPException(status_code=502, detail=f"Network error validating API key: {e}")
1561
1582
 
1562
1583
  router = get_router()
1563
1584
  success = router.set_api_key(data.provider.lower(), data.api_key.strip())
@@ -1630,11 +1651,56 @@ async def set_instagram_credentials(
1630
1651
  Set Instagram credentials.
1631
1652
  - Requires API authentication
1632
1653
  """
1633
- if not data.username or not data.password:
1634
- raise HTTPException(status_code=400, detail="Username and password required")
1654
+ sessionid = getattr(data, "sessionid", None)
1655
+
1656
+ if not sessionid and (not data.username or not data.password):
1657
+ raise HTTPException(status_code=400, detail="Either login (username + password) OR Session ID is required")
1658
+
1659
+ username_to_use = data.username or "session_user"
1635
1660
 
1636
1661
  api_keys_file = get_config_path(".api_keys")
1637
1662
 
1663
+ # Authenticate with Instagram first
1664
+ import instaloader
1665
+ import httpx
1666
+ import urllib.parse
1667
+
1668
+ L = instaloader.Instaloader()
1669
+ try:
1670
+ session_file = Path(__file__).parent / ".instaloader_session"
1671
+ if sessionid:
1672
+ # Decode if URL-encoded (common from browser)
1673
+ clean_session = urllib.parse.unquote(sessionid.strip())
1674
+
1675
+ # Fast HTTP verification before committing to instaloader
1676
+ # so we avoid slow retries and BadResponseException
1677
+ async with httpx.AsyncClient(timeout=15.0, follow_redirects=False) as client:
1678
+ verify_resp = await client.get("https://www.instagram.com/", cookies={"sessionid": clean_session})
1679
+ if verify_resp.status_code == 302:
1680
+ raise HTTPException(status_code=401, detail="Invalid or expired Session ID")
1681
+
1682
+ L.context._session.cookies.set("sessionid", clean_session, domain=".instagram.com")
1683
+ L.context.username = username_to_use
1684
+ else:
1685
+ L.login(data.username, data.password)
1686
+ username_to_use = data.username
1687
+
1688
+ L.save_session_to_file(str(session_file))
1689
+ logger.info(f"🍪 Instagram session successfully verified and saved for {username_to_use}")
1690
+ except HTTPException:
1691
+ raise
1692
+ except instaloader.exceptions.BadCredentialsException:
1693
+ raise HTTPException(status_code=401, detail="Invalid username or password")
1694
+ except instaloader.exceptions.TwoFactorAuthRequiredException:
1695
+ raise HTTPException(status_code=401, detail="Two-factor auth blocked login. Please use Session ID cookie instead.")
1696
+ except instaloader.exceptions.ConnectionException as e:
1697
+ error_msg = str(e).lower()
1698
+ if "checkpoint" in error_msg or "challenge" in error_msg:
1699
+ raise HTTPException(status_code=401, detail="Instagram Checkpoint block. Please use Session ID cookie instead.")
1700
+ raise HTTPException(status_code=400, detail=f"Instagram connection error: {e}")
1701
+ except Exception as e:
1702
+ raise HTTPException(status_code=500, detail=f"Failed to authenticate with Instagram: {e}")
1703
+
1638
1704
  # Read existing content
1639
1705
  lines = []
1640
1706
  username_found = False
@@ -1644,27 +1710,27 @@ async def set_instagram_credentials(
1644
1710
  with open(api_keys_file, "r") as f:
1645
1711
  for line in f:
1646
1712
  if line.startswith("INSTAGRAM_USERNAME="):
1647
- lines.append(f"INSTAGRAM_USERNAME={data.username}\n")
1713
+ lines.append(f"INSTAGRAM_USERNAME={username_to_use}\n")
1648
1714
  username_found = True
1649
1715
  elif line.startswith("INSTAGRAM_PASSWORD="):
1650
- lines.append(f"INSTAGRAM_PASSWORD={data.password}\n")
1716
+ lines.append(f"INSTAGRAM_PASSWORD={data.password}\n" if data.password else "INSTAGRAM_PASSWORD=\n")
1651
1717
  password_found = True
1652
1718
  else:
1653
1719
  lines.append(line)
1654
1720
 
1655
1721
  if not username_found:
1656
- lines.append(f"INSTAGRAM_USERNAME={data.username}\n")
1722
+ lines.append(f"INSTAGRAM_USERNAME={username_to_use}\n")
1657
1723
  if not password_found:
1658
- lines.append(f"INSTAGRAM_PASSWORD={data.password}\n")
1724
+ lines.append(f"INSTAGRAM_PASSWORD={data.password}\n" if data.password else "INSTAGRAM_PASSWORD=\n")
1659
1725
 
1660
1726
  with open(api_keys_file, "w") as f:
1661
1727
  f.writelines(lines)
1662
-
1663
- logger.info(f"📸 Instagram credentials updated for {data.username}")
1728
+
1729
+ logger.info(f"📸 Instagram credentials updated for {username_to_use}")
1664
1730
 
1665
1731
  return {
1666
1732
  "success": True,
1667
- "username": data.username,
1733
+ "username": username_to_use,
1668
1734
  "message": "Instagram credentials updated"
1669
1735
  }
1670
1736