oauth.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * Test helper for resolving API keys from ~/.pi/agent/auth.json
  3. *
  4. * Supports both API key and OAuth credentials.
  5. * OAuth tokens are automatically refreshed if expired and saved back to auth.json.
  6. */
  7. import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
  8. import { homedir } from "os";
  9. import { dirname, join } from "path";
  10. import { getOAuthApiKey } from "../src/utils/oauth/index.ts";
  11. import type { OAuthCredentials, OAuthProvider } from "../src/utils/oauth/types.ts";
  12. const AUTH_PATH = join(homedir(), ".pi", "agent", "auth.json");
  13. type ApiKeyCredential = {
  14. type: "api_key";
  15. key: string;
  16. };
  17. type OAuthCredentialEntry = {
  18. type: "oauth";
  19. } & OAuthCredentials;
  20. type AuthCredential = ApiKeyCredential | OAuthCredentialEntry;
  21. type AuthStorage = Record<string, AuthCredential>;
  22. function loadAuthStorage(): AuthStorage {
  23. if (!existsSync(AUTH_PATH)) {
  24. return {};
  25. }
  26. try {
  27. const content = readFileSync(AUTH_PATH, "utf-8");
  28. return JSON.parse(content);
  29. } catch {
  30. return {};
  31. }
  32. }
  33. function saveAuthStorage(storage: AuthStorage): void {
  34. const configDir = dirname(AUTH_PATH);
  35. if (!existsSync(configDir)) {
  36. mkdirSync(configDir, { recursive: true, mode: 0o700 });
  37. }
  38. writeFileSync(AUTH_PATH, JSON.stringify(storage, null, 2), "utf-8");
  39. chmodSync(AUTH_PATH, 0o600);
  40. }
  41. /**
  42. * Resolve API key for a provider from ~/.pi/agent/auth.json
  43. *
  44. * For API key credentials, returns the key directly.
  45. * For OAuth credentials, returns the access token (refreshing if expired and saving back).
  46. *
  47. */
  48. export async function resolveApiKey(provider: string): Promise<string | undefined> {
  49. const storage = loadAuthStorage();
  50. const entry = storage[provider];
  51. if (!entry) return undefined;
  52. if (entry.type === "api_key") {
  53. return entry.key;
  54. }
  55. if (entry.type === "oauth") {
  56. // Build OAuthCredentials record for getOAuthApiKey
  57. const oauthCredentials: Record<string, OAuthCredentials> = {};
  58. for (const [key, value] of Object.entries(storage)) {
  59. if (value.type === "oauth") {
  60. const { type: _, ...creds } = value;
  61. oauthCredentials[key] = creds;
  62. }
  63. }
  64. let result: { newCredentials: OAuthCredentials; apiKey: string } | null = null;
  65. try {
  66. result = await getOAuthApiKey(provider as OAuthProvider, oauthCredentials);
  67. } catch (e) {
  68. console.log(JSON.stringify(e));
  69. }
  70. if (!result) return undefined;
  71. // Save refreshed credentials back to auth.json
  72. storage[provider] = { type: "oauth", ...result.newCredentials };
  73. saveAuthStorage(storage);
  74. return result.apiKey;
  75. }
  76. return undefined;
  77. }