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
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import crypto from 'node:crypto';
import { v4 as uuidv4 } from 'uuid';

// 响应数据的接口定义
interface TenantAccessTokenResponse {
    code: number;
    expire: number;
    msg: string;
    tenant_access_token: string;
}

interface EventHeader {
    event_id: string;
    token: string;
    create_time: string;
    event_type: string;
    tenant_key: string;
    app_id: string;
}

interface SenderId {
    open_id: string;
    union_id: string;
    user_id: string;
}

interface Sender {
    sender_id: SenderId;
    sender_type: string;
    tenant_key: string;
}

interface Message {
    chat_id: string;
    chat_type: string;
    content: string;
    create_time: string;
    message_id: string;
    message_type: string;
    update_time: string;
    user_agent: string;
}

interface EventBody {
    message: Message;
    sender: Sender;
}

export interface EventMessage {
    schema: string;
    header: EventHeader;
    event: EventBody;
}

/**
 * 获取飞书租户访问令牌
 * @param appId 应用 ID
 * @param appSecret 应用密钥
 * @returns Promise<TenantAccessTokenResponse>
 */
export async function getTenantAccessToken(appId: string, appSecret: string): Promise<TenantAccessTokenResponse> {
    const url = 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal';

    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            app_id: appId,
            app_secret: appSecret,
        }),
    });

    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json() as TenantAccessTokenResponse
}






//https://open.feishu.cn/document/server-docs/event-subscription-guide/event-subscription-configure-/encrypt-key-encryption-configuration-case
export class AESCipher {
    private decryptKey: Buffer;
    private encryptKey: string;
    constructor(key: string) {
        this.encryptKey = key;
        const hash = crypto.createHash('sha256');
        hash.update(key);
        this.decryptKey = hash.digest();
    }

    async decrypt(encrypt: string): Promise<string> {
        // 将 base64 字符串转换为 Uint8Array
        const encryptBuffer = Uint8Array.from(atob(encrypt), c => c.charCodeAt(0));

        // 提取 IV (前16字节)
        const iv = encryptBuffer.slice(0, 16);
        // 提取加密数据
        const data = encryptBuffer.slice(16);

        // 从密钥字符串创建 CryptoKey
        const cryptoKey = await crypto.subtle.importKey(
            'raw',
            this.decryptKey,
            { name: 'AES-CBC' },
            false,
            ['decrypt']
        );

        // 解密
        const decryptedBuffer = await crypto.subtle.decrypt(
            {
                name: 'AES-CBC',
                iv: iv
            },
            cryptoKey,
            data
        );

        // 转换为字符串
        return new TextDecoder().decode(decryptedBuffer);
    }

    calculateSignature(
        timestamp: string,
        nonce: string,
        body: string
    ): string {
        const content = timestamp + nonce + this.encryptKey + body;
        const sign = crypto.createHash('sha256').update(content).digest('hex');
        return sign;
    }
}




export async function handleAuth(request: Request,verificationToken:string,encryptKey:string ): Promise<Response | EventMessage> {

    const { headers } = request
    const contentType = headers.get('content-type') || ''
    if (request.method !== 'POST' || !contentType.includes('application/json')) {
        return new Response('Invalid request', { status: 400 })
    }
    const body: string = await request.text()
    const cipher = new AESCipher(encryptKey)
    let data = JSON.parse(body)
    // 如果是加密事件,进行解密
    if (data.encrypt) {
        data = JSON.parse(await cipher.decrypt(data.encrypt))
    }
    const signature = headers.get('X-Lark-Signature');
    //绑定的时候没有signature,所以得判断下
    if (signature) {
        const timestamp = headers.get('X-Lark-Request-Timestamp')!;
        const nonce = headers.get('X-Lark-Request-Nonce')!;
        const sign = cipher.calculateSignature(timestamp, nonce, body)

        if (sign !== signature) {
            return new Response('Invalid request', { status: 400 })
        }
    }

    // 如果校验通过,返回 challenge 值
    if (data.type && data.type === 'url_verification') {
        return new Response(JSON.stringify({ challenge: data.challenge }), {
            headers: { 'Content-Type': 'application/json' },
        })
    }

    if (data.header.token != verificationToken) {
        return new Response('Invalid request', { status: 400 })
    }

    return data;
}


// 定义响应接口
interface MessageResponse {
    code: number;
    msg: string;
    data: {
        body: {
            content: string;
        };
        chat_id: string;
        create_time: string;
        deleted: boolean;
        message_id: string;
        msg_type: string;
        sender: {
            id: string;
            id_type: string;
            sender_type: string;
            tenant_key: string;
        };
        update_time: string;
        updated: boolean;
    };
}

// 定义请求参数接口
interface MessageRequest {
    content: string;
    msg_type: string;
    receive_id: string;
    uuid: string;
}

// 发送消息函数
//https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/message/create
export async function sendFeishuMessageText(token: string, receive_id: string, content: string): Promise<MessageResponse> {
    const url = 'https://open.feishu.cn/open-apis/im/v1/messages';
    try {
        const response = await fetch(`${url}?receive_id_type=open_id`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
                msg_type: "text",
                content: JSON.stringify({ text: content }),
                receive_id: receive_id, // 需要配置接收者ID
                uuid: uuidv4()
            } as MessageRequest)
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}, ${await response.text()}`);
        }
        const data: MessageResponse = await response.json() as MessageResponse;

        return data;
    } catch (error) {
        console.error('发送消息失败:', error);
        throw error;
    }
}




interface LarkCardRequest {
    type: string;
    data: string;
}
interface LarkCardResponse {
    code: number;
    data: {
        card_id: string;
    };
    msg: string;
}

//第一步创建卡片
//https://open.feishu.cn/document/uAjLw4CM/ukzMukzMukzM/feishu-cards/streaming-updates-openapi-overview#5ac65a50
export async function sendFeishuCreateCard(token: string, title: string, content: string, element_id: string = "markdown_content"): Promise<LarkCardResponse> {

    const url = 'https://open.feishu.cn/open-apis/cardkit/v1/cards';
    const requestBody: LarkCardRequest = {
        type: "card_json",
        data: JSON.stringify({
            schema: "2.0",
            header: {
                title: {
                    content: title,
                    tag: "plain_text"
                }
            },
            config: {
                streaming_mode: true,
                summary: {
                    content: ""
                }
            },
            body: {
                elements: [
                    {
                        tag: "markdown",
                        content: content,
                        element_id: element_id
                    }
                ]
            }
        })
    };

    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: JSON.stringify(requestBody)
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        return data as LarkCardResponse;
    } catch (error) {
        console.error('Error:', error instanceof Error ? error.message : 'Unknown error');
        throw error;
    }
}

//第二部发送消息
export async function sendFeishuMessageCard(token: string, card_id: string, receive_id: string): Promise<MessageResponse> {
    const url = 'https://open.feishu.cn/open-apis/im/v1/messages';
    try {
        const response = await fetch(`${url}?receive_id_type=open_id`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
                msg_type: "interactive",
                content: JSON.stringify({
                    type: "card", data: {
                        "card_id": card_id
                    }
                }),
                receive_id: receive_id, // 需要配置接收者ID
                uuid: uuidv4()
            } as MessageRequest)
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}, ${await response.text()}`);
        }
        const data: MessageResponse = await response.json() as MessageResponse;
        return data;
    } catch (error) {
        console.error('发送消息失败:', error);
        throw error;
    }
}

//第三部更新卡片
interface UpdateCardParams {
    token: string;
    card_id: string;
    element_id: string;
    sequence: number;
    content: string;
}

interface UpdateCardResponse {
    code: number;
    data: Record<string, unknown>;
    msg: string;
}

export async function updateMarkdownCard({
    token,
    card_id,
    element_id,
    sequence,
    content
}: UpdateCardParams): Promise<UpdateCardResponse> {
    const url = `https://open.feishu.cn/open-apis/cardkit/v1/cards/${card_id}/elements/${element_id}/content`;
    const headers = {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
    };
    const body = JSON.stringify({
        content,
        sequence,
        uuid: uuidv4()
    });

    try {
        const response = await fetch(url, {
            method: 'PUT',
            headers,
            body
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const result: UpdateCardResponse = await response.json() as UpdateCardResponse;
        if (result.code !== 0) {
            throw new Error(`API error: ${result.msg}`);
        }

        return result;
    } catch (error) {
        console.error('Update failed:', error);
        throw error;
    }
}