File size: 5,613 Bytes
bc4a7e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { createHash } from "crypto";
import {
  getApiKeys,
  getCombos,
  getModelAliases,
  getProviderConnections,
  getProviderNodes,
  getSettings,
} from "@/lib/localDb";

type JsonRecord = Record<string, unknown>;

export interface ConfigSyncBundle {
  settings: JsonRecord;
  providerConnections: JsonRecord[];
  providerNodes: JsonRecord[];
  modelAliases: JsonRecord;
  combos: JsonRecord[];
  apiKeys: JsonRecord[];
}

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

function sanitizeSettingsForSync(settings: unknown): JsonRecord {
  const record = asRecord(settings);
  const {
    password: _password,
    requireLogin: _requireLogin,
    cloudEnabled: _cloudEnabled,
    ...safeSettings
  } = record;
  return safeSettings;
}

function sortByStringKeys<T extends JsonRecord>(items: T[], keys: string[]) {
  return [...items].sort((a, b) => {
    for (const key of keys) {
      const leftRaw = a[key];
      const rightRaw = b[key];

      if (typeof leftRaw === "number" || typeof rightRaw === "number") {
        const left = typeof leftRaw === "number" ? leftRaw : Number.MAX_SAFE_INTEGER;
        const right = typeof rightRaw === "number" ? rightRaw : Number.MAX_SAFE_INTEGER;
        if (left !== right) return left - right;
        continue;
      }

      const left = typeof leftRaw === "string" ? String(leftRaw) : "";
      const right = typeof rightRaw === "string" ? String(rightRaw) : "";
      const comparison = left.localeCompare(right, undefined, { numeric: true });
      if (comparison !== 0) return comparison;
    }
    return 0;
  });
}

function pickDefined(record: JsonRecord, keys: string[]) {
  return Object.fromEntries(
    keys.filter((key) => record[key] !== undefined).map((key) => [key, record[key]])
  );
}

function sanitizeProviderConnectionForSync(connection: unknown): JsonRecord {
  const record = asRecord(connection);
  return pickDefined(record, [
    "id",
    "provider",
    "authType",
    "name",
    "displayName",
    "email",
    "priority",
    "globalPriority",
    "defaultModel",
    "isActive",
    "accessToken",
    "refreshToken",
    "expiresAt",
    "expiresIn",
    "tokenType",
    "scope",
    "idToken",
    "projectId",
    "apiKey",
    "providerSpecificData",
    "group",
  ]);
}

function sanitizeProviderNodeForSync(node: unknown): JsonRecord {
  const record = asRecord(node);
  return pickDefined(record, [
    "id",
    "type",
    "name",
    "prefix",
    "apiType",
    "baseUrl",
    "chatPath",
    "modelsPath",
  ]);
}

function sanitizeComboForSync(combo: unknown): JsonRecord {
  const record = asRecord(combo);
  const { createdAt: _createdAt, updatedAt: _updatedAt, ...rest } = record;
  return rest;
}

function sanitizeApiKeyForSync(apiKey: unknown): JsonRecord {
  const record = asRecord(apiKey);
  return pickDefined(record, [
    "id",
    "name",
    "key",
    "machineId",
    "allowedModels",
    "allowedCombos",
    "allowedConnections",
    "noLog",
    "autoResolve",
    "isActive",
    "accessSchedule",
    "maxRequestsPerDay",
    "maxRequestsPerMinute",
    "throttleDelayMs",
    "maxSessions",
  ]);
}

function canonicalizeJson(value: unknown): unknown {
  if (Array.isArray(value)) {
    return value.map((entry) => canonicalizeJson(entry));
  }

  if (value && typeof value === "object") {
    return Object.fromEntries(
      Object.keys(value as JsonRecord)
        .sort((a, b) => a.localeCompare(b))
        .map((key) => [key, canonicalizeJson((value as JsonRecord)[key])])
    );
  }

  return value;
}

export function serializeStableJson(value: unknown) {
  return JSON.stringify(canonicalizeJson(value));
}

export function computeConfigSyncVersion(bundle: ConfigSyncBundle) {
  return createHash("sha256").update(serializeStableJson(bundle)).digest("hex");
}

export async function buildConfigSyncBundle(): Promise<ConfigSyncBundle> {
  const [settings, providerConnections, providerNodes, modelAliases, combos, apiKeys] =
    await Promise.all([
      getSettings(),
      getProviderConnections(),
      getProviderNodes(),
      getModelAliases(),
      getCombos(),
      getApiKeys(),
    ]);

  return {
    settings: sanitizeSettingsForSync(settings),
    providerConnections: sortByStringKeys(
      providerConnections.map((connection) => sanitizeProviderConnectionForSync(connection)),
      ["provider", "name", "id"]
    ),
    providerNodes: sortByStringKeys(
      providerNodes.map((node) => sanitizeProviderNodeForSync(node)),
      ["type", "name", "id"]
    ),
    modelAliases: asRecord(modelAliases),
    combos: sortByStringKeys(
      combos.map((combo) => sanitizeComboForSync(combo)),
      ["sortOrder", "name", "id"]
    ),
    apiKeys: sortByStringKeys(
      apiKeys.map((apiKey) => sanitizeApiKeyForSync(apiKey)),
      ["name", "id"]
    ),
  };
}

export async function buildConfigSyncEnvelope() {
  const bundle = await buildConfigSyncBundle();
  const version = computeConfigSyncVersion(bundle);
  return {
    version,
    bundle,
  };
}

export function toLegacyCloudSyncPayload(bundle: ConfigSyncBundle) {
  return {
    providers: bundle.providerConnections,
    providerNodes: bundle.providerNodes,
    modelAliases: bundle.modelAliases,
    combos: bundle.combos,
    apiKeys: bundle.apiKeys,
    settings: bundle.settings,
  };
}