# -*- coding: utf-8 -*- from xml.sax.saxutils import escape import re, os, zipfile def norm(t): return re.sub(r'[\u200c\u200f\u200e]', '', (t or '')).strip() def cell_text(tc): return ''.join(re.findall(r']*>([^<]*)', tc)) def para(text): ps = '' for line in str(text).split('\n'): line = line.strip() or ' ' ps += ('' '' '' + escape(line) + '') return ps def rows_of(tbl): return [(m.start(), m.end(), m.group(0)) for m in re.finditer(r'].*?', tbl, re.S)] def cells_of(row): return re.findall(r'.*?', row, re.S) def insert_into_cell(tc, value): pi = tc.find('', para(value) + '') return tc[:pi] + para(value) + tc[pi:] def fill_by_label(tbl, label_norm, value, any_cell=False): """Insert value into the cell following the label cell (same row), else next row's first empty cell.""" rs = rows_of(tbl) for idx, (s, e, row) in enumerate(rs): cells = cells_of(row) texts = [norm(cell_text(c)) for c in cells] hit = None if not any_cell and texts and texts[0] == label_norm and len(cells) >= 2: hit = 1 elif any_cell: for i, t in enumerate(texts): if t == label_norm: hit = i + 1 if i + 1 < len(cells) else i break if hit is not None: new_row = row.replace(cells[hit], insert_into_cell(cells[hit], value), 1) return tbl[:s] + new_row + tbl[e:], True # value cell on the NEXT row if any_cell and label_norm in texts and idx + 1 < len(rs): s2, e2, row2 = rs[idx + 1] c2 = cells_of(row2) if c2: t0 = norm(cell_text(c2[0])) if t0 == '': new_row2 = row2.replace(c2[0], insert_into_cell(c2[0], value), 1) return tbl[:s2] + new_row2 + tbl[e2:], True return tbl, False def table_id(tbl): for s, e, row in rows_of(tbl): cells = cells_of(row) texts = [norm(cell_text(c)) for c in cells] for i, t in enumerate(texts): if t.startswith('شناسه الزام') and i + 1 < len(cells): return cell_text(cells[i + 1]) return None def table_field(tbl, label_norm): for s, e, row in rows_of(tbl): cells = cells_of(row) texts = [norm(cell_text(c)) for c in cells] for i, t in enumerate(texts): if t == label_norm and i + 1 < len(cells): return cell_text(cells[i + 1]) return '' def find_answer(id_text): if id_text: for ans in A: if any(k in id_text for k in ans['keys']): return ans return None BODIES = { 'بروز بودن اجزا': ['ابزارها و چارچوب'], 'سرآیندها': ['Strict Transport Security'], 'Cookie': ['پیکربندی صحیح Cookie'], 'Ports': ['درگاه‌هایی'], 'متدهای ناامن': ['متدهای ناامن'], 'Anti-CSRF': ['Anti-CSRF'], } def find_answer_by_body(body): b = norm(body) for name, keys in BODIES.items(): if any(norm(k) in b for k in keys): for ans in A: if ans['keys'][0] == name: return ans return None def find_by_name(name): n = norm(name) for ans in A: if any(norm(k) in n for k in ans['keys']): return ans return None # --- main --- os.makedirs(OUT_DIR, exist_ok=True) with zipfile.ZipFile(SRC) as z: xml = z.read('word/document.xml').decode('utf-8') tables = [(m.start(), m.end(), m.group(0)) for m in re.finditer(r'.*?', xml, re.S)] report = {'req': 0, 'vuln': 0, 'res': False, 'unmatched': [], 'dupes': []} matched = set() order = [] for start, end, tbl in reversed(tables): new_tbl, tid = tbl, table_id(tbl) ans = find_answer(tid) if tid else None if not tid: joined = ' '.join(norm(cell_text(c)) for c in re.findall(r'.*?', tbl, re.S)) if 'نام متقاضی' in joined: for lab, val in [('نام متقاضی', 'Raymand Communications Naqsh Jahan'), ('نام محصول', 'Raymand-CTI'), ('نسخه محصول', '2.0.3'), ('تاریخ تکمیل', '2026-09-16'), ('نسخه‌ی سند', '1.0')]: new_tbl, ch = fill_by_label(new_tbl, norm(lab), val, any_cell=True) xml = xml[:start] + new_tbl + xml[end:] continue if 'تعداد هسته' in joined: res = A[0] for lab, val in [('نوع', 'GNU/Linux (Debian GNU/Linux 12 bookworm)'), ('نسخه', '12 (bookworm)'), ('تعداد هسته‌ی پردازنده', '4'), ('میزان RAM', '8 GB'), ('حافظه', '100 GB')]: new_tbl, ch = fill_by_label(new_tbl, norm(lab), val, any_cell=True) report['res'] = report['res'] or ch order.append((0, 'منابع مورد نیاز', 'منابع نصب و راه‌اندازی', res)) report['res'] = True xml = xml[:start] + new_tbl + xml[end:] continue else: joined_txt = ' '.join(norm(cell_text(c)) for c in re.findall(r'.*?', tbl, re.S)) body = table_field(tbl, norm('متن الزام')) + ' ' + table_field(tbl, norm('نام الزام')) + ' ' + joined_txt ans = find_answer_by_body(body) if ans is not None: key = ans['keys'][0] if key in matched: report['dupes'].append(key) matched.add(key) desc_full = 'وضعیت: ' + ans['status'] + '\n' + ans['desc'] for lab, val in [('نحوه‌ی دسترسی', ans['access']), ('تصویر', ans['img']), ('توضیحات بیشتر', desc_full)]: new_tbl, ch = fill_by_label(new_tbl, norm(lab), val) if tid: report['req'] += 1 order.append((len(order) + 1, tid.strip(), table_field(tbl, norm('نام الزام')), ans)) else: report['vuln'] += 1 order.append((0, '', (find_by_name(key) and '') or key, ans)) xml = xml[:start] + new_tbl + xml[end:] else: report['unmatched'].append(((tid or '').strip() or '(no-id-table)')[:60] + ' :: ' + norm(cell_text(tbl))[:80]) with zipfile.ZipFile(SRC) as zin, zipfile.ZipFile(OUT, 'w', zipfile.ZIP_DEFLATED) as zout: for item in zin.infolist(): data = zin.read(item.filename) if item.filename == 'word/document.xml': data = xml.encode('utf-8') zout.writestr(item, data) order = [(i + 1, tid, tname, ans) for i, (n, tid, tname, ans) in enumerate(order)] md = ['# پاسخ‌نامه سند خودارزیابی — Raymand-CTI نسخه ۲.۰.۳', '', '> منبع پاسخ‌ها: تحلیل ایستای کد (`cti-app/` فرانت، `p-line/` بک‌اند) و سند عدم‌انطباق `docs/markdown/عدم‌انطباق-الزامات-امنیتی-CTI.md`.', '> تاریخ تهیه: 2026-09-16 — نسخه سند خودارزیابی: 1.0', '', '## راهنمای وضعیت', '', '- **' + S_DONE + '** — شواهد کد موجود است؛ تصویر برای ارزیابی پیوست می‌شود.', '- **' + S_PART + '** — پیاده‌سازی ناقص یا در دستور کار اصلاح (ارجاع NC).', '- **' + S_NO + '** — طبق قواعد پرسشنامه گزینه‌ای انتخاب نمی‌شود.', '- **' + S_NA + '** — قابلیت جزو محصول نیست.', '', '## جدول خلاصه', '', '| # | شناسه الزام | نام | وضعیت |', '|---|---|---|---|'] for i, tid, tname, ans in order: md.append('| %d | %s | %s | %s |' % (i, (tid or '—').replace('|', '/'), (tname or '')[:70].replace('|', '/'), ans['status'] if ans else '—')) md.append('') md.append('## پاسخ تفصیلی') for i, tid, tname, ans in order: md.append('') md.append('### %d — %s' % (i, tid.replace('\n', ' + ') if tid else tname)) if tname: md.append('**نام الزام:** ' + tname.strip().replace('\n', ' ')) md.append('**وضعیت:** ' + ans['status']) md.append('**نحوه‌ی دسترسی:** ' + ans['access']) md.append('**توضیحات:** ' + ans['desc']) md.append('**شواهد/تصویر:** ' + ans['img']) open(MD, 'w', encoding='utf-8').write('\n'.join(md)) print('REQ_FILLED:', report['req'], '| VULN_FILLED:', report['vuln'], '| RESOURCES:', report['res']) print('DUPES:', report['dupes']) print('UNMATCHED:', report['unmatched']) print('OUT:', OUT, os.path.getsize(OUT)) print('MD:', MD, os.path.getsize(MD))