@zhafron/opencode-kiro-auth 1.0.0

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.
Files changed (110) hide show
  1. package/README.md +85 -0
  2. package/dist/constants.d.ts +26 -0
  3. package/dist/constants.js +60 -0
  4. package/dist/index.d.ts +3 -0
  5. package/dist/index.js +1 -0
  6. package/dist/kiro/auth.d.ts +5 -0
  7. package/dist/kiro/auth.js +24 -0
  8. package/dist/kiro/oauth-idc.d.ts +24 -0
  9. package/dist/kiro/oauth-idc.js +132 -0
  10. package/dist/kiro/oauth-social.d.ts +17 -0
  11. package/dist/kiro/oauth-social.js +51 -0
  12. package/dist/plugin/accounts.d.ts +28 -0
  13. package/dist/plugin/accounts.js +156 -0
  14. package/dist/plugin/auth-page.d.ts +3 -0
  15. package/dist/plugin/auth-page.js +568 -0
  16. package/dist/plugin/cli.d.ts +6 -0
  17. package/dist/plugin/cli.js +98 -0
  18. package/dist/plugin/config/index.d.ts +3 -0
  19. package/dist/plugin/config/index.js +2 -0
  20. package/dist/plugin/config/loader.d.ts +6 -0
  21. package/dist/plugin/config/loader.js +125 -0
  22. package/dist/plugin/config/schema.d.ts +44 -0
  23. package/dist/plugin/config/schema.js +28 -0
  24. package/dist/plugin/debug.d.ts +2 -0
  25. package/dist/plugin/debug.js +9 -0
  26. package/dist/plugin/errors.d.ts +17 -0
  27. package/dist/plugin/errors.js +34 -0
  28. package/dist/plugin/logger.d.ts +4 -0
  29. package/dist/plugin/logger.js +37 -0
  30. package/dist/plugin/models.d.ts +3 -0
  31. package/dist/plugin/models.js +14 -0
  32. package/dist/plugin/oauth-parser.d.ts +5 -0
  33. package/dist/plugin/oauth-parser.js +23 -0
  34. package/dist/plugin/quota.d.ts +15 -0
  35. package/dist/plugin/quota.js +68 -0
  36. package/dist/plugin/recovery.d.ts +19 -0
  37. package/dist/plugin/recovery.js +302 -0
  38. package/dist/plugin/refresh-queue.d.ts +14 -0
  39. package/dist/plugin/refresh-queue.js +69 -0
  40. package/dist/plugin/request.d.ts +4 -0
  41. package/dist/plugin/request.js +240 -0
  42. package/dist/plugin/response.d.ts +6 -0
  43. package/dist/plugin/response.js +246 -0
  44. package/dist/plugin/server.d.ts +24 -0
  45. package/dist/plugin/server.js +96 -0
  46. package/dist/plugin/storage.d.ts +7 -0
  47. package/dist/plugin/storage.js +75 -0
  48. package/dist/plugin/streaming.d.ts +3 -0
  49. package/dist/plugin/streaming.js +503 -0
  50. package/dist/plugin/token.d.ts +2 -0
  51. package/dist/plugin/token.js +56 -0
  52. package/dist/plugin/types.d.ts +148 -0
  53. package/dist/plugin/types.js +0 -0
  54. package/dist/plugin/usage.d.ts +3 -0
  55. package/dist/plugin/usage.js +36 -0
  56. package/dist/plugin.d.ts +32 -0
  57. package/dist/plugin.js +222 -0
  58. package/dist/src/constants.d.ts +22 -0
  59. package/dist/src/constants.js +35 -0
  60. package/dist/src/kiro/auth.d.ts +5 -0
  61. package/dist/src/kiro/auth.js +69 -0
  62. package/dist/src/kiro/oauth-idc.d.ts +22 -0
  63. package/dist/src/kiro/oauth-idc.js +99 -0
  64. package/dist/src/kiro/oauth-social.d.ts +17 -0
  65. package/dist/src/kiro/oauth-social.js +69 -0
  66. package/dist/src/plugin/accounts.d.ts +23 -0
  67. package/dist/src/plugin/accounts.js +265 -0
  68. package/dist/src/plugin/cli.d.ts +6 -0
  69. package/dist/src/plugin/cli.js +98 -0
  70. package/dist/src/plugin/config/index.d.ts +3 -0
  71. package/dist/src/plugin/config/index.js +2 -0
  72. package/dist/src/plugin/config/loader.d.ts +7 -0
  73. package/dist/src/plugin/config/loader.js +143 -0
  74. package/dist/src/plugin/config/schema.d.ts +68 -0
  75. package/dist/src/plugin/config/schema.js +44 -0
  76. package/dist/src/plugin/debug.d.ts +2 -0
  77. package/dist/src/plugin/debug.js +9 -0
  78. package/dist/src/plugin/errors.d.ts +17 -0
  79. package/dist/src/plugin/errors.js +34 -0
  80. package/dist/src/plugin/logger.d.ts +4 -0
  81. package/dist/src/plugin/logger.js +17 -0
  82. package/dist/src/plugin/models.d.ts +3 -0
  83. package/dist/src/plugin/models.js +14 -0
  84. package/dist/src/plugin/oauth-parser.d.ts +5 -0
  85. package/dist/src/plugin/oauth-parser.js +23 -0
  86. package/dist/src/plugin/quota.d.ts +25 -0
  87. package/dist/src/plugin/quota.js +175 -0
  88. package/dist/src/plugin/recovery.d.ts +19 -0
  89. package/dist/src/plugin/recovery.js +302 -0
  90. package/dist/src/plugin/refresh-queue.d.ts +14 -0
  91. package/dist/src/plugin/refresh-queue.js +69 -0
  92. package/dist/src/plugin/request.d.ts +35 -0
  93. package/dist/src/plugin/request.js +411 -0
  94. package/dist/src/plugin/response.d.ts +6 -0
  95. package/dist/src/plugin/response.js +246 -0
  96. package/dist/src/plugin/server.d.ts +10 -0
  97. package/dist/src/plugin/server.js +203 -0
  98. package/dist/src/plugin/storage.d.ts +5 -0
  99. package/dist/src/plugin/storage.js +106 -0
  100. package/dist/src/plugin/streaming.d.ts +12 -0
  101. package/dist/src/plugin/streaming.js +444 -0
  102. package/dist/src/plugin/token.d.ts +8 -0
  103. package/dist/src/plugin/token.js +130 -0
  104. package/dist/src/plugin/types.d.ts +144 -0
  105. package/dist/src/plugin/types.js +0 -0
  106. package/dist/src/plugin/usage.d.ts +28 -0
  107. package/dist/src/plugin/usage.js +159 -0
  108. package/dist/src/plugin.d.ts +2 -0
  109. package/dist/src/plugin.js +341 -0
  110. package/package.json +57 -0
@@ -0,0 +1,302 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { randomBytes } from 'node:crypto';
4
+ import lockfile from 'proper-lockfile';
5
+ import { xdgConfig } from 'xdg-basedir';
6
+ import * as logger from './logger';
7
+ import { KiroTokenRefreshError, KiroQuotaExhaustedError, KiroRateLimitError, KiroAuthError } from './errors';
8
+ const LOCK_OPTIONS = {
9
+ stale: 10000,
10
+ retries: {
11
+ retries: 5,
12
+ minTimeout: 100,
13
+ maxTimeout: 1000,
14
+ factor: 2,
15
+ },
16
+ };
17
+ const MAX_ERROR_COUNT = 3;
18
+ function getRecoveryPath() {
19
+ const configDir = xdgConfig || `${process.env.HOME}/.config`;
20
+ return `${configDir}/opencode/kiro-recovery.json`;
21
+ }
22
+ async function ensureFileExists(path) {
23
+ try {
24
+ await fs.access(path);
25
+ }
26
+ catch {
27
+ await fs.mkdir(dirname(path), { recursive: true });
28
+ const defaultStorage = {
29
+ version: 1,
30
+ sessions: {},
31
+ };
32
+ await fs.writeFile(path, JSON.stringify(defaultStorage, null, 2), 'utf-8');
33
+ }
34
+ }
35
+ async function withFileLock(path, fn) {
36
+ await ensureFileExists(path);
37
+ let release = null;
38
+ try {
39
+ release = await lockfile.lock(path, LOCK_OPTIONS);
40
+ return await fn();
41
+ }
42
+ catch (error) {
43
+ logger.error('Recovery file lock operation failed', error);
44
+ throw error;
45
+ }
46
+ finally {
47
+ if (release) {
48
+ try {
49
+ await release();
50
+ }
51
+ catch (unlockError) {
52
+ logger.warn('Failed to release recovery lock', unlockError);
53
+ }
54
+ }
55
+ }
56
+ }
57
+ async function loadRecoveryState() {
58
+ const path = getRecoveryPath();
59
+ try {
60
+ await ensureFileExists(path);
61
+ const content = await fs.readFile(path, 'utf-8');
62
+ const data = JSON.parse(content);
63
+ if (data.version !== 1) {
64
+ logger.warn('Unknown recovery storage version, returning default');
65
+ return {
66
+ version: 1,
67
+ sessions: {},
68
+ };
69
+ }
70
+ if (typeof data.sessions !== 'object' || data.sessions === null) {
71
+ logger.warn('Invalid sessions object, returning default');
72
+ return {
73
+ version: 1,
74
+ sessions: {},
75
+ };
76
+ }
77
+ return data;
78
+ }
79
+ catch (error) {
80
+ const code = error.code;
81
+ if (code === 'ENOENT') {
82
+ return {
83
+ version: 1,
84
+ sessions: {},
85
+ };
86
+ }
87
+ logger.error('Failed to load recovery state', error);
88
+ return {
89
+ version: 1,
90
+ sessions: {},
91
+ };
92
+ }
93
+ }
94
+ async function saveRecoveryState(state) {
95
+ const path = getRecoveryPath();
96
+ await withFileLock(path, async () => {
97
+ const tempPath = `${path}.${randomBytes(6).toString('hex')}.tmp`;
98
+ const content = JSON.stringify(state, null, 2);
99
+ await fs.mkdir(dirname(path), { recursive: true });
100
+ await fs.writeFile(tempPath, content, 'utf-8');
101
+ await fs.rename(tempPath, path);
102
+ });
103
+ }
104
+ function isNetworkError(error) {
105
+ if (!error)
106
+ return false;
107
+ const errorCode = error.code || error.errno;
108
+ if (typeof errorCode === 'string') {
109
+ const networkCodes = [
110
+ 'ECONNRESET',
111
+ 'ECONNREFUSED',
112
+ 'ETIMEDOUT',
113
+ 'ENOTFOUND',
114
+ 'ENETUNREACH',
115
+ 'EHOSTUNREACH',
116
+ 'EPIPE',
117
+ 'EAI_AGAIN',
118
+ ];
119
+ if (networkCodes.includes(errorCode)) {
120
+ return true;
121
+ }
122
+ }
123
+ const message = error.message || error.toString?.() || '';
124
+ const lowerMessage = message.toLowerCase();
125
+ const networkPatterns = [
126
+ 'network',
127
+ 'connection',
128
+ 'timeout',
129
+ 'econnreset',
130
+ 'econnrefused',
131
+ 'socket hang up',
132
+ 'fetch failed',
133
+ ];
134
+ return networkPatterns.some(pattern => lowerMessage.includes(pattern));
135
+ }
136
+ function getStatusCode(error) {
137
+ if (!error)
138
+ return null;
139
+ if (typeof error.statusCode === 'number') {
140
+ return error.statusCode;
141
+ }
142
+ if (typeof error.status === 'number') {
143
+ return error.status;
144
+ }
145
+ if (error.response && typeof error.response.status === 'number') {
146
+ return error.response.status;
147
+ }
148
+ return null;
149
+ }
150
+ function isRecoverableStatusCode(statusCode) {
151
+ const recoverableCodes = [
152
+ 429,
153
+ 502,
154
+ 503,
155
+ 504,
156
+ ];
157
+ return recoverableCodes.includes(statusCode);
158
+ }
159
+ function isUnrecoverableStatusCode(statusCode) {
160
+ const unrecoverableCodes = [
161
+ 400,
162
+ 402,
163
+ 403,
164
+ 404,
165
+ ];
166
+ return unrecoverableCodes.includes(statusCode);
167
+ }
168
+ function isRecoverableErrorImpl(error) {
169
+ if (!error)
170
+ return false;
171
+ if (error instanceof KiroTokenRefreshError) {
172
+ return false;
173
+ }
174
+ if (error instanceof KiroQuotaExhaustedError) {
175
+ return false;
176
+ }
177
+ if (error instanceof KiroRateLimitError) {
178
+ return true;
179
+ }
180
+ if (error instanceof KiroAuthError) {
181
+ const statusCode = error.statusCode;
182
+ if (statusCode === 401) {
183
+ return true;
184
+ }
185
+ if (statusCode && isUnrecoverableStatusCode(statusCode)) {
186
+ return false;
187
+ }
188
+ return true;
189
+ }
190
+ if (isNetworkError(error)) {
191
+ return true;
192
+ }
193
+ const statusCode = getStatusCode(error);
194
+ if (statusCode !== null) {
195
+ if (isUnrecoverableStatusCode(statusCode)) {
196
+ return false;
197
+ }
198
+ if (isRecoverableStatusCode(statusCode)) {
199
+ return true;
200
+ }
201
+ }
202
+ return false;
203
+ }
204
+ function getErrorMessage(error) {
205
+ if (!error)
206
+ return 'Unknown error';
207
+ if (typeof error === 'string') {
208
+ return error;
209
+ }
210
+ if (error.message && typeof error.message === 'string') {
211
+ return error.message;
212
+ }
213
+ if (error.toString && typeof error.toString === 'function') {
214
+ return error.toString();
215
+ }
216
+ try {
217
+ return JSON.stringify(error);
218
+ }
219
+ catch {
220
+ return 'Unknown error';
221
+ }
222
+ }
223
+ export function createSessionRecoveryHook(enabled, autoResume) {
224
+ const handleSessionError = async (error, sessionId) => {
225
+ if (!enabled) {
226
+ return false;
227
+ }
228
+ if (!sessionId) {
229
+ logger.warn('No session ID provided for recovery');
230
+ return false;
231
+ }
232
+ if (!isRecoverableErrorImpl(error)) {
233
+ logger.debug('Error is not recoverable', { sessionId, error: getErrorMessage(error) });
234
+ return false;
235
+ }
236
+ try {
237
+ const storage = await loadRecoveryState();
238
+ let sessionState = storage.sessions[sessionId];
239
+ if (!sessionState) {
240
+ sessionState = {
241
+ sessionId,
242
+ conversationId: '',
243
+ model: '',
244
+ lastMessageIndex: 0,
245
+ errorCount: 1,
246
+ lastError: getErrorMessage(error),
247
+ timestamp: Date.now(),
248
+ };
249
+ }
250
+ else {
251
+ sessionState.errorCount += 1;
252
+ sessionState.lastError = getErrorMessage(error);
253
+ sessionState.timestamp = Date.now();
254
+ }
255
+ if (sessionState.errorCount > MAX_ERROR_COUNT) {
256
+ logger.warn('Session error count exceeded maximum', {
257
+ sessionId,
258
+ errorCount: sessionState.errorCount
259
+ });
260
+ delete storage.sessions[sessionId];
261
+ await saveRecoveryState(storage);
262
+ return false;
263
+ }
264
+ storage.sessions[sessionId] = sessionState;
265
+ await saveRecoveryState(storage);
266
+ logger.log('Session error recorded for recovery', {
267
+ sessionId,
268
+ errorCount: sessionState.errorCount,
269
+ shouldRetry: true
270
+ });
271
+ return true;
272
+ }
273
+ catch (storageError) {
274
+ logger.error('Failed to handle session error', storageError);
275
+ return false;
276
+ }
277
+ };
278
+ const isRecoverableError = (error) => {
279
+ return isRecoverableErrorImpl(error);
280
+ };
281
+ const clearSession = async (sessionId) => {
282
+ if (!sessionId) {
283
+ return;
284
+ }
285
+ try {
286
+ const storage = await loadRecoveryState();
287
+ if (storage.sessions[sessionId]) {
288
+ delete storage.sessions[sessionId];
289
+ await saveRecoveryState(storage);
290
+ logger.debug('Session cleared from recovery state', { sessionId });
291
+ }
292
+ }
293
+ catch (error) {
294
+ logger.error('Failed to clear session', error);
295
+ }
296
+ };
297
+ return {
298
+ handleSessionError,
299
+ isRecoverableError,
300
+ clearSession,
301
+ };
302
+ }
@@ -0,0 +1,14 @@
1
+ import type { KiroAuthDetails } from './types';
2
+ import type { AccountManager } from './accounts';
3
+ export interface ProactiveRefreshQueue {
4
+ start(): void;
5
+ stop(): void;
6
+ setAccountManager(manager: AccountManager): void;
7
+ }
8
+ export interface RefreshQueueConfig {
9
+ enabled: boolean;
10
+ checkIntervalSeconds: number;
11
+ bufferSeconds: number;
12
+ }
13
+ export declare function isTokenExpiringSoon(auth: KiroAuthDetails, bufferMs: number): boolean;
14
+ export declare function createProactiveRefreshQueue(config: RefreshQueueConfig): ProactiveRefreshQueue;
@@ -0,0 +1,69 @@
1
+ import { refreshAccessToken } from './token';
2
+ import * as logger from './logger';
3
+ export function isTokenExpiringSoon(auth, bufferMs) {
4
+ const now = Date.now();
5
+ const expiresAt = auth.expires;
6
+ const timeUntilExpiry = expiresAt - now;
7
+ return timeUntilExpiry <= bufferMs && timeUntilExpiry > 0;
8
+ }
9
+ export function createProactiveRefreshQueue(config) {
10
+ let intervalId = null;
11
+ let accountManager = null;
12
+ let isRunning = false;
13
+ async function checkAndRefresh() {
14
+ if (!accountManager) {
15
+ return;
16
+ }
17
+ try {
18
+ const accounts = accountManager.getAccounts();
19
+ const bufferMs = config.bufferSeconds * 1000;
20
+ for (const account of accounts) {
21
+ try {
22
+ const auth = accountManager.toAuthDetails(account);
23
+ if (isTokenExpiringSoon(auth, bufferMs)) {
24
+ logger.log(`[RefreshQueue] Token expiring soon for account ${account.email}, refreshing...`);
25
+ const refreshedAuth = await refreshAccessToken(auth);
26
+ accountManager.updateFromAuth(account, refreshedAuth);
27
+ await accountManager.saveToDisk();
28
+ logger.log(`[RefreshQueue] Successfully refreshed token for account ${account.email}`);
29
+ }
30
+ }
31
+ catch (error) {
32
+ logger.error(`[RefreshQueue] Failed to refresh token for account ${account.email}: ${error instanceof Error ? error.message : String(error)}`);
33
+ }
34
+ }
35
+ }
36
+ catch (error) {
37
+ logger.error(`[RefreshQueue] Error during refresh check: ${error instanceof Error ? error.message : String(error)}`);
38
+ }
39
+ }
40
+ function start() {
41
+ if (!config.enabled || isRunning) {
42
+ return;
43
+ }
44
+ const intervalMs = config.checkIntervalSeconds * 1000;
45
+ intervalId = setInterval(() => {
46
+ checkAndRefresh().catch((error) => {
47
+ logger.error(`[RefreshQueue] Unhandled error in refresh check: ${error instanceof Error ? error.message : String(error)}`);
48
+ });
49
+ }, intervalMs);
50
+ isRunning = true;
51
+ logger.log(`[RefreshQueue] Started proactive refresh queue (interval: ${config.checkIntervalSeconds}s, buffer: ${config.bufferSeconds}s)`);
52
+ }
53
+ function stop() {
54
+ if (intervalId) {
55
+ clearInterval(intervalId);
56
+ intervalId = null;
57
+ }
58
+ isRunning = false;
59
+ logger.log('[RefreshQueue] Stopped proactive refresh queue');
60
+ }
61
+ function setAccountManager(manager) {
62
+ accountManager = manager;
63
+ }
64
+ return {
65
+ start,
66
+ stop,
67
+ setAccountManager,
68
+ };
69
+ }
@@ -0,0 +1,35 @@
1
+ import type { KiroAuthDetails, PreparedRequest } from './types';
2
+ interface OpenAIMessage {
3
+ role: 'user' | 'assistant' | 'system';
4
+ content: string | Array<{
5
+ type: string;
6
+ text?: string;
7
+ image_url?: {
8
+ url: string;
9
+ };
10
+ tool_use_id?: string;
11
+ id?: string;
12
+ name?: string;
13
+ input?: unknown;
14
+ thinking?: string;
15
+ source?: {
16
+ media_type: string;
17
+ data: string;
18
+ };
19
+ }>;
20
+ }
21
+ interface OpenAITool {
22
+ name: string;
23
+ description?: string;
24
+ input_schema?: Record<string, unknown>;
25
+ }
26
+ export declare function transformToCodeWhisperer(url: string, body: string, model: string, auth: KiroAuthDetails, thinkingEnabled?: boolean, thinkingBudget?: number): PreparedRequest;
27
+ export declare function mergeAdjacentMessages(messages: OpenAIMessage[]): OpenAIMessage[];
28
+ export declare function convertToolsToCodeWhisperer(tools: OpenAITool[]): any[];
29
+ export declare function extractImagesFromContent(content: any): {
30
+ text: string;
31
+ images: any[];
32
+ };
33
+ export declare function buildUserAgent(machineId: string): string;
34
+ export declare function generateMachineId(auth: KiroAuthDetails): string;
35
+ export {};