import assert from 'node:assert/strict'; import test from 'node:test'; import sharp from 'sharp'; import { uploadWechatGeneratedImage } from './wechat-media.mjs'; test('uploadWechatGeneratedImage converts a generated asset and uploads WeChat image media', async () => { const source = await sharp({ create: { width: 32, height: 32, channels: 3, background: '#336699' }, }).webp().toBuffer(); const calls = []; const result = await uploadWechatGeneratedImage( 'access-1', '/MindSpace/user/public/images/fresh.webp', { publicBaseUrl: 'https://example.com', wechatFetch: async (url, init = {}) => { calls.push({ url: String(url), init }); if (String(url).startsWith('https://example.com/')) { return new Response(source, { status: 200, headers: { 'Content-Type': 'image/webp' } }); } if (String(url).includes('/cgi-bin/media/upload')) { assert.equal(init.method, 'POST'); assert.ok(init.body instanceof FormData); return new Response(JSON.stringify({ type: 'image', media_id: 'wx-media-1', created_at: 1 }), { status: 200, headers: { 'Content-Type': 'application/json' }, }); } throw new Error(`unexpected url: ${url}`); }, }, ); assert.equal(result.mediaId, 'wx-media-1'); assert.equal(result.contentType, 'image/jpeg'); assert.ok(result.bytes > 0); assert.match(calls[1].url, /access_token=access-1/); assert.match(calls[1].url, /type=image/); }); test('uploadWechatGeneratedImage accepts configured imgproxy origin and rejects unknown origins', async () => { const source = await sharp({ create: { width: 16, height: 16, channels: 3, background: '#884422' }, }).png().toBuffer(); const wechatFetch = async (url) => { if (String(url).startsWith('https://img.example.com/')) { return new Response(source, { status: 200, headers: { 'Content-Type': 'image/png' } }); } return new Response(JSON.stringify({ type: 'image', media_id: 'wx-media-imgproxy' }), { status: 200, headers: { 'Content-Type': 'application/json' }, }); }; const accepted = await uploadWechatGeneratedImage( 'access-2', 'https://img.example.com/signed/generated.webp', { publicBaseUrl: 'https://app.example.com', allowedPublicBaseUrls: ['https://img.example.com'], wechatFetch, }, ); assert.equal(accepted.mediaId, 'wx-media-imgproxy'); await assert.rejects( uploadWechatGeneratedImage('access-2', 'https://untrusted.example.net/generated.webp', { publicBaseUrl: 'https://app.example.com', allowedPublicBaseUrls: ['https://img.example.com'], wechatFetch, }), /可信公网域名/, ); });