newo 1.4.0 → 1.5.1

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.
@@ -1,13 +1,12 @@
1
1
  import fs from 'fs-extra';
2
+ import type { ParsedArticle, AkbImportArticle } from './types.js';
2
3
 
3
4
  /**
4
5
  * Parse AKB file and extract articles
5
- * @param {string} filePath - Path to AKB file
6
- * @returns {Array} Array of parsed articles
7
6
  */
8
- function parseAkbFile(filePath) {
9
- const content = fs.readFileSync(filePath, 'utf8');
10
- const articles = [];
7
+ export async function parseAkbFile(filePath: string): Promise<ParsedArticle[]> {
8
+ const content = await fs.readFile(filePath, 'utf8');
9
+ const articles: ParsedArticle[] = [];
11
10
 
12
11
  // Split by article separators (---)
13
12
  const sections = content.split(/^---\s*$/gm).filter(section => section.trim());
@@ -27,34 +26,37 @@ function parseAkbFile(filePath) {
27
26
 
28
27
  /**
29
28
  * Parse individual article section
30
- * @param {Array} lines - Lines of the article section
31
- * @returns {Object|null} Parsed article object
32
29
  */
33
- function parseArticleSection(lines) {
34
- let topicName = '';
35
- let category = '';
36
- let summary = '';
37
- let keywords = '';
38
- let topicSummary = '';
30
+ function parseArticleSection(lines: readonly string[]): ParsedArticle | null {
31
+ const state = {
32
+ topicName: '',
33
+ category: '',
34
+ summary: '',
35
+ keywords: '',
36
+ topicSummary: ''
37
+ };
39
38
 
40
39
  // Find topic name (# r001)
41
40
  const topicLine = lines.find(line => line.match(/^#\s+r\d+/));
42
- if (!topicLine) return null;
41
+ if (!topicLine) {
42
+ console.warn('No topic line found in section');
43
+ return null;
44
+ }
43
45
 
44
- topicName = topicLine.replace(/^#\s+/, '').trim();
46
+ state.topicName = topicLine.replace(/^#\s+/, '').trim();
45
47
 
46
48
  // Extract category/subcategory/description (first ## line)
47
49
  const categoryLine = lines.find(line => line.startsWith('## ') && line.includes(' / '));
48
50
  if (categoryLine) {
49
- category = categoryLine.replace(/^##\s+/, '').trim();
51
+ state.category = categoryLine.replace(/^##\s+/, '').trim();
50
52
  }
51
53
 
52
54
  // Extract summary (second ## line)
53
55
  const summaryLineIndex = lines.findIndex(line => line.startsWith('## ') && line.includes(' / '));
54
56
  if (summaryLineIndex >= 0 && summaryLineIndex + 1 < lines.length) {
55
57
  const nextLine = lines[summaryLineIndex + 1];
56
- if (nextLine.startsWith('## ') && !nextLine.includes(' / ')) {
57
- summary = nextLine.replace(/^##\s+/, '').trim();
58
+ if (nextLine && nextLine.startsWith('## ') && !nextLine.includes(' / ')) {
59
+ state.summary = nextLine.replace(/^##\s+/, '').trim();
58
60
  }
59
61
  }
60
62
 
@@ -63,7 +65,10 @@ function parseArticleSection(lines) {
63
65
  index > summaryLineIndex + 1 && line.startsWith('## ') && !line.includes(' / ')
64
66
  );
65
67
  if (keywordsLineIndex >= 0) {
66
- keywords = lines[keywordsLineIndex].replace(/^##\s+/, '').trim();
68
+ const keywordsLine = lines[keywordsLineIndex];
69
+ if (keywordsLine) {
70
+ state.keywords = keywordsLine.replace(/^##\s+/, '').trim();
71
+ }
67
72
  }
68
73
 
69
74
  // Extract category content
@@ -72,41 +77,32 @@ function parseArticleSection(lines) {
72
77
 
73
78
  if (categoryStartIndex >= 0 && categoryEndIndex >= 0) {
74
79
  const categoryLines = lines.slice(categoryStartIndex, categoryEndIndex + 1);
75
- topicSummary = categoryLines.join('\n');
80
+ state.topicSummary = categoryLines.join('\n');
76
81
  }
77
82
 
78
83
  // Create topic_facts array
79
- const topicFacts = [
80
- category,
81
- summary,
82
- keywords
83
- ].filter(fact => fact.trim() !== '');
84
+ const topicFacts = [state.category, state.summary, state.keywords].filter(fact => fact.trim() !== '');
84
85
 
85
86
  return {
86
- topic_name: category, // Use the descriptive title as topic_name
87
+ topic_name: state.category, // Use the descriptive title as topic_name
87
88
  persona_id: null, // Will be set when importing
88
- topic_summary: topicSummary,
89
+ topic_summary: state.topicSummary,
89
90
  topic_facts: topicFacts,
90
91
  confidence: 100,
91
- source: topicName, // Use the ID (r001) as source
92
- labels: ["rag_context"]
92
+ source: state.topicName, // Use the ID (r001) as source
93
+ labels: ['rag_context']
93
94
  };
94
95
  }
95
96
 
96
97
  /**
97
98
  * Convert parsed articles to API format for bulk import
98
- * @param {Array} articles - Parsed articles
99
- * @param {string} personaId - Target persona ID
100
- * @returns {Array} Array of articles ready for API import
101
99
  */
102
- function prepareArticlesForImport(articles, personaId) {
100
+ export function prepareArticlesForImport(
101
+ articles: ParsedArticle[],
102
+ personaId: string
103
+ ): AkbImportArticle[] {
103
104
  return articles.map(article => ({
104
105
  ...article,
105
106
  persona_id: personaId
106
107
  }));
107
- }
108
-
109
- export {
110
- parseAkbFile,
111
- prepareArticlesForImport
112
- };
108
+ }
package/src/api.ts ADDED
@@ -0,0 +1,130 @@
1
+ import axios, { type AxiosInstance, type InternalAxiosRequestConfig, type AxiosResponse, type AxiosError } from 'axios';
2
+ import { getValidAccessToken, forceReauth } from './auth.js';
3
+ import { ENV } from './env.js';
4
+ import type {
5
+ ProjectMeta,
6
+ Agent,
7
+ Skill,
8
+ FlowEvent,
9
+ FlowState,
10
+ AkbImportArticle,
11
+ CustomerProfile
12
+ } from './types.js';
13
+
14
+ // Per-request retry tracking to avoid shared state issues
15
+ const RETRY_SYMBOL = Symbol('retried');
16
+
17
+ export async function makeClient(verbose: boolean = false, token?: string): Promise<AxiosInstance> {
18
+ let accessToken = token || await getValidAccessToken();
19
+ if (verbose) console.log('✓ Access token obtained');
20
+
21
+ const client = axios.create({
22
+ baseURL: ENV.NEWO_BASE_URL,
23
+ headers: { accept: 'application/json' }
24
+ });
25
+
26
+ client.interceptors.request.use(async (config: InternalAxiosRequestConfig) => {
27
+ config.headers = config.headers || {};
28
+ config.headers.Authorization = `Bearer ${accessToken}`;
29
+
30
+ if (verbose) {
31
+ console.log(`→ ${config.method?.toUpperCase()} ${config.url}`);
32
+ if (config.data) console.log(' Data:', JSON.stringify(config.data, null, 2));
33
+ if (config.params) console.log(' Params:', config.params);
34
+ }
35
+
36
+ return config;
37
+ });
38
+
39
+ client.interceptors.response.use(
40
+ (response: AxiosResponse) => {
41
+ if (verbose) {
42
+ console.log(`← ${response.status} ${response.config.method?.toUpperCase()} ${response.config.url}`);
43
+ if (response.data && Object.keys(response.data).length < 20) {
44
+ console.log(' Response:', JSON.stringify(response.data, null, 2));
45
+ } else if (response.data) {
46
+ const itemCount = Array.isArray(response.data) ? response.data.length : Object.keys(response.data).length;
47
+ console.log(` Response: [${typeof response.data}] ${Array.isArray(response.data) ? itemCount + ' items' : 'large object'}`);
48
+ }
49
+ }
50
+ return response;
51
+ },
52
+ async (error: AxiosError) => {
53
+ const status = error?.response?.status;
54
+ if (verbose) {
55
+ console.log(`← ${status} ${error.config?.method?.toUpperCase()} ${error.config?.url} - ${error.message}`);
56
+ if (error.response?.data) console.log(' Error data:', error.response.data);
57
+ }
58
+
59
+ // Use per-request retry tracking to avoid shared state issues
60
+ const config = error.config as InternalAxiosRequestConfig & { [RETRY_SYMBOL]?: boolean };
61
+
62
+ if (status === 401 && !config?.[RETRY_SYMBOL]) {
63
+ if (config) {
64
+ config[RETRY_SYMBOL] = true;
65
+ if (verbose) console.log('🔄 Retrying with fresh token...');
66
+ accessToken = await forceReauth();
67
+
68
+ config.headers = config.headers || {};
69
+ config.headers.Authorization = `Bearer ${accessToken}`;
70
+ return client.request(config);
71
+ }
72
+ }
73
+
74
+ throw error;
75
+ }
76
+ );
77
+
78
+ return client;
79
+ }
80
+
81
+ export async function listProjects(client: AxiosInstance): Promise<ProjectMeta[]> {
82
+ const response = await client.get<ProjectMeta[]>('/api/v1/designer/projects');
83
+ return response.data;
84
+ }
85
+
86
+ export async function listAgents(client: AxiosInstance, projectId: string): Promise<Agent[]> {
87
+ const response = await client.get<Agent[]>('/api/v1/bff/agents/list', {
88
+ params: { project_id: projectId }
89
+ });
90
+ return response.data;
91
+ }
92
+
93
+ export async function getProjectMeta(client: AxiosInstance, projectId: string): Promise<ProjectMeta> {
94
+ const response = await client.get<ProjectMeta>(`/api/v1/designer/projects/by-id/${projectId}`);
95
+ return response.data;
96
+ }
97
+
98
+ export async function listFlowSkills(client: AxiosInstance, flowId: string): Promise<Skill[]> {
99
+ const response = await client.get<Skill[]>(`/api/v1/designer/flows/${flowId}/skills`);
100
+ return response.data;
101
+ }
102
+
103
+ export async function getSkill(client: AxiosInstance, skillId: string): Promise<Skill> {
104
+ const response = await client.get<Skill>(`/api/v1/designer/skills/${skillId}`);
105
+ return response.data;
106
+ }
107
+
108
+ export async function updateSkill(client: AxiosInstance, skillObject: Skill): Promise<void> {
109
+ await client.put(`/api/v1/designer/flows/skills/${skillObject.id}`, skillObject);
110
+ }
111
+
112
+ export async function listFlowEvents(client: AxiosInstance, flowId: string): Promise<FlowEvent[]> {
113
+ const response = await client.get<FlowEvent[]>(`/api/v1/designer/flows/${flowId}/events`);
114
+ return response.data;
115
+ }
116
+
117
+ export async function listFlowStates(client: AxiosInstance, flowId: string): Promise<FlowState[]> {
118
+ const response = await client.get<FlowState[]>(`/api/v1/designer/flows/${flowId}/states`);
119
+ return response.data;
120
+ }
121
+
122
+ export async function importAkbArticle(client: AxiosInstance, articleData: AkbImportArticle): Promise<unknown> {
123
+ const response = await client.post('/api/v1/akb/append-manual', articleData);
124
+ return response.data;
125
+ }
126
+
127
+ export async function getCustomerProfile(client: AxiosInstance): Promise<CustomerProfile> {
128
+ const response = await client.get<CustomerProfile>('/api/v1/customer/profile');
129
+ return response.data;
130
+ }
package/src/auth.ts ADDED
@@ -0,0 +1,415 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import axios, { AxiosError } from 'axios';
4
+ import { ENV } from './env.js';
5
+ import { customerStateDir } from './fsutil.js';
6
+ import type { TokenResponse, StoredTokens, CustomerConfig } from './types.js';
7
+
8
+ const STATE_DIR = path.join(process.cwd(), '.newo');
9
+
10
+ // Constants for validation and timeouts
11
+ const API_KEY_MIN_LENGTH = 10;
12
+ const TOKEN_MIN_LENGTH = 20;
13
+ const REQUEST_TIMEOUT = 30000; // 30 seconds
14
+ const TOKEN_EXPIRY_BUFFER = 60000; // 1 minute buffer for token expiry
15
+
16
+ // Validation functions
17
+ function validateApiKey(apiKey: string, customerIdn?: string): void {
18
+ if (!apiKey || typeof apiKey !== 'string') {
19
+ throw new Error(`Invalid API key format${customerIdn ? ` for customer ${customerIdn}` : ''}: must be a non-empty string`);
20
+ }
21
+ if (apiKey.length < API_KEY_MIN_LENGTH) {
22
+ throw new Error(`API key too short${customerIdn ? ` for customer ${customerIdn}` : ''}: minimum ${API_KEY_MIN_LENGTH} characters required`);
23
+ }
24
+ if (apiKey.includes(' ') || apiKey.includes('\n') || apiKey.includes('\t')) {
25
+ throw new Error(`Invalid API key format${customerIdn ? ` for customer ${customerIdn}` : ''}: contains invalid characters`);
26
+ }
27
+ }
28
+
29
+ function validateTokens(tokens: StoredTokens): void {
30
+ if (!tokens.access_token || typeof tokens.access_token !== 'string' || tokens.access_token.length < TOKEN_MIN_LENGTH) {
31
+ throw new Error('Invalid access token format: must be a non-empty string with minimum length');
32
+ }
33
+ if (tokens.refresh_token && (typeof tokens.refresh_token !== 'string' || tokens.refresh_token.length < TOKEN_MIN_LENGTH)) {
34
+ throw new Error('Invalid refresh token format: must be a non-empty string with minimum length');
35
+ }
36
+ if (tokens.expires_at && (typeof tokens.expires_at !== 'number' || tokens.expires_at <= 0)) {
37
+ throw new Error('Invalid token expiry: must be a positive number');
38
+ }
39
+ }
40
+
41
+ function validateUrl(url: string, name: string): void {
42
+ if (!url || typeof url !== 'string') {
43
+ throw new Error(`${name} must be a non-empty string`);
44
+ }
45
+ try {
46
+ new URL(url);
47
+ } catch {
48
+ throw new Error(`${name} must be a valid URL format`);
49
+ }
50
+ if (!url.startsWith('https://') && !url.startsWith('http://')) {
51
+ throw new Error(`${name} must use HTTP or HTTPS protocol`);
52
+ }
53
+ }
54
+
55
+ // Enhanced logging function
56
+ function logAuthEvent(level: 'info' | 'warn' | 'error', message: string, meta?: Record<string, unknown>): void {
57
+ const timestamp = new Date().toISOString();
58
+ const logEntry = {
59
+ timestamp,
60
+ level,
61
+ module: 'auth',
62
+ message,
63
+ ...meta
64
+ };
65
+
66
+ // Sanitize sensitive data
67
+ const sanitized = JSON.parse(JSON.stringify(logEntry, (key, value) => {
68
+ if (typeof key === 'string' && (key.toLowerCase().includes('key') || key.toLowerCase().includes('token') || key.toLowerCase().includes('secret'))) {
69
+ return typeof value === 'string' ? `${value.slice(0, 8)}...` : value;
70
+ }
71
+ return value;
72
+ }));
73
+
74
+ if (level === 'error') {
75
+ console.error(JSON.stringify(sanitized));
76
+ } else if (level === 'warn') {
77
+ console.warn(JSON.stringify(sanitized));
78
+ } else {
79
+ console.log(JSON.stringify(sanitized));
80
+ }
81
+ }
82
+
83
+ // Enhanced error handling for network requests
84
+ function handleNetworkError(error: unknown, operation: string, customerIdn?: string): never {
85
+ const customerInfo = customerIdn ? ` for customer ${customerIdn}` : '';
86
+
87
+ if (error instanceof AxiosError) {
88
+ const statusCode = error.response?.status;
89
+ const responseData = error.response?.data;
90
+
91
+ if (statusCode === 401) {
92
+ throw new Error(`Authentication failed${customerInfo}: Invalid API key or credentials`);
93
+ } else if (statusCode === 403) {
94
+ throw new Error(`Access forbidden${customerInfo}: Insufficient permissions`);
95
+ } else if (statusCode === 429) {
96
+ throw new Error(`Rate limit exceeded${customerInfo}: Please try again later`);
97
+ } else if (statusCode && statusCode >= 500) {
98
+ throw new Error(`Server error${customerInfo}: The NEWO service is temporarily unavailable (${statusCode})`);
99
+ } else if (error.code === 'ECONNREFUSED') {
100
+ throw new Error(`Connection refused${customerInfo}: Cannot reach NEWO service`);
101
+ } else if (error.code === 'ETIMEDOUT' || error.code === 'ENOTFOUND') {
102
+ throw new Error(`Network timeout${customerInfo}: Check your internet connection`);
103
+ } else {
104
+ throw new Error(`Network error during ${operation}${customerInfo}: ${error.message}${responseData ? ` - ${JSON.stringify(responseData)}` : ''}`);
105
+ }
106
+ }
107
+
108
+ throw new Error(`Failed to ${operation}${customerInfo}: ${error instanceof Error ? error.message : String(error)}`);
109
+ }
110
+
111
+ function tokensPath(customerIdn?: string): string {
112
+ if (customerIdn) {
113
+ return path.join(customerStateDir(customerIdn), 'tokens.json');
114
+ }
115
+ return path.join(STATE_DIR, 'tokens.json'); // Legacy path
116
+ }
117
+
118
+ async function saveTokens(tokens: StoredTokens, customerIdn?: string): Promise<void> {
119
+ try {
120
+ validateTokens(tokens);
121
+
122
+ const filePath = tokensPath(customerIdn);
123
+ await fs.ensureDir(path.dirname(filePath));
124
+ await fs.writeJson(filePath, tokens, { spaces: 2 });
125
+
126
+ logAuthEvent('info', 'Tokens saved successfully', {
127
+ customerIdn: customerIdn || 'legacy',
128
+ expiresAt: tokens.expires_at ? new Date(tokens.expires_at).toISOString() : undefined,
129
+ hasRefreshToken: !!tokens.refresh_token
130
+ });
131
+ } catch (error: unknown) {
132
+ logAuthEvent('error', 'Failed to save tokens', {
133
+ customerIdn: customerIdn || 'legacy',
134
+ error: error instanceof Error ? error.message : String(error)
135
+ });
136
+ throw new Error(`Failed to save authentication tokens${customerIdn ? ` for customer ${customerIdn}` : ''}: ${error instanceof Error ? error.message : String(error)}`);
137
+ }
138
+ }
139
+
140
+ async function loadTokens(customerIdn?: string): Promise<StoredTokens | null> {
141
+ try {
142
+ const filePath = tokensPath(customerIdn);
143
+ if (await fs.pathExists(filePath)) {
144
+ const tokens = await fs.readJson(filePath) as StoredTokens;
145
+
146
+ // Validate loaded tokens
147
+ try {
148
+ validateTokens(tokens);
149
+ } catch (validationError: unknown) {
150
+ logAuthEvent('warn', 'Loaded tokens failed validation, will regenerate', {
151
+ customerIdn: customerIdn || 'legacy',
152
+ error: validationError instanceof Error ? validationError.message : String(validationError)
153
+ });
154
+ return null; // Force token regeneration
155
+ }
156
+
157
+ logAuthEvent('info', 'Tokens loaded successfully', {
158
+ customerIdn: customerIdn || 'legacy',
159
+ expiresAt: tokens.expires_at ? new Date(tokens.expires_at).toISOString() : undefined,
160
+ hasRefreshToken: !!tokens.refresh_token
161
+ });
162
+
163
+ return tokens;
164
+ }
165
+ } catch (error: unknown) {
166
+ logAuthEvent('warn', 'Failed to load tokens from file', {
167
+ customerIdn: customerIdn || 'legacy',
168
+ error: error instanceof Error ? error.message : String(error)
169
+ });
170
+ }
171
+
172
+ // Fallback to environment tokens for legacy mode or bootstrap
173
+ if (!customerIdn && (ENV.NEWO_ACCESS_TOKEN || ENV.NEWO_REFRESH_TOKEN)) {
174
+ const tokens: StoredTokens = {
175
+ access_token: ENV.NEWO_ACCESS_TOKEN || '',
176
+ refresh_token: ENV.NEWO_REFRESH_TOKEN || '',
177
+ expires_at: Date.now() + 10 * 60 * 1000
178
+ };
179
+ await saveTokens(tokens);
180
+ return tokens;
181
+ }
182
+
183
+ return null;
184
+ }
185
+
186
+ function isExpired(tokens: StoredTokens | null): boolean {
187
+ if (!tokens?.expires_at) {
188
+ logAuthEvent('warn', 'Token has no expiry time, treating as expired');
189
+ return true;
190
+ }
191
+
192
+ const currentTime = Date.now();
193
+ const expiryTime = tokens.expires_at;
194
+ const timeUntilExpiry = expiryTime - currentTime;
195
+
196
+ if (timeUntilExpiry <= TOKEN_EXPIRY_BUFFER) {
197
+ logAuthEvent('info', 'Token is expired or expires soon', {
198
+ expiresAt: new Date(expiryTime).toISOString(),
199
+ timeUntilExpiry: Math.round(timeUntilExpiry / 1000)
200
+ });
201
+ return true;
202
+ }
203
+
204
+ return false;
205
+ }
206
+
207
+ function normalizeTokenResponse(tokenResponse: TokenResponse): { access: string; refresh: string; expiresInSec: number } {
208
+ const access = tokenResponse.access_token || tokenResponse.token || tokenResponse.accessToken;
209
+ const refresh = tokenResponse.refresh_token || tokenResponse.refreshToken || '';
210
+ const expiresInSec = tokenResponse.expires_in || tokenResponse.expiresIn || 3600;
211
+
212
+ if (!access) {
213
+ throw new Error('Invalid token response: missing access token');
214
+ }
215
+
216
+ return { access, refresh, expiresInSec };
217
+ }
218
+
219
+ export async function exchangeApiKeyForToken(customer?: CustomerConfig): Promise<StoredTokens> {
220
+ const apiKey = customer?.apiKey || ENV.NEWO_API_KEY;
221
+ const customerIdn = customer?.idn;
222
+
223
+ // Validate inputs
224
+ if (!apiKey) {
225
+ throw new Error(customer
226
+ ? `API key not set for customer ${customer.idn}. Set NEWO_CUSTOMER_${customer.idn.toUpperCase()}_API_KEY in your environment`
227
+ : 'NEWO_API_KEY not set. Provide an API key in .env file'
228
+ );
229
+ }
230
+
231
+ validateApiKey(apiKey, customerIdn);
232
+ validateUrl(ENV.NEWO_BASE_URL, 'NEWO_BASE_URL');
233
+
234
+ logAuthEvent('info', 'Exchanging API key for tokens', { customerIdn: customerIdn || 'legacy' });
235
+
236
+ try {
237
+ const url = `${ENV.NEWO_BASE_URL}/api/v1/auth/api-key/token`;
238
+ const response = await axios.post<TokenResponse>(
239
+ url,
240
+ {},
241
+ {
242
+ timeout: REQUEST_TIMEOUT,
243
+ headers: {
244
+ 'x-api-key': apiKey,
245
+ 'accept': 'application/json',
246
+ 'user-agent': 'newo-cli/1.5.0'
247
+ }
248
+ }
249
+ );
250
+
251
+ if (!response.data) {
252
+ throw new Error('Empty response from token exchange endpoint');
253
+ }
254
+
255
+ const { access, refresh, expiresInSec } = normalizeTokenResponse(response.data);
256
+
257
+ const tokens: StoredTokens = {
258
+ access_token: access,
259
+ refresh_token: refresh,
260
+ expires_at: Date.now() + expiresInSec * 1000
261
+ };
262
+
263
+ // Validate tokens before saving
264
+ validateTokens(tokens);
265
+
266
+ await saveTokens(tokens, customerIdn);
267
+
268
+ logAuthEvent('info', 'API key exchange completed successfully', {
269
+ customerIdn: customerIdn || 'legacy',
270
+ expiresAt: new Date(tokens.expires_at).toISOString()
271
+ });
272
+
273
+ return tokens;
274
+ } catch (error: unknown) {
275
+ logAuthEvent('error', 'API key exchange failed', {
276
+ customerIdn: customerIdn || 'legacy',
277
+ error: error instanceof Error ? error.message : String(error)
278
+ });
279
+ handleNetworkError(error, 'exchange API key for token', customerIdn);
280
+ }
281
+ }
282
+
283
+ export async function refreshWithEndpoint(refreshToken: string, customer?: CustomerConfig): Promise<StoredTokens> {
284
+ const customerIdn = customer?.idn;
285
+
286
+ // Validate inputs
287
+ if (!ENV.NEWO_REFRESH_URL) {
288
+ throw new Error('NEWO_REFRESH_URL not set in environment');
289
+ }
290
+ if (!refreshToken || typeof refreshToken !== 'string' || refreshToken.length < TOKEN_MIN_LENGTH) {
291
+ throw new Error(`Invalid refresh token${customerIdn ? ` for customer ${customerIdn}` : ''}: must be a non-empty string with minimum length`);
292
+ }
293
+
294
+ validateUrl(ENV.NEWO_REFRESH_URL, 'NEWO_REFRESH_URL');
295
+
296
+ logAuthEvent('info', 'Refreshing tokens using refresh endpoint', { customerIdn: customerIdn || 'legacy' });
297
+
298
+ try {
299
+ const response = await axios.post<TokenResponse>(
300
+ ENV.NEWO_REFRESH_URL,
301
+ { refresh_token: refreshToken },
302
+ {
303
+ timeout: REQUEST_TIMEOUT,
304
+ headers: {
305
+ 'accept': 'application/json',
306
+ 'user-agent': 'newo-cli/1.5.0'
307
+ }
308
+ }
309
+ );
310
+
311
+ if (!response.data) {
312
+ throw new Error('Empty response from token refresh endpoint');
313
+ }
314
+
315
+ const { access, expiresInSec } = normalizeTokenResponse(response.data);
316
+ const refresh = response.data.refresh_token || response.data.refreshToken || refreshToken;
317
+
318
+ const tokens: StoredTokens = {
319
+ access_token: access,
320
+ refresh_token: refresh,
321
+ expires_at: Date.now() + expiresInSec * 1000
322
+ };
323
+
324
+ // Validate tokens before saving
325
+ validateTokens(tokens);
326
+
327
+ await saveTokens(tokens, customerIdn);
328
+
329
+ logAuthEvent('info', 'Token refresh completed successfully', {
330
+ customerIdn: customerIdn || 'legacy',
331
+ expiresAt: new Date(tokens.expires_at).toISOString()
332
+ });
333
+
334
+ return tokens;
335
+ } catch (error: unknown) {
336
+ logAuthEvent('error', 'Token refresh failed', {
337
+ customerIdn: customerIdn || 'legacy',
338
+ error: error instanceof Error ? error.message : String(error)
339
+ });
340
+ handleNetworkError(error, 'refresh token', customerIdn);
341
+ }
342
+ }
343
+
344
+ export async function getValidAccessToken(customer?: CustomerConfig): Promise<string> {
345
+ const customerIdn = customer?.idn;
346
+
347
+ logAuthEvent('info', 'Getting valid access token', { customerIdn: customerIdn || 'legacy' });
348
+
349
+ try {
350
+ let tokens = await loadTokens(customerIdn);
351
+
352
+ // No tokens found, exchange API key
353
+ if (!tokens || !tokens.access_token) {
354
+ logAuthEvent('info', 'No existing tokens found, exchanging API key', { customerIdn: customerIdn || 'legacy' });
355
+ tokens = await exchangeApiKeyForToken(customer);
356
+ return tokens.access_token;
357
+ }
358
+
359
+ // Tokens are valid and not expired
360
+ if (!isExpired(tokens)) {
361
+ logAuthEvent('info', 'Using existing valid access token', { customerIdn: customerIdn || 'legacy' });
362
+ return tokens.access_token;
363
+ }
364
+
365
+ // Try to refresh if refresh URL and token available
366
+ if (ENV.NEWO_REFRESH_URL && tokens.refresh_token) {
367
+ try {
368
+ logAuthEvent('info', 'Attempting to refresh expired token', { customerIdn: customerIdn || 'legacy' });
369
+ tokens = await refreshWithEndpoint(tokens.refresh_token, customer);
370
+ return tokens.access_token;
371
+ } catch (error: unknown) {
372
+ const message = error instanceof Error ? error.message : String(error);
373
+ logAuthEvent('warn', 'Token refresh failed, falling back to API key exchange', {
374
+ customerIdn: customerIdn || 'legacy',
375
+ error: message
376
+ });
377
+ }
378
+ } else {
379
+ logAuthEvent('info', 'No refresh endpoint or refresh token available, using API key exchange', {
380
+ customerIdn: customerIdn || 'legacy'
381
+ });
382
+ }
383
+
384
+ // Fallback to API key exchange
385
+ tokens = await exchangeApiKeyForToken(customer);
386
+ return tokens.access_token;
387
+ } catch (error: unknown) {
388
+ logAuthEvent('error', 'Failed to get valid access token', {
389
+ customerIdn: customerIdn || 'legacy',
390
+ error: error instanceof Error ? error.message : String(error)
391
+ });
392
+ throw new Error(`Unable to obtain valid access token${customerIdn ? ` for customer ${customerIdn}` : ''}: ${error instanceof Error ? error.message : String(error)}`);
393
+ }
394
+ }
395
+
396
+ export async function forceReauth(customer?: CustomerConfig): Promise<string> {
397
+ const customerIdn = customer?.idn;
398
+
399
+ logAuthEvent('info', 'Forcing re-authentication', { customerIdn: customerIdn || 'legacy' });
400
+
401
+ try {
402
+ const tokens = await exchangeApiKeyForToken(customer);
403
+ logAuthEvent('info', 'Forced re-authentication completed successfully', {
404
+ customerIdn: customerIdn || 'legacy',
405
+ expiresAt: new Date(tokens.expires_at).toISOString()
406
+ });
407
+ return tokens.access_token;
408
+ } catch (error: unknown) {
409
+ logAuthEvent('error', 'Forced re-authentication failed', {
410
+ customerIdn: customerIdn || 'legacy',
411
+ error: error instanceof Error ? error.message : String(error)
412
+ });
413
+ throw error;
414
+ }
415
+ }