File size: 10,751 Bytes
bbfde3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
const Busboy = require('busboy');
const JSZip = require('jszip');
const { applyCorsHeaders, handleCorsPreflight } = require('../lib/cors-middleware');

// Helper function to send JSON with proper headers
function sendJson(res, status, data) {
  res.setHeader('Content-Type', 'application/json');
  res.status(status).end(JSON.stringify(data));
}

module.exports = async (req, res) => {
  if (handleCorsPreflight(req, res, { allowedMethods: 'POST, OPTIONS' })) {
    return;
  }
  applyCorsHeaders(req, res, { allowedMethods: 'POST, OPTIONS' });

  if (req.method !== 'POST') {
    sendJson(res, 405, { error: 'Method not allowed' });
    return;
  }

  try {
    const busboy = Busboy({ headers: req.headers });
    let fileData = null;
    let filename = null;

    busboy.on('file', (fieldname, file, info) => {
      filename = info.filename;
      const chunks = [];
      
      file.on('data', (chunk) => {
        chunks.push(chunk);
      });
      
      file.on('end', () => {
        fileData = Buffer.concat(chunks);
      });
    });

    busboy.on('finish', async () => {
      if (!fileData || !filename) {
        res.status(400).json({ error: 'No file uploaded' });
        return;
      }

      if (!filename.toLowerCase().endsWith('.docx')) {
        res.status(400).json({ error: 'Please upload a .docx file' });
        return;
      }

      try {
        const remediatedFile = await remediateDocx(fileData, filename);
        
        // Always fix filename: replace underscores with hyphens and add -remediated suffix
        let suggestedName = filename
          .replace(/_/g, '-')  // Replace all underscores with hyphens
          .replace(/\.docx$/i, '-remediated.docx');  // Add -remediated before extension

        res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
        res.setHeader('Content-Disposition', `attachment; filename="${suggestedName}"`);
        res.status(200).send(remediatedFile);
        
      } catch (error) {
        res.status(500).json({ error: error.message });
      }
    });

    req.pipe(busboy);

  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

async function remediateDocx(fileData, filename) {
  try {
    const zip = await JSZip.loadAsync(fileData);
    
    // Helper function to write only if content changed
    const writeIfChanged = (filename, original, modified) => {
      if (original !== modified && modified !== null) {
        zip.file(filename, modified);
        return true;
      }
      return false;
    };
    
    // Process document.xml
    const docFile = zip.file('word/document.xml');
    if (docFile) {
      const origDocXml = await docFile.async('string');
      const afterShadows = removeShadowsOnly(origDocXml);
      const afterInlineContent = applyInlineContentFixes(afterShadows || origDocXml);
      writeIfChanged('word/document.xml', origDocXml, afterInlineContent);
    }
    
    // Process styles.xml
    const stylesFile = zip.file('word/styles.xml');
    if (stylesFile) {
      const origStylesXml = await stylesFile.async('string');
      const afterStylesShadows = removeShadowsOnly(origStylesXml);
      writeIfChanged('word/styles.xml', origStylesXml, afterStylesShadows);
    }
    
    // Process theme files
    const themeFile = zip.file('word/theme/theme1.xml');
    if (themeFile) {
      const origThemeXml = await themeFile.async('string');
      const afterTheme = removeShadowsOnly(origThemeXml);
      writeIfChanged('word/theme/theme1.xml', origThemeXml, afterTheme);
    }
    
    // Protection removal
    try {
      const settingsFile = zip.file('word/settings.xml');
      if (settingsFile) {
        const origSettings = await settingsFile.async('string');
        const hasAnyProt = /<w:(?:documentProtection|writeProtection|readOnlyRecommended|editRestrictions|formProtection|protection|docProtection|enforcement|locked|trackRevisions|crypt)\b/.test(origSettings);
        if (hasAnyProt) {
          let cleaned = origSettings;
          
          cleaned = cleaned.replace(/<w:(?:documentProtection|writeProtection|readOnlyRecommended|editRestrictions|formProtection|protection|docProtection)[^>]*\/>/g, '');
          cleaned = cleaned.replace(/<w:(?:documentProtection|writeProtection|readOnlyRecommended|editRestrictions|formProtection|protection|docProtection)[^>]*>[\s\S]*?<\/w:(?:documentProtection|writeProtection|readOnlyRecommended|editRestrictions|formProtection|protection|docProtection)>/g, '');
          cleaned = cleaned.replace(/<w:(?:enforcement|locked|trackRevisions)[^>]*\/>/g, '');
          cleaned = cleaned.replace(/<w:(?:enforcement|locked|trackRevisions)[^>]*>[\s\S]*?<\/w:(?:enforcement|locked|trackRevisions)>/g, '');
          cleaned = cleaned.replace(/<w:crypt[^>]*\/>/g, '');
          cleaned = cleaned.replace(/<w:crypt[^>]*>[\s\S]*?<\/w:crypt[^>]*>/g, '');
          cleaned = cleaned.replace(/\s?w:(?:locked|trackRevisions|enforcement)="[^"]*"/g, '');
          
          writeIfChanged('word/settings.xml', origSettings, cleaned);
        }
      }
    } catch (e) {
      console.warn('[remediateDocx] Protection removal failed:', e.message);
    }
    
    // Generate with proper compression
    const remediatedBuffer = await zip.generateAsync({ 
      type: 'nodebuffer',
      compression: 'DEFLATE',
      compressionOptions: { level: 6 }
    });
    
    return remediatedBuffer;
    
  } catch (error) {
    throw new Error(`Failed to remediate document: ${error.message}`);
  }
}



function applyInlineContentFixes(xmlContent) {
  if (!xmlContent) return null;
  
  const original = xmlContent;
  let fixedXml = xmlContent;

  // Apply the same patterns as in the analysis function
  const floatingPatterns = [
    // DrawingML anchor patterns (modern Word drawings)
    {
      pattern: /<wp:anchor[^>]*>([\s\S]*?)<\/wp:anchor>/g,
      replacement: function(match, content) {
        // Convert anchor (floating) to inline
        return `<wp:inline>${content}</wp:inline>`;
      }
    },
    // Text wrapping patterns
    {
      pattern: /<wp:wrapSquare[^>]*\/>/g,
      replacement: ''
    },
    {
      pattern: /<wp:wrapTight[^>]*>[\s\S]*?<\/wp:wrapTight>/g,
      replacement: ''
    },
    {
      pattern: /<wp:wrapThrough[^>]*>[\s\S]*?<\/wp:wrapThrough>/g,
      replacement: ''
    },
    {
      pattern: /<wp:wrapTopAndBottom[^>]*\/>/g,
      replacement: ''
    },
    {
      pattern: /<wp:wrapNone[^>]*\/>/g,
      replacement: ''
    },
    // Position and alignment patterns
    {
      pattern: /<wp:positionH[^>]*>[\s\S]*?<\/wp:positionH>/g,
      replacement: ''
    },
    {
      pattern: /<wp:positionV[^>]*>[\s\S]*?<\/wp:positionV>/g,
      replacement: ''
    },
    // VML patterns for legacy compatibility
    {
      pattern: /mso-position-horizontal:[^;]*;?/g,
      replacement: ''
    },
    {
      pattern: /mso-position-vertical:[^;]*;?/g,
      replacement: ''
    },
    {
      pattern: /mso-wrap-style:[^;]*;?/g,
      replacement: ''
    },
    {
      pattern: /left:\s*[^;]*;?/g,
      replacement: ''
    },
    {
      pattern: /top:\s*[^;]*;?/g,
      replacement: ''
    }
  ];

  // Apply fixes for floating elements
  floatingPatterns.forEach(patternObj => {
    const { pattern, replacement } = patternObj;
    
    if (typeof replacement === 'function') {
      fixedXml = fixedXml.replace(pattern, replacement);
    } else {
      fixedXml = fixedXml.replace(pattern, replacement);
    }
  });

  // Special handling for drawing elements - ensure they are inline
  const drawingPattern = /<w:drawing[^>]*>[\s\S]*?<\/w:drawing>/g;
  const drawingMatches = fixedXml.match(drawingPattern);
  
  if (drawingMatches) {
    drawingMatches.forEach(drawing => {
      // Check if this drawing contains floating elements
      if (drawing.includes('wp:anchor') && !drawing.includes('wp:inline')) {
        // Convert anchor to inline within the drawing
        let fixedDrawing = drawing.replace(/<wp:anchor[^>]*>/g, '<wp:inline>');
        fixedDrawing = fixedDrawing.replace(/<\/wp:anchor>/g, '</wp:inline>');
        
        if (fixedDrawing !== drawing) {
          fixedXml = fixedXml.replace(drawing, fixedDrawing);
        }
      }
    });
  }

  // If nothing changed, return null
  if (fixedXml === original) return null;
  return fixedXml;
}

function removeShadowsOnly(xmlContent) {
  const original = xmlContent;
  let fixedXml = xmlContent;
  
  // 1. Remove basic Word text shadows
  fixedXml = fixedXml.replace(/<w:shadow\s*\/>/g, '');
  fixedXml = fixedXml.replace(/<w:shadow[^>]*>.*?<\/w:shadow>/g, '');
  fixedXml = fixedXml.replace(/\s+\w*shadow\w*\s*=\s*"[^"]*"/g, '');
  
  // 2. Remove advanced DrawingML shadow effects
  fixedXml = fixedXml.replace(/<a:outerShdw[^>]*\/>/g, '');
  fixedXml = fixedXml.replace(/<a:outerShdw[^>]*>.*?<\/a:outerShdw>/g, '');
  fixedXml = fixedXml.replace(/<a:innerShdw[^>]*\/>/g, '');
  fixedXml = fixedXml.replace(/<a:innerShdw[^>]*>.*?<\/a:innerShdw>/g, '');
  fixedXml = fixedXml.replace(/<a:prstShdw[^>]*\/>/g, '');
  fixedXml = fixedXml.replace(/<a:prstShdw[^>]*>.*?<\/a:prstShdw>/g, '');
  
  // 3. Remove Office 2010+ shadow effects
  fixedXml = fixedXml.replace(/<w14:shadow[^>]*\/>/g, '');
  fixedXml = fixedXml.replace(/<w14:shadow[^>]*>.*?<\/w14:shadow>/g, '');
  fixedXml = fixedXml.replace(/<w15:shadow[^>]*\/>/g, '');
  fixedXml = fixedXml.replace(/<w15:shadow[^>]*>.*?<\/w15:shadow>/g, '');
  
  // 4. Remove shadow-related text effects and 3D properties
  fixedXml = fixedXml.replace(/<w14:glow[^>]*\/>/g, '');
  fixedXml = fixedXml.replace(/<w14:glow[^>]*>.*?<\/w14:glow>/g, '');
  fixedXml = fixedXml.replace(/<w14:reflection[^>]*\/>/g, '');
  fixedXml = fixedXml.replace(/<w14:reflection[^>]*>.*?<\/w14:reflection>/g, '');
  fixedXml = fixedXml.replace(/<w14:props3d[^>]*\/>/g, '');
  fixedXml = fixedXml.replace(/<w14:props3d[^>]*>.*?<\/w14:props3d>/g, '');
  
  // 5. Remove shadow properties and attributes (safely)
  // Remove only within attribute values, not entire element names
  fixedXml = fixedXml.replace(/\s+\w*shdw\w*\s*=\s*"[^"]*"/g, '');
  
  // NOTE: Font normalization, font size fixes, and line spacing fixes have been 
  // removed - these are now flagged for user attention instead of auto-fixed
  
  // If nothing changed, return null so callers can avoid rewriting the part
  if (fixedXml === original) return null;
  return fixedXml;
}