message-images.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334
  1. // Only identifiers from the observed Teams AMS image schema are retained. Never
  2. // retain arbitrary img URLs, query strings, cookies or signed download links.
  3. export const AMS_OBJECT_ID = /^[a-zA-Z0-9_-]{1,200}$/;
  4. export function messageImage(attributes) {
  5. const type = attributes.itemtype || '';
  6. if (type && !/^https?:\/\/schema\.skype\.com\/AMSImage$/.test(type)) return null;
  7. try {
  8. const url = new URL(attributes.src);
  9. if (url.protocol !== 'https:' || url.username || url.password || url.port || url.hash
  10. || !['as-api.asm.skype.com', 'as-prod.asyncgw.teams.microsoft.com'].includes(url.hostname)) return null;
  11. const match = url.pathname.match(/^\/v1\/(?:[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}\/)?objects\/([a-zA-Z0-9_-]{1,200})\/views\/imgo$/);
  12. if (!match) return null;
  13. const image = { objectId: match[1], label: cleanImageLabel(attributes.alt) || '图片' };
  14. for (const key of ['width', 'height']) {
  15. const value = Number(attributes[key]);
  16. if (Number.isInteger(value) && value > 0 && value <= 100000) image[key] = value;
  17. }
  18. return image;
  19. } catch { return null; }
  20. }
  21. export function cleanImageLabel(value) {
  22. return typeof value === 'string' ? [...value.replace(/[\u0000-\u001f\u007f]/g, '').trim()].slice(0, 200).join('') : '';
  23. }
  24. export function validMessageImages(value) {
  25. if (!Array.isArray(value)) return [];
  26. const seen = new Set(), result = [];
  27. for (const image of value.slice(0, 100)) {
  28. if (!image || typeof image.objectId !== 'string' || !AMS_OBJECT_ID.test(image.objectId) || seen.has(image.objectId)) continue;
  29. seen.add(image.objectId);
  30. result.push({ objectId: image.objectId, label: cleanImageLabel(image.label) || '图片',
  31. ...Object.fromEntries(['width', 'height'].filter(k => Number.isInteger(image[k]) && image[k] > 0 && image[k] <= 100000).map(k => [k, image[k]])) });
  32. }
  33. return result;
  34. }