File size: 5,454 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
import { NextResponse } from "next/server";
import { z } from "zod";
import { getAuditRequestContext, logAuditEvent } from "@/lib/compliance/index";
import { getSettings } from "@/lib/localDb";
import {
  ensurePersistentManagementPasswordHash,
  getStoredManagementPassword,
  verifyManagementPassword,
} from "@/lib/auth/managementPassword";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
import { checkLoginGuard, clearLoginAttempts, recordLoginFailure } from "@/server/auth/loginGuard";
import { createAccessToken } from "@/lib/db/accessTokens";
import { ACCESS_SCOPES } from "@/lib/accessTokens/scopes";

/**
 * POST /api/cli/connect — remote-mode bootstrap.
 *
 * Exchange the management password for a scoped CLI access token. Public route
 * (no token exists yet) that does its OWN password verification + brute-force
 * lockout, mirroring /api/auth/login — but mints an `oma_` access token instead
 * of a dashboard JWT cookie. The plaintext token is returned exactly once.
 *
 * Default scope is `admin`: the password holder is the owner and can already do
 * anything; the first token should be able to mint narrower tokens for other
 * machines. Pass `scope` to downscope (e.g. a read-only CI token).
 */

const connectSchema = z.object({
  password: z.string().min(1),
  name: z.string().min(1).max(100).optional(),
  scope: z.enum(ACCESS_SCOPES).optional(),
  expiresInDays: z.number().int().positive().max(3650).optional(),
});

export async function POST(request: Request) {
  const auditContext = getAuditRequestContext(request);

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

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

    const settings = await getSettings();
    const bruteForceEnabled = settings.bruteForceProtection !== false;
    const clientIp = auditContext.ipAddress || null;

    const guardCheck = checkLoginGuard(clientIp, { enabled: bruteForceEnabled });
    if (!guardCheck.allowed) {
      logAuditEvent({
        action: "cli.connect.locked",
        actor: "anonymous",
        target: "cli-access-token",
        resourceType: "auth_session",
        status: "failed",
        ipAddress: clientIp || undefined,
        requestId: auditContext.requestId,
        metadata: { retryAfterSeconds: guardCheck.retryAfterSeconds || 0 },
      });
      return NextResponse.json(
        { error: "Too many failed attempts. Try again later." },
        {
          status: 429,
          headers: guardCheck.retryAfterSeconds
            ? { "Retry-After": String(guardCheck.retryAfterSeconds) }
            : {},
        }
      );
    }

    const passwordState = await ensurePersistentManagementPasswordHash({
      settings,
      source: "cli.connect",
    });
    const storedHash = getStoredManagementPassword(passwordState.settings);
    if (!storedHash) {
      return NextResponse.json(
        { error: "No password configured. Complete onboarding first.", needsSetup: true },
        { status: 403 }
      );
    }

    const isValid = await verifyManagementPassword(password, storedHash);
    if (!isValid) {
      const failureDecision = recordLoginFailure(clientIp, { enabled: bruteForceEnabled });
      logAuditEvent({
        action: "cli.connect.failed",
        actor: "anonymous",
        target: "cli-access-token",
        resourceType: "auth_session",
        status: "failed",
        ipAddress: clientIp || undefined,
        requestId: auditContext.requestId,
        metadata: { reason: "invalid_password", lockedOut: failureDecision.allowed === false },
      });
      if (!failureDecision.allowed) {
        return NextResponse.json(
          { error: "Too many failed attempts. Try again later." },
          {
            status: 429,
            headers: failureDecision.retryAfterSeconds
              ? { "Retry-After": String(failureDecision.retryAfterSeconds) }
              : {},
          }
        );
      }
      return NextResponse.json({ error: "Invalid password" }, { status: 401 });
    }

    clearLoginAttempts(clientIp);

    const tokenScope = scope ?? "admin";
    const tokenName = (name ?? "remote-cli").trim() || "remote-cli";
    const expiresAt =
      typeof expiresInDays === "number"
        ? new Date(Date.now() + expiresInDays * 86_400_000).toISOString()
        : null;

    const { record, secret } = createAccessToken({
      name: tokenName,
      scope: tokenScope,
      expiresAt,
    });

    logAuditEvent({
      action: "cli.connect.success",
      actor: "admin",
      target: "cli-access-token",
      resourceType: "auth_session",
      status: "success",
      ipAddress: clientIp || undefined,
      requestId: auditContext.requestId,
      metadata: { tokenId: record.id, scope: tokenScope },
    });

    return NextResponse.json({
      success: true,
      token: secret,
      id: record.id,
      name: record.name,
      scope: record.scope,
      expiresAt: record.expiresAt,
    });
  } catch (error) {
    console.error("[CLI] connect failed:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}