typeclaw 0.48.3 → 0.48.4

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,6 +1,11 @@
1
1
  import { join } from 'node:path'
2
2
 
3
- import { attemptLogin as upstreamAttemptLogin, type KakaoDeviceType } from 'agent-messenger/kakaotalk'
3
+ import {
4
+ attemptLogin as upstreamAttemptLogin,
5
+ KakaoOAuthRefreshError,
6
+ type KakaoDeviceType,
7
+ refreshKakaoOAuthToken as upstreamRefreshKakaoOAuthToken,
8
+ } from 'agent-messenger/kakaotalk'
4
9
 
5
10
  import { decrypt, EncryptionError } from './encryption'
6
11
  import { SecretsKakaoCredentialStore } from './kakao-store'
@@ -15,26 +20,44 @@ export const RENEWAL_THRESHOLD_MS = 5 * 24 * 60 * 60 * 1000
15
20
  // for cron skips (host asleep, daemon respawning, etc.) and to absorb any
16
21
  // downward drift in KakaoTalk's actual TTL.
17
22
 
23
+ type ReauthDecision = {
24
+ kind: 'reauth_required'
25
+ reason: 'no_password' | 'no_email' | 'key_missing' | 'decrypt_failed'
26
+ message: string
27
+ }
28
+
29
+ type PasswordRenewalDecision =
30
+ | ReauthDecision
31
+ | { kind: 'should_renew'; method: 'password'; account: AccountSnapshot & { email: string }; password: string }
32
+
18
33
  export type RenewalDecision =
19
34
  | { kind: 'skip'; reason: 'no_account' | 'fresh_enough'; ageMs?: number }
20
- | { kind: 'reauth_required'; reason: 'no_password' | 'no_email' | 'key_missing' | 'decrypt_failed'; message: string }
21
- | { kind: 'should_renew'; account: AccountSnapshot; password: string }
35
+ | ReauthDecision
36
+ | { kind: 'should_renew'; method: 'oauth_refresh'; account: AccountSnapshot }
37
+ | PasswordRenewalDecision
22
38
 
23
39
  export type AccountSnapshot = {
24
40
  account_id: string
25
- email: string
41
+ oauth_token: string
42
+ user_id: string
43
+ refresh_token?: string
26
44
  device_uuid: string
27
45
  device_type: KakaoDeviceType
46
+ auth_method?: 'login' | 'extract'
28
47
  created_at: string
29
48
  updated_at: string
49
+ email?: string
30
50
  }
31
51
 
52
+ export type RenewalMethod = 'oauth_refresh' | 'password'
53
+
32
54
  export type RenewalAttempt =
33
- | { kind: 'ok'; account_id: string; previousUpdatedAt: string; nextUpdatedAt: string }
55
+ | { kind: 'ok'; account_id: string; previousUpdatedAt: string; nextUpdatedAt: string; method: RenewalMethod }
34
56
  | { kind: 'reauth_required'; account_id: string; reason: string; message: string }
35
57
  | { kind: 'transient_failure'; account_id: string; reason: string }
36
58
 
37
59
  export type AttemptLoginFn = typeof upstreamAttemptLogin
60
+ export type RefreshOAuthTokenFn = typeof upstreamRefreshKakaoOAuthToken
38
61
 
39
62
  export type RenewalContext = {
40
63
  containerName: string
@@ -42,6 +65,7 @@ export type RenewalContext = {
42
65
  keyStore: KeyStore
43
66
  now?: () => number
44
67
  attemptLogin?: AttemptLoginFn
68
+ refreshOAuthToken?: RefreshOAuthTokenFn
45
69
  }
46
70
 
47
71
  export async function decideRenewal(block: KakaoChannelBlock, ctx: RenewalContext): Promise<RenewalDecision> {
@@ -56,42 +80,64 @@ export async function decideRenewal(block: KakaoChannelBlock, ctx: RenewalContex
56
80
  return { kind: 'skip', reason: 'fresh_enough', ageMs }
57
81
  }
58
82
 
83
+ const snapshot = snapshotAccount(account)
84
+ if (account.refresh_token !== undefined) {
85
+ return { kind: 'should_renew', method: 'oauth_refresh', account: snapshot }
86
+ }
87
+
88
+ return decidePasswordRenewal(snapshot, account.encryptedPassword, ctx)
89
+ }
90
+
91
+ function snapshotAccount(account: KakaoChannelBlock['accounts'][string]): AccountSnapshot {
92
+ return {
93
+ account_id: account.account_id,
94
+ oauth_token: account.oauth_token,
95
+ user_id: account.user_id,
96
+ ...(account.refresh_token !== undefined ? { refresh_token: account.refresh_token } : {}),
97
+ device_uuid: account.device_uuid,
98
+ device_type: account.device_type,
99
+ ...(account.auth_method !== undefined ? { auth_method: account.auth_method } : {}),
100
+ created_at: account.created_at,
101
+ updated_at: account.updated_at,
102
+ ...(account.email !== undefined ? { email: account.email } : {}),
103
+ }
104
+ }
105
+
106
+ async function decidePasswordRenewal(
107
+ account: AccountSnapshot,
108
+ encryptedPassword: KakaoChannelBlock['accounts'][string]['encryptedPassword'],
109
+ ctx: RenewalContext,
110
+ ): Promise<PasswordRenewalDecision> {
59
111
  if (!account.email) {
60
112
  return {
61
113
  kind: 'reauth_required',
62
114
  reason: 'no_email',
63
- message: `KakaoTalk account ${accountId} has no stored email — run \`typeclaw channel reauth kakaotalk\`.`,
115
+ message: `KakaoTalk account ${account.account_id} has no stored email — run \`typeclaw channel reauth kakaotalk\`.`,
64
116
  }
65
117
  }
66
- if (!account.encryptedPassword) {
118
+ if (!encryptedPassword) {
67
119
  return {
68
120
  kind: 'reauth_required',
69
121
  reason: 'no_password',
70
- message: `KakaoTalk account ${accountId} has no stored password — run \`typeclaw channel reauth kakaotalk\`.`,
122
+ message: `KakaoTalk account ${account.account_id} has no stored password — run \`typeclaw channel reauth kakaotalk\`.`,
71
123
  }
72
124
  }
73
125
 
74
126
  let plaintextPassword: string
75
127
  try {
76
128
  const key = await ctx.keyStore.read(ctx.containerName)
77
- plaintextPassword = decrypt(account.encryptedPassword, key, {
129
+ plaintextPassword = decrypt(encryptedPassword, key, {
78
130
  containerName: ctx.containerName,
79
131
  accountId: account.account_id,
80
132
  })
81
133
  } catch (err) {
82
- return classifyDecryptFailure(err, accountId)
134
+ return classifyDecryptFailure(err, account.account_id)
83
135
  }
84
136
 
85
137
  return {
86
138
  kind: 'should_renew',
87
- account: {
88
- account_id: account.account_id,
89
- email: account.email,
90
- device_uuid: account.device_uuid,
91
- device_type: account.device_type,
92
- created_at: account.created_at,
93
- updated_at: account.updated_at,
94
- },
139
+ method: 'password',
140
+ account: { ...account, email: account.email },
95
141
  password: plaintextPassword,
96
142
  }
97
143
  }
@@ -103,7 +149,7 @@ export async function renewCurrentAccount(
103
149
  const backend = new SecretsBackend(secretsPath)
104
150
  const block = backend.readChannelsSync()?.kakaotalk
105
151
  const parsed = parseBlockOrEmpty(block)
106
- const decision = await decideRenewal(parsed, ctx)
152
+ let decision = await decideRenewal(parsed, ctx)
107
153
 
108
154
  if (decision.kind === 'skip') {
109
155
  return {
@@ -121,6 +167,62 @@ export async function renewCurrentAccount(
121
167
  }
122
168
  }
123
169
 
170
+ if (decision.method === 'oauth_refresh') {
171
+ const refreshOAuthToken = ctx.refreshOAuthToken ?? upstreamRefreshKakaoOAuthToken
172
+ try {
173
+ const refreshed = await refreshOAuthToken({
174
+ accessToken: decision.account.oauth_token,
175
+ refreshToken: decision.account.refresh_token ?? '',
176
+ deviceUuid: decision.account.device_uuid,
177
+ })
178
+ const store = new SecretsKakaoCredentialStore({ mode: 'host', secretsPath })
179
+ const nowIso = new Date().toISOString()
180
+ await store.setAccount({
181
+ account_id: decision.account.account_id,
182
+ oauth_token: refreshed.accessToken,
183
+ user_id: decision.account.user_id,
184
+ refresh_token: refreshed.refreshToken,
185
+ device_uuid: decision.account.device_uuid,
186
+ device_type: decision.account.device_type,
187
+ ...(decision.account.auth_method !== undefined ? { auth_method: decision.account.auth_method } : {}),
188
+ created_at: decision.account.created_at,
189
+ updated_at: nowIso,
190
+ })
191
+ return {
192
+ kind: 'ok',
193
+ account_id: decision.account.account_id,
194
+ previousUpdatedAt: decision.account.updated_at,
195
+ nextUpdatedAt: nowIso,
196
+ method: 'oauth_refresh',
197
+ }
198
+ } catch (err) {
199
+ // Only a rejected or incomplete refresh credential justifies the heavier
200
+ // password login. Transport/server failures keep the refresh token in
201
+ // place and retry next tick rather than risk a passcode or captcha prompt.
202
+ if (
203
+ !(err instanceof KakaoOAuthRefreshError) ||
204
+ (err.code !== 'refresh_rejected' && err.code !== 'refresh_credentials_missing')
205
+ ) {
206
+ return {
207
+ kind: 'transient_failure',
208
+ account_id: decision.account.account_id,
209
+ reason: err instanceof Error ? err.message : String(err),
210
+ }
211
+ }
212
+
213
+ const account = parsed.accounts[decision.account.account_id]
214
+ decision = await decidePasswordRenewal(decision.account, account?.encryptedPassword, ctx)
215
+ if (decision.kind === 'reauth_required') {
216
+ return {
217
+ kind: 'reauth_required',
218
+ account_id: parsed.currentAccount ?? '',
219
+ reason: decision.reason,
220
+ message: decision.message,
221
+ }
222
+ }
223
+ }
224
+ }
225
+
124
226
  const attemptLogin = ctx.attemptLogin ?? upstreamAttemptLogin
125
227
  const result = await attemptLogin(
126
228
  decision.account.email,
@@ -166,6 +268,7 @@ export async function renewCurrentAccount(
166
268
  account_id: decision.account.account_id,
167
269
  previousUpdatedAt: decision.account.updated_at,
168
270
  nextUpdatedAt: nowIso,
271
+ method: 'password',
169
272
  }
170
273
  }
171
274
 
@@ -174,7 +277,7 @@ function parseBlockOrEmpty(value: unknown): KakaoChannelBlock {
174
277
  return value as KakaoChannelBlock
175
278
  }
176
279
 
177
- function classifyDecryptFailure(err: unknown, accountId: string): RenewalDecision {
280
+ function classifyDecryptFailure(err: unknown, accountId: string): ReauthDecision {
178
281
  if (err instanceof KeyStoreError) {
179
282
  if (err.code === 'missing') {
180
283
  return {