File size: 9,002 Bytes
cd8bd0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  getProviderConnections,
  createProviderConnection,
  updateProviderConnection,
} from "@/lib/localDb";
import { ClaudeAuthFileError } from "@/lib/oauth/utils/claudeAuthFile";

type JsonRecord = Record<string, unknown>;

function toRecord(value: unknown): JsonRecord {
  return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
}

function toNonEmptyString(value: unknown): string | null {
  if (typeof value !== "string") return null;
  const trimmed = value.trim();
  return trimmed ? trimmed : null;
}

// ──── Public types ────────────────────────────────────────────────────────────

export interface ParsedClaudeAuth {
  accessToken: string;
  refreshToken: string;
  expiresAt: string | null; // ISO (converted from ms)
  scopes: string[];
  subscriptionType: string | null;
  rateLimitTier: string | null;
  email: string | null; // from bootstrap enrichment
}

export interface EnrichedClaudeAuth extends ParsedClaudeAuth {
  accountUUID: string | null;
  organizationUUID: string | null;
  organizationName: string | null;
  organizationType: string | null;
  rateLimitTier: string | null;
}

export interface CreateConnectionOptions {
  name?: string;
  email?: string;
  overwriteExisting?: boolean;
}

// ──── Parse & validate ────────────────────────────────────────────────────────

export function parseAndValidateClaudeAuth(raw: unknown): ParsedClaudeAuth {
  const doc = toRecord(raw);
  const oauthBlock = toRecord(doc.claudeAiOauth);

  const accessToken = toNonEmptyString(oauthBlock.accessToken);
  const refreshToken = toNonEmptyString(oauthBlock.refreshToken);

  if (!accessToken) {
    throw new ClaudeAuthFileError(
      "accessToken is missing or empty in claudeAiOauth",
      400,
      "missing_access_token"
    );
  }

  if (!refreshToken) {
    throw new ClaudeAuthFileError(
      "refreshToken is missing or empty in claudeAiOauth",
      400,
      "missing_refresh_token"
    );
  }

  // expiresAt in the file is ms epoch; store as ISO in DB
  let expiresAt: string | null = null;
  const rawExpiresAt = oauthBlock.expiresAt;
  if (typeof rawExpiresAt === "number" && Number.isFinite(rawExpiresAt)) {
    expiresAt = new Date(rawExpiresAt).toISOString();
  } else if (typeof rawExpiresAt === "string" && rawExpiresAt.trim()) {
    expiresAt = rawExpiresAt.trim();
  }

  const rawScopes = oauthBlock.scopes;
  const scopes: string[] = Array.isArray(rawScopes)
    ? rawScopes.filter((s): s is string => typeof s === "string")
    : [];

  return {
    accessToken,
    refreshToken,
    expiresAt,
    scopes,
    subscriptionType: toNonEmptyString(oauthBlock.subscriptionType),
    rateLimitTier: toNonEmptyString(oauthBlock.rateLimitTier),
    email: null,
  };
}

// ──── Bootstrap enrichment ────────────────────────────────────────────────────

export async function enrichWithBootstrap(
  parsed: ParsedClaudeAuth,
  // proxyConfig reserved for future authenticated-proxy support
  proxyConfig?: null
): Promise<EnrichedClaudeAuth> {
  const base: EnrichedClaudeAuth = {
    ...parsed,
    accountUUID: null,
    organizationUUID: null,
    organizationName: null,
    organizationType: null,
    rateLimitTier: parsed.rateLimitTier,
  };

  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 8000);

  try {
    const res = await fetch("https://api.anthropic.com/api/claude_cli/bootstrap", {
      method: "GET",
      headers: {
        Authorization: `Bearer ${parsed.accessToken}`,
        "anthropic-version": "2023-06-01",
        "Content-Type": "application/json",
      },
      signal: controller.signal,
    });

    if (!res.ok) {
      return base;
    }

    const body = toRecord(await res.json());

    const accountUUID = toNonEmptyString(body.account_uuid);
    const organizationUUID = toNonEmptyString(body.organization_uuid);
    const organizationName = toNonEmptyString(body.organization_name);
    const organizationType = toNonEmptyString(body.organization_type);
    const rateLimitTier = toNonEmptyString(body.rate_limit_tier) || parsed.rateLimitTier;
    const bootstrapEmail = toNonEmptyString(body.account_email);

    return {
      ...base,
      accountUUID,
      organizationUUID,
      organizationName,
      organizationType,
      rateLimitTier,
      email: parsed.email || bootstrapEmail,
    };
  } catch {
    // Network error, timeout, or parse failure β€” best-effort; callers handle null fields
    return base;
  } finally {
    clearTimeout(timer);
  }
}

// ──── Lookup ──────────────────────────────────────────────────────────────────

export async function findExistingClaudeConnection(
  accountUUID: string
): Promise<JsonRecord | null> {
  const connections = await getProviderConnections({ provider: "claude" });
  const lower = accountUUID.toLowerCase();
  return (
    (connections.find((c) => {
      const psd = toRecord((c as JsonRecord).providerSpecificData);
      const stored = toNonEmptyString(psd.accountUUID);
      return stored !== null && stored.toLowerCase() === lower;
    }) as JsonRecord | undefined) ?? null
  );
}

// ──── Create / update connection ──────────────────────────────────────────────

export async function createConnectionFromAuthFile(
  enriched: EnrichedClaudeAuth,
  options: CreateConnectionOptions
): Promise<{ connection: JsonRecord; created: boolean }> {
  // Duplicate detection by accountUUID (skipped when bootstrap failed)
  if (enriched.accountUUID) {
    const existing = await findExistingClaudeConnection(enriched.accountUUID);

    if (existing) {
      if (!options.overwriteExisting) {
        throw new ClaudeAuthFileError(
          "A Claude connection for this account already exists. Pass overwriteExisting: true to replace it.",
          409,
          "duplicate_account"
        );
      }

      const updated = await updateProviderConnection(existing.id as string, {
        accessToken: enriched.accessToken,
        refreshToken: enriched.refreshToken,
        expiresAt: enriched.expiresAt,
        email:
          options.email || enriched.email || (existing.email as string | undefined) || undefined,
        name:
          options.name ||
          (existing.name as string | undefined) ||
          options.email ||
          enriched.email ||
          "Claude (imported)",
        testStatus: "active",
        providerSpecificData: {
          ...toRecord(existing.providerSpecificData),
          accountUUID: enriched.accountUUID,
          organizationUUID: enriched.organizationUUID,
          organizationName: enriched.organizationName,
          organizationType: enriched.organizationType,
          rateLimitTier: enriched.rateLimitTier,
          scopes: enriched.scopes,
          subscriptionType: enriched.subscriptionType,
          bootstrapEmail: enriched.email,
          importedAt: new Date().toISOString(),
        },
      });

      return { connection: updated || existing, created: false };
    }
  }

  // Identity check: when bootstrap failed and we have no email, refuse unless
  // the caller has explicitly opted into overwrite mode (they know what they're doing).
  if (!enriched.email && !enriched.accountUUID && !options.overwriteExisting) {
    throw new ClaudeAuthFileError(
      "Could not verify the account identity (bootstrap failed and no email/accountUUID available). Pass overwriteExisting: true to import anyway.",
      409,
      "identity_unverified"
    );
  }

  const email = options.email || enriched.email || undefined;
  const name = options.name || options.email || enriched.email || "Claude (imported)";

  const connection = await createProviderConnection({
    provider: "claude",
    authType: "oauth",
    name,
    email,
    accessToken: enriched.accessToken,
    refreshToken: enriched.refreshToken,
    expiresAt: enriched.expiresAt,
    isActive: true,
    testStatus: "active",
    providerSpecificData: {
      accountUUID: enriched.accountUUID,
      organizationUUID: enriched.organizationUUID,
      organizationName: enriched.organizationName,
      organizationType: enriched.organizationType,
      rateLimitTier: enriched.rateLimitTier,
      scopes: enriched.scopes,
      subscriptionType: enriched.subscriptionType,
      bootstrapEmail: enriched.email,
      importedAt: new Date().toISOString(),
    },
  });

  return { connection, created: true };
}