File size: 9,239 Bytes
6111b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
"use server";

import { NextResponse } from "next/server";
import fs from "fs/promises";
import path from "path";
import { requireCliToolsAuth } from "@/lib/api/requireCliToolsAuth";
import { ensureCliConfigWriteAllowed, getCliConfigPaths } from "@/shared/services/cliRuntime";
import { resolveDataDir } from "@/lib/dataPaths";
import { compareTr } from "@/shared/utils/turkishText";
import { codexProfileIdSchema, codexProfileNameSchema } from "@/shared/validation/schemas";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";

const PROFILES_DIR = path.join(resolveDataDir(), "codex-profiles");

/**

 * Resolve a path inside PROFILES_DIR and verify it stays within bounds.

 * Throws on path traversal attempts.

 */
function safeProfilePath(...segments: string[]): string {
  const resolved = path.resolve(PROFILES_DIR, ...segments);
  const base = path.resolve(PROFILES_DIR);
  if (resolved !== base && !resolved.startsWith(base + path.sep)) {
    throw new Error("Invalid path: directory traversal detected");
  }
  return resolved;
}

/**

 * Ensure profiles directory exists

 */
async function ensureProfilesDir() {
  await fs.mkdir(PROFILES_DIR, { recursive: true });
  return PROFILES_DIR;
}

/**

 * Extract a label from auth.json content (email or auth_mode)

 */
function extractAuthLabel(authJson) {
  try {
    const data = JSON.parse(authJson);
    // ChatGPT-style auth
    if (data.tokens?.id_token) {
      const payload = data.tokens.id_token.split(".")[1];
      const decoded = JSON.parse(Buffer.from(payload, "base64").toString());
      if (decoded.email) return decoded.email;
    }
    if (data.auth_mode) return data.auth_mode;
    if (data.OPENAI_API_KEY) return `API Key: ${data.OPENAI_API_KEY.slice(0, 8)}...`;
    return "unknown";
  } catch {
    return "unknown";
  }
}

// GET - List all saved profiles
export async function GET(request: Request) {
  const authError = await requireCliToolsAuth(request);
  if (authError) return authError;

  try {
    await ensureProfilesDir();

    let entries;
    try {
      entries = await fs.readdir(PROFILES_DIR);
    } catch {
      return NextResponse.json({ profiles: [] });
    }

    const profileFiles = entries.filter((e) => e.endsWith(".json"));
    const profiles = [];

    for (const file of profileFiles) {
      try {
        const raw = await fs.readFile(path.join(PROFILES_DIR, file), "utf-8");
        const profile = JSON.parse(raw);
        profiles.push({
          id: file.replace(".json", ""),
          name: profile.name,
          authLabel: profile.authLabel || "unknown",
          createdAt: profile.createdAt,
          hasConfig: !!profile.configToml,
          hasAuth: !!profile.authJson,
        });
      } catch {
        // Skip corrupt files
      }
    }

    // Sort by name
    profiles.sort((a, b) => compareTr(a.name, b.name));
    return NextResponse.json({ profiles });
  } catch (error) {
    console.log("Error listing codex profiles:", error.message);
    return NextResponse.json({ error: "Failed to list profiles" }, { status: 500 });
  }
}

// POST - Save current config as a named profile
export async function POST(request) {
  const authError = await requireCliToolsAuth(request);
  if (authError) return authError;

  let rawBody;
  try {
    rawBody = await request.json();
  } catch {
    return NextResponse.json(
      {
        error: {
          message: "Invalid request",
          details: [{ field: "body", message: "Invalid JSON body" }],
        },
      },
      { status: 400 }
    );
  }

  try {
    const writeGuard = ensureCliConfigWriteAllowed();
    if (writeGuard) {
      return NextResponse.json({ error: writeGuard }, { status: 403 });
    }

    const validation = validateBody(codexProfileNameSchema, rawBody);
    if (isValidationFailure(validation)) {
      return NextResponse.json({ error: validation.error }, { status: 400 });
    }
    const { name } = validation.data;

    const paths = getCliConfigPaths("codex");
    if (!paths) {
      return NextResponse.json({ error: "Codex config paths not found" }, { status: 500 });
    }

    // Read current files
    let configToml = null;
    let authJson = null;

    try {
      configToml = await fs.readFile(paths.config, "utf-8");
    } catch {
      // No config file
    }

    try {
      authJson = await fs.readFile(paths.auth, "utf-8");
    } catch {
      // No auth file
    }

    if (!configToml && !authJson) {
      return NextResponse.json(
        { error: "No Codex configuration files found to save" },
        { status: 400 }
      );
    }

    const profileId = name
      .trim()
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/^-|-$/g, "");

    const profile = {
      name: name.trim(),
      createdAt: new Date().toISOString(),
      authLabel: authJson ? extractAuthLabel(authJson) : "no-auth",
      configToml,
      authJson,
    };

    await ensureProfilesDir();
    const profilePath = safeProfilePath(`${profileId}.json`);
    await fs.writeFile(profilePath, JSON.stringify(profile, null, 2));

    return NextResponse.json({
      success: true,
      message: `Profile "${name}" saved successfully`,
      profileId,
    });
  } catch (error) {
    console.log("Error saving codex profile:", error.message);
    return NextResponse.json({ error: "Failed to save profile" }, { status: 500 });
  }
}

// PUT - Activate a saved profile (restore its config + auth)
export async function PUT(request) {
  const authError = await requireCliToolsAuth(request);
  if (authError) return authError;

  let rawBody;
  try {
    rawBody = await request.json();
  } catch {
    return NextResponse.json(
      {
        error: {
          message: "Invalid request",
          details: [{ field: "body", message: "Invalid JSON body" }],
        },
      },
      { status: 400 }
    );
  }

  try {
    const writeGuard = ensureCliConfigWriteAllowed();
    if (writeGuard) {
      return NextResponse.json({ error: writeGuard }, { status: 403 });
    }

    const validation = validateBody(codexProfileIdSchema, rawBody);
    if (isValidationFailure(validation)) {
      return NextResponse.json({ error: validation.error }, { status: 400 });
    }
    const { profileId } = validation.data;

    const profilePath = safeProfilePath(`${profileId}.json`);
    let profile;
    try {
      const raw = await fs.readFile(profilePath, "utf-8");
      profile = JSON.parse(raw);
    } catch {
      return NextResponse.json({ error: `Profile "${profileId}" not found` }, { status: 404 });
    }

    const paths = getCliConfigPaths("codex");
    if (!paths) {
      return NextResponse.json({ error: "Codex config paths not found" }, { status: 500 });
    }

    // Create backup of current config before switching
    const { createMultiBackup } = await import("@/shared/services/backupService");
    await createMultiBackup("codex", [paths.config, paths.auth]);

    // Ensure codex dir exists
    await fs.mkdir(path.dirname(paths.config), { recursive: true });

    // Restore files
    if (profile.configToml) {
      await fs.writeFile(paths.config, profile.configToml);
    }
    if (profile.authJson) {
      await fs.writeFile(paths.auth, profile.authJson);
    }

    return NextResponse.json({
      success: true,
      message: `Profile "${profile.name}" activated`,
      profileId,
      restoredConfig: !!profile.configToml,
      restoredAuth: !!profile.authJson,
    });
  } catch (error) {
    console.log("Error activating codex profile:", error.message);
    return NextResponse.json({ error: "Failed to activate profile" }, { status: 500 });
  }
}

// DELETE - Remove a saved profile
export async function DELETE(request) {
  const authError = await requireCliToolsAuth(request);
  if (authError) return authError;

  let rawBody;
  try {
    rawBody = await request.json();
  } catch {
    return NextResponse.json(
      {
        error: {
          message: "Invalid request",
          details: [{ field: "body", message: "Invalid JSON body" }],
        },
      },
      { status: 400 }
    );
  }

  try {
    const validation = validateBody(codexProfileIdSchema, rawBody);
    if (isValidationFailure(validation)) {
      return NextResponse.json({ error: validation.error }, { status: 400 });
    }
    const { profileId } = validation.data;

    const profilePath = safeProfilePath(`${profileId}.json`);
    try {
      await fs.unlink(profilePath);
    } catch (err) {
      if (err.code === "ENOENT") {
        return NextResponse.json({ error: `Profile "${profileId}" not found` }, { status: 404 });
      }
      throw err;
    }

    return NextResponse.json({
      success: true,
      message: `Profile "${profileId}" deleted`,
    });
  } catch (error) {
    console.log("Error deleting codex profile:", error.message);
    return NextResponse.json({ error: "Failed to delete profile" }, { status: 500 });
  }
}