File size: 6,817 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
import { createHash, randomUUID } from "crypto";

import { getDbInstance, rowToCamel } from "./core";
import { decrypt, encrypt } from "./encryption";

export type CommandCodeAuthStatus = "pending" | "received" | "applied" | "expired";

export interface CommandCodeAuthMetadata {
  userId?: string;
  userName?: string;
  keyName?: string;
  receivedAt?: string;
}

export interface CommandCodeAuthSafeStatus {
  id: string;
  stateHash: string;
  status: CommandCodeAuthStatus;
  metadata: CommandCodeAuthMetadata | null;
  createdAt: string;
  expiresAt: string;
  receivedAt: string | null;
  appliedAt: string | null;
  updatedAt: string;
}

export interface ConsumedCommandCodeAuthSecret extends CommandCodeAuthSafeStatus {
  apiKey: string;
}

type DbRunResult = { changes?: number };
type DbStatement<TRow = unknown> = {
  get: (...params: unknown[]) => TRow | undefined;
  all: (...params: unknown[]) => TRow[];
  run: (...params: unknown[]) => DbRunResult;
};
type DbLike = {
  prepare: <TRow = unknown>(sql: string) => DbStatement<TRow>;
  transaction: <T extends (...args: unknown[]) => unknown>(fn: T) => T;
};

type AuthSessionRow = {
  id: string;
  state_hash: string;
  status: CommandCodeAuthStatus;
  encrypted_api_key?: string | null;
  metadata_json?: string | null;
  created_at: string;
  expires_at: string;
  received_at?: string | null;
  applied_at?: string | null;
  updated_at: string;
};

function db(): DbLike {
  return getDbInstance() as unknown as DbLike;
}

export function hashCommandCodeAuthState(state: string): string {
  return createHash("sha256").update(state, "utf8").digest("hex");
}

function nowIso(): string {
  return new Date().toISOString();
}

function parseMetadata(value: unknown): CommandCodeAuthMetadata | null {
  if (!value) return null;
  // rowToCamel auto-parses the `metadata_json` column and exposes the object under
  // `camel.metadata` (already parsed); accept that directly. Fall back to parsing a
  // raw string for any other caller.
  if (typeof value === "object" && !Array.isArray(value)) {
    return value as CommandCodeAuthMetadata;
  }
  if (typeof value !== "string") return null;
  try {
    const parsed = JSON.parse(value) as CommandCodeAuthMetadata;
    return parsed && typeof parsed === "object" ? parsed : null;
  } catch {
    return null;
  }
}

function toSafeStatus(row: AuthSessionRow): CommandCodeAuthSafeStatus {
  const camel = rowToCamel(row) as Record<string, unknown>;
  return {
    id: String(camel.id),
    stateHash: String(camel.stateHash),
    status: camel.status as CommandCodeAuthStatus,
    metadata: parseMetadata(camel.metadata ?? camel.metadataJson),
    createdAt: String(camel.createdAt),
    expiresAt: String(camel.expiresAt),
    receivedAt: (camel.receivedAt as string | null | undefined) ?? null,
    appliedAt: (camel.appliedAt as string | null | undefined) ?? null,
    updatedAt: String(camel.updatedAt),
  };
}

function markExpiredForState(stateHash: string, now = nowIso()): void {
  db()
    .prepare(
      `UPDATE command_code_auth_sessions
       SET status = 'expired', updated_at = ?
       WHERE state_hash = ? AND status IN ('pending', 'received') AND expires_at <= ?`
    )
    .run(now, stateHash, now);
}

export function createPendingCommandCodeAuthSession(input: {
  stateHash: string;
  expiresAt: string;
}): CommandCodeAuthSafeStatus {
  const id = randomUUID();
  const now = nowIso();
  db()
    .prepare(
      `INSERT INTO command_code_auth_sessions (
        id, state_hash, status, encrypted_api_key, metadata_json,
        created_at, expires_at, received_at, applied_at, updated_at
      ) VALUES (?, ?, 'pending', NULL, NULL, ?, ?, NULL, NULL, ?)`
    )
    .run(id, input.stateHash, now, input.expiresAt, now);

  const row = db()
    .prepare<AuthSessionRow>("SELECT * FROM command_code_auth_sessions WHERE id = ?")
    .get(id);
  if (!row) throw new Error("Failed to create Command Code auth session");
  return toSafeStatus(row);
}

export function markCommandCodeAuthSessionReceived(input: {
  stateHash: string;
  apiKey: string;
  metadata?: CommandCodeAuthMetadata;
}): CommandCodeAuthSafeStatus | null {
  const now = nowIso();
  markExpiredForState(input.stateHash, now);
  const metadata: CommandCodeAuthMetadata = {
    ...(input.metadata || {}),
    receivedAt: now,
  };
  const encryptedApiKey = encrypt(input.apiKey);
  db()
    .prepare(
      `UPDATE command_code_auth_sessions
       SET status = 'received', encrypted_api_key = ?, metadata_json = ?, received_at = ?, updated_at = ?
       WHERE state_hash = ? AND status IN ('pending', 'received') AND expires_at > ?`
    )
    .run(encryptedApiKey, JSON.stringify(metadata), now, now, input.stateHash, now);

  return getCommandCodeAuthSessionSafeStatus(input.stateHash);
}

export function getCommandCodeAuthSessionSafeStatus(
  stateHash: string
): CommandCodeAuthSafeStatus | null {
  markExpiredForState(stateHash);
  const row = db()
    .prepare<AuthSessionRow>("SELECT * FROM command_code_auth_sessions WHERE state_hash = ?")
    .get(stateHash);
  return row ? toSafeStatus(row) : null;
}

export function consumeCommandCodeAuthSecret(
  stateHash: string
): ConsumedCommandCodeAuthSecret | null {
  const database = db();
  return database.transaction(() => {
    const now = nowIso();
    database
      .prepare(
        `UPDATE command_code_auth_sessions
         SET status = 'expired', updated_at = ?
         WHERE state_hash = ? AND status IN ('pending', 'received') AND expires_at <= ?`
      )
      .run(now, stateHash, now);

    const row = database
      .prepare<AuthSessionRow>(
        `SELECT * FROM command_code_auth_sessions
         WHERE state_hash = ? AND status = 'received' AND expires_at > ? AND encrypted_api_key IS NOT NULL`
      )
      .get(stateHash, now);
    if (!row?.encrypted_api_key) return null;

    const apiKey = decrypt(row.encrypted_api_key);
    if (!apiKey) return null;

    const result = database
      .prepare(
        `UPDATE command_code_auth_sessions
         SET status = 'applied', encrypted_api_key = NULL, applied_at = ?, updated_at = ?
         WHERE id = ? AND status = 'received'`
      )
      .run(now, now, row.id);
    if (!result.changes) return null;

    return {
      ...toSafeStatus({
        ...row,
        status: "applied",
        encrypted_api_key: null,
        applied_at: now,
        updated_at: now,
      }),
      apiKey,
    };
  })() as ConsumedCommandCodeAuthSecret | null;
}

export function cleanupExpiredCommandCodeAuthSessions(now = nowIso()): number {
  const result = db()
    .prepare(
      `UPDATE command_code_auth_sessions
       SET status = 'expired', updated_at = ?
       WHERE status IN ('pending', 'received') AND expires_at <= ?`
    )
    .run(now, now);
  return result.changes ?? 0;
}