@wengine-ai/claude-code-router-shared 2.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Sensitive field identification and sanitization functionality
3
+ */
4
+
5
+ import { SanitizeResult } from './types';
6
+
7
+ // Sensitive field pattern list
8
+ const SENSITIVE_PATTERNS = [
9
+ 'api_key', 'apikey', 'apiKey', 'APIKEY',
10
+ 'api_secret', 'apisecret', 'apiSecret',
11
+ 'secret', 'SECRET',
12
+ 'token', 'TOKEN', 'auth_token',
13
+ 'password', 'PASSWORD', 'passwd',
14
+ 'private_key', 'privateKey',
15
+ 'access_key', 'accessKey',
16
+ ];
17
+
18
+ // Environment variable placeholder regex
19
+ const ENV_VAR_REGEX = /^\$\{?[A-Z_][A-Z0-9_]*\}?$/;
20
+
21
+ /**
22
+ * Check if field name is sensitive
23
+ */
24
+ function isSensitiveField(fieldName: string): boolean {
25
+ const lowerFieldName = fieldName.toLowerCase();
26
+ return SENSITIVE_PATTERNS.some(pattern =>
27
+ lowerFieldName.includes(pattern.toLowerCase())
28
+ );
29
+ }
30
+
31
+ /**
32
+ * Generate environment variable name
33
+ * @param fieldType Field type (provider, transformer, global)
34
+ * @param entityName Entity name (e.g., provider name)
35
+ * @param fieldName Field name
36
+ */
37
+ export function generateEnvVarName(
38
+ fieldType: 'provider' | 'transformer' | 'global',
39
+ entityName: string,
40
+ fieldName: string
41
+ ): string {
42
+ // Generate uppercase environment variable name
43
+ // e.g., DEEPSEEK_API_KEY, CUSTOM_TRANSFORMER_SECRET
44
+ const prefix = entityName.toUpperCase().replace(/[^A-Z0-9]/g, '_');
45
+ const field = fieldName.toUpperCase().replace(/[^A-Z0-9]/g, '_');
46
+
47
+ // If prefix and field name are the same (e.g., API_KEY), avoid duplication
48
+ if (prefix === field) {
49
+ return prefix;
50
+ }
51
+
52
+ return `${prefix}_${field}`;
53
+ }
54
+
55
+ /**
56
+ * Check if value is already an environment variable placeholder
57
+ */
58
+ function isEnvPlaceholder(value: any): boolean {
59
+ if (typeof value !== 'string') {
60
+ return false;
61
+ }
62
+ return ENV_VAR_REGEX.test(value.trim());
63
+ }
64
+
65
+ /**
66
+ * Extract variable name from environment variable placeholder
67
+ * @param value Environment variable value (e.g., $VAR or ${VAR})
68
+ */
69
+ function extractEnvVarName(value: string): string | null {
70
+ const trimmed = value.trim();
71
+
72
+ // Match ${VAR_NAME} format
73
+ const bracedMatch = trimmed.match(/^\$\{([A-Z_][A-Z0-9_]*)\}$/);
74
+ if (bracedMatch) {
75
+ return bracedMatch[1];
76
+ }
77
+
78
+ // Match $VAR_NAME format
79
+ const unbracedMatch = trimmed.match(/^\$([A-Z_][A-Z0-9_]*)$/);
80
+ if (unbracedMatch) {
81
+ return unbracedMatch[1];
82
+ }
83
+
84
+ return null;
85
+ }
86
+
87
+ /**
88
+ * Recursively traverse object to identify and sanitize sensitive fields
89
+ * @param config Configuration object
90
+ * @param path Current field path
91
+ * @param sanitizedCount Sanitized field count
92
+ */
93
+ function sanitizeObject(
94
+ config: any,
95
+ path: string = '',
96
+ sanitizedCount: number = 0
97
+ ): { sanitized: any; count: number } {
98
+ if (!config || typeof config !== 'object') {
99
+ return { sanitized: config, count: sanitizedCount };
100
+ }
101
+
102
+ if (Array.isArray(config)) {
103
+ const sanitizedArray: any[] = [];
104
+ for (let i = 0; i < config.length; i++) {
105
+ const result = sanitizeObject(
106
+ config[i],
107
+ path ? `${path}[${i}]` : `[${i}]`,
108
+ sanitizedCount
109
+ );
110
+ sanitizedArray.push(result.sanitized);
111
+ sanitizedCount = result.count;
112
+ }
113
+ return { sanitized: sanitizedArray, count: sanitizedCount };
114
+ }
115
+
116
+ const sanitizedObj: any = {};
117
+ for (const [key, value] of Object.entries(config)) {
118
+ const currentPath = path ? `${path}.${key}` : key;
119
+
120
+ // Check if this is a sensitive field
121
+ if (isSensitiveField(key) && typeof value === 'string') {
122
+ // If value is already an environment variable, keep unchanged
123
+ if (isEnvPlaceholder(value)) {
124
+ sanitizedObj[key] = value;
125
+ } else {
126
+ // Sanitize: replace with environment variable placeholder
127
+ // Try to infer entity name from path
128
+ let entityName = 'CONFIG';
129
+ const pathParts = currentPath.split('.');
130
+
131
+ // If path contains Providers or transformers, try to extract entity name
132
+ for (let i = 0; i < pathParts.length; i++) {
133
+ if (pathParts[i] === 'Providers' || pathParts[i] === 'transformers') {
134
+ // Find name field
135
+ if (i + 1 < pathParts.length && pathParts[i + 1].match(/^\d+$/)) {
136
+ // This is array index, find name field at same level
137
+ const parentPath = pathParts.slice(0, i + 2).join('.');
138
+ // Find name in current context
139
+ const context = config;
140
+ if (context.name) {
141
+ entityName = context.name;
142
+ }
143
+ }
144
+ break;
145
+ }
146
+ }
147
+
148
+ const envVarName = generateEnvVarName('global', entityName, key);
149
+ sanitizedObj[key] = `\${${envVarName}}`;
150
+
151
+ sanitizedCount++;
152
+ }
153
+ } else if (typeof value === 'object' && value !== null) {
154
+ // Recursively process nested objects
155
+ const result = sanitizeObject(value, currentPath, sanitizedCount);
156
+ sanitizedObj[key] = result.sanitized;
157
+ sanitizedCount = result.count;
158
+ } else {
159
+ // Keep original value
160
+ sanitizedObj[key] = value;
161
+ }
162
+ }
163
+
164
+ return { sanitized: sanitizedObj, count: sanitizedCount };
165
+ }
166
+
167
+ /**
168
+ * Sanitize configuration object
169
+ * @param config Original configuration
170
+ * @returns Sanitization result
171
+ */
172
+ export async function sanitizeConfig(config: any): Promise<SanitizeResult> {
173
+ // Deep copy configuration to avoid modifying original object
174
+ const configCopy = JSON.parse(JSON.stringify(config));
175
+
176
+ const result = sanitizeObject(configCopy);
177
+
178
+ return {
179
+ sanitizedConfig: result.sanitized,
180
+ sanitizedCount: result.count,
181
+ };
182
+ }
183
+
184
+ /**
185
+ * Fill sensitive information into configuration
186
+ * @param config Preset configuration (containing environment variable placeholders)
187
+ * @param inputs User input sensitive information
188
+ * @returns Filled configuration
189
+ */
190
+ export function fillSensitiveInputs(config: any, inputs: Record<string, string>): any {
191
+ const configCopy = JSON.parse(JSON.stringify(config));
192
+
193
+ function fillObject(obj: any, path: string = ''): any {
194
+ if (!obj || typeof obj !== 'object') {
195
+ return obj;
196
+ }
197
+
198
+ if (Array.isArray(obj)) {
199
+ return obj.map((item, index) =>
200
+ fillObject(item, path ? `${path}[${index}]` : `[${index}]`)
201
+ );
202
+ }
203
+
204
+ const result: any = {};
205
+ for (const [key, value] of Object.entries(obj)) {
206
+ const currentPath = path ? `${path}.${key}` : key;
207
+
208
+ if (typeof value === 'string' && isEnvPlaceholder(value)) {
209
+ // Check if there is user input
210
+ const input = inputs[currentPath];
211
+ if (input) {
212
+ result[key] = input;
213
+ } else {
214
+ result[key] = value;
215
+ }
216
+ } else if (typeof value === 'object' && value !== null) {
217
+ result[key] = fillObject(value, currentPath);
218
+ } else {
219
+ result[key] = value;
220
+ }
221
+ }
222
+
223
+ return result;
224
+ }
225
+
226
+ return fillObject(configCopy);
227
+ }
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Type definitions for preset functionality
3
+ */
4
+
5
+ // Collection of user input values
6
+ export interface UserInputValues {
7
+ [inputId: string]: any;
8
+ }
9
+
10
+ // Input type enumeration
11
+ export enum InputType {
12
+ PASSWORD = 'password', // Password input (hidden)
13
+ INPUT = 'input', // Text input
14
+ SELECT = 'select', // Single selection
15
+ MULTISELECT = 'multiselect', // Multiple selection
16
+ CONFIRM = 'confirm', // Confirmation checkbox
17
+ EDITOR = 'editor', // Multi-line text editor
18
+ NUMBER = 'number', // Number input
19
+ }
20
+
21
+ // Option definition
22
+ export interface InputOption {
23
+ label: string; // Display text
24
+ value: string | number | boolean; // Actual value
25
+ description?: string; // Option description
26
+ disabled?: boolean; // Whether disabled
27
+ icon?: string; // Icon
28
+ }
29
+
30
+ // Dynamic option source
31
+ export interface DynamicOptions {
32
+ type: 'static' | 'providers' | 'models' | 'custom';
33
+ // static: Use fixed options array
34
+ // providers: Dynamically retrieve from Providers configuration
35
+ // models: Retrieve from specified provider's models
36
+ // custom: Custom function (reserved, not implemented yet)
37
+
38
+ // Used when type is 'static'
39
+ options?: InputOption[];
40
+
41
+ // Used when type is 'providers'
42
+ // Automatically extract name and related configuration from preset's Providers
43
+
44
+ // Used when type is 'models'
45
+ providerField?: string; // Point to provider selector field path (e.g. "#{selectedProvider}")
46
+
47
+ // Used when type is 'custom' (reserved)
48
+ source?: string; // Custom data source
49
+ }
50
+
51
+ // Conditional expression
52
+ export interface Condition {
53
+ field: string; // Dependent field path
54
+ operator?: 'eq' | 'ne' | 'in' | 'nin' | 'gt' | 'lt' | 'gte' | 'lte' | 'exists';
55
+ value?: any; // Comparison value
56
+ // eq: equals
57
+ // ne: not equals
58
+ // in: included in (array)
59
+ // nin: not included in (array)
60
+ // gt: greater than
61
+ // lt: less than
62
+ // gte: greater than or equal to
63
+ // lte: less than or equal to
64
+ // exists: field exists (doesn't check value)
65
+ }
66
+
67
+ // Complex field input configuration
68
+ export interface RequiredInput {
69
+ id: string; // Unique identifier (for variable reference)
70
+ type?: InputType; // Input type, defaults to password
71
+ label?: string; // Display label
72
+ prompt?: string; // Prompt information/description
73
+ placeholder?: string; // Placeholder
74
+
75
+ // Option configuration (for select/multiselect)
76
+ options?: InputOption[] | DynamicOptions;
77
+
78
+ // Conditional display
79
+ when?: Condition | Condition[]; // Show this field only when conditions are met (supports AND/OR logic)
80
+
81
+ // Default value
82
+ defaultValue?: any;
83
+
84
+ // Validation rules
85
+ required?: boolean; // Whether required, defaults to true
86
+ validator?: RegExp | string | ((value: any) => boolean | string);
87
+
88
+ // UI configuration
89
+ min?: number; // Minimum value (for number)
90
+ max?: number; // Maximum value (for number)
91
+ rows?: number; // Number of rows (for editor)
92
+
93
+ // Advanced configuration
94
+ dependsOn?: string[]; // Explicitly declare dependent fields (for optimizing update order)
95
+ }
96
+
97
+ // Provider configuration
98
+ export interface ProviderConfig {
99
+ name: string;
100
+ api_base_url: string;
101
+ api_key: string;
102
+ models: string[];
103
+ transformer?: any;
104
+ [key: string]: any;
105
+ }
106
+
107
+ // Router configuration
108
+ export interface RouterConfig {
109
+ default?: string;
110
+ background?: string;
111
+ think?: string;
112
+ longContext?: string;
113
+ longContextThreshold?: number;
114
+ webSearch?: string;
115
+ image?: string;
116
+ models?: Record<string, string>;
117
+ [key: string]: string | number | Record<string, string> | undefined;
118
+ }
119
+
120
+ // Transformer configuration
121
+ export interface TransformerConfig {
122
+ path?: string;
123
+ use: Array<string | [string, any]>;
124
+ options?: any;
125
+ [key: string]: any;
126
+ }
127
+
128
+ // Preset metadata (flattened structure, for manifest.json)
129
+ export interface PresetMetadata {
130
+ name: string; // Preset name
131
+ version: string; // Version number (semver)
132
+ description?: string; // Description
133
+ author?: string; // Author
134
+ homepage?: string; // Homepage
135
+ repository?: string; // Source repository
136
+ license?: string; // License
137
+ keywords?: string[]; // Keywords
138
+ ccrVersion?: string; // Compatible CCR version
139
+ source?: string; // Preset source URL
140
+ sourceType?: 'local' | 'gist' | 'registry';
141
+ checksum?: string; // Preset content checksum
142
+ }
143
+
144
+ // Preset configuration section
145
+ export interface PresetConfigSection {
146
+ Providers?: ProviderConfig[];
147
+ Router?: RouterConfig;
148
+ transformers?: TransformerConfig[];
149
+ StatusLine?: any;
150
+ NON_INTERACTIVE_MODE?: boolean;
151
+
152
+ // CLI-only fields (not used by server)
153
+ noServer?: boolean; // CLI: Whether to skip local server startup and use provider's API directly
154
+ claudeCodeSettings?: { // CLI: Claude Code specific settings
155
+ env?: Record<string, any>; // CLI: Environment variables to pass to Claude Code
156
+ statusLine?: any; // CLI: Status line configuration
157
+ [key: string]: any;
158
+ };
159
+
160
+ [key: string]: any;
161
+ }
162
+
163
+ // Template configuration (for dynamically generating configuration based on user input)
164
+ export interface TemplateConfig {
165
+ // Template configuration using #{variable} syntax (different from statusline's {{variable}} format)
166
+ // Example: { "Providers": [{ "name": "#{providerName}", "api_key": "#{apiKey}" }] }
167
+ [key: string]: any;
168
+ }
169
+
170
+ // Configuration mapping (maps user input values to specific configuration locations)
171
+ export interface ConfigMapping {
172
+ // Field path (supports array syntax, e.g. "Providers[0].api_key")
173
+ target: string;
174
+
175
+ // Value source (references user input id, or uses fixed value)
176
+ value: string | any; // If string and starts with #, treated as variable reference (e.g. #{fieldId})
177
+
178
+ // Condition (optional, apply this mapping only when condition is met)
179
+ when?: Condition | Condition[];
180
+ }
181
+
182
+ // Complete preset file format
183
+ export interface PresetFile {
184
+ metadata?: PresetMetadata;
185
+ config: PresetConfigSection;
186
+ secrets?: {
187
+ // Sensitive information storage, format: field path -> value
188
+ // Example: { "Providers[0].api_key": "sk-xxx", "APIKEY": "my-secret" }
189
+ [fieldPath: string]: string;
190
+ };
191
+
192
+ // === Dynamic configuration system ===
193
+ // Configuration input schema
194
+ schema?: RequiredInput[];
195
+
196
+ // Configuration template (uses variable replacement)
197
+ template?: TemplateConfig;
198
+
199
+ // Configuration mappings (maps user input to configuration)
200
+ configMappings?: ConfigMapping[];
201
+ }
202
+
203
+ // manifest.json format (file inside ZIP archive)
204
+ export interface ManifestFile extends PresetMetadata, PresetConfigSection {
205
+ // === Dynamic configuration system ===
206
+ schema?: RequiredInput[];
207
+ template?: TemplateConfig;
208
+ configMappings?: ConfigMapping[];
209
+
210
+ // === User configuration value storage ===
211
+ // User-filled configuration values are stored separately from original configuration
212
+ // Values collected during installation are stored here, applied at runtime
213
+ userValues?: UserInputValues;
214
+ }
215
+
216
+ // Online preset index entry
217
+ export interface PresetIndexEntry {
218
+ id: string; // Unique identifier
219
+ name: string; // Display name
220
+ description?: string; // Short description
221
+ version: string; // Latest version
222
+ author?: string; // Author
223
+ downloads?: number; // Download count
224
+ stars?: number; // Star count
225
+ tags?: string[]; // Tags
226
+ url: string; // Download address
227
+ repo?: string; // Repository (e.g., 'owner/repo')
228
+ checksum?: string; // SHA256 checksum
229
+ ccrVersion?: string; // Compatible version
230
+ }
231
+
232
+ // Online preset repository index
233
+ export interface PresetRegistry {
234
+ version: string; // Index format version
235
+ lastUpdated: string; // Last update time
236
+ presets: PresetIndexEntry[];
237
+ }
238
+
239
+ // Configuration validation result
240
+ export interface ValidationResult {
241
+ valid: boolean;
242
+ errors: string[];
243
+ warnings: string[];
244
+ }
245
+
246
+ // Merge strategy enumeration
247
+ export enum MergeStrategy {
248
+ ASK = 'ask', // Interactive prompt
249
+ OVERWRITE = 'overwrite', // Overwrite existing
250
+ MERGE = 'merge', // Intelligent merge
251
+ SKIP = 'skip', // Skip conflicting items
252
+ }
253
+
254
+ // Sanitization result
255
+ export interface SanitizeResult {
256
+ sanitizedConfig: any;
257
+ sanitizedCount: number;
258
+ }
259
+
260
+ // Preset information (for list display)
261
+ export interface PresetInfo {
262
+ name: string; // Preset name
263
+ version?: string; // Version number
264
+ description?: string; // Description
265
+ author?: string; // Author
266
+ config: PresetConfigSection;
267
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist",
5
+ "rootDir": "./src"
6
+ },
7
+ "include": ["src/**/*"],
8
+ "exclude": ["node_modules", "dist"]
9
+ }