Treasury & Bank Transfer Management System — سامانه مدیریت خزانه‌داری و حواله‌های بانکی

feat: add read-only SQL query editor, copy UX and safe SELECT preview validation

davoodmehraban89 committed Oct 15, 2026 at 20:43 UTC 885ea4f059479b311b22c044982b1a7ef1d13e3d
9 files changed +239
docs/SQL_READ_ONLY_STAGE_1.md new
+13
@@ -0,0 +1,13 @@
1 +# SQL Server Read-Only Integration — Stage 1 (2026-10-15)
2 +
3 +- Added /integrations with Persian RTL UI, editable sample query and copy-current-text button.
4 +- Suggested schema contract only: **not** inferred from customer's accounting SQL schema.
5 +- SELECT-only lexical guard and at-most-100-row SQL template. No query execution API yet.
6 +- No secrets, connection strings or database rows are stored/transmitted by this UI.
7 +- No modification to Mayan, Peyvast, production SQL tables or bank submission.
8 +- Branch is based on phase-7-production-infrastructure-bank-golive because main contains only README.md.
9 +- This GitHub branch does not include the newer local Windows V5/1.0.1 worktree; merge pending.
10 +
11 +Security: SQL lexical validation is not a database permission boundary. Real preview requires a protected server-only endpoint, verified desktop-local identity, a dedicated SQL login genuinely limited to SELECT on approved views, server-enforced row/timeout limits and non-production integration tests.
12 +
13 +Next: Recover C:\TreasuryFlow-P1\.worktrees\batch-payment-import-v1.0.1, map real schema without secrets, implement authenticated local test-connection/schema inspection, then build and smoke-test Setup EXE. No live bank traffic is authorized.
src/app/integrations/clipboard.test.ts new
+14
@@ -0,0 +1,14 @@
1 +import {describe,expect,it,vi} from 'vitest';
2 +import {copyQueryText} from './clipboard';
3 +describe('SQL query clipboard',()=>{
4 + it('copies exact edited SQL',async()=>{
5 + const original=Object.getOwnPropertyDescriptor(globalThis,'navigator');
6 + const writeText=vi.fn().mockResolvedValue(undefined);
7 + Object.defineProperty(globalThis,'navigator',{configurable:true,value:{clipboard:{writeText}}});
8 + try{expect(await copyQueryText('SELECT TOP (7) X FROM dbo.Y')).toBe(true);
9 + expect(writeText).toHaveBeenCalledWith('SELECT TOP (7) X FROM dbo.Y');
10 + }finally{if(original)Object.defineProperty(globalThis,'navigator',original);
11 + else Reflect.deleteProperty(globalThis,'navigator');}
12 + });
13 + it('does not copy empty SQL',async()=>expect(await copyQueryText('')).toBe(false));
14 +});
src/app/integrations/clipboard.ts new
+15
@@ -0,0 +1,15 @@
1 +/** Copy precisely the editor's current text without sending it to a server. */
2 +export async function copyQueryText(text:string):Promise<boolean>{
3 + if(!text)return false;
4 + try{
5 + if(typeof navigator!=='undefined'&&navigator.clipboard?.writeText){
6 + await navigator.clipboard.writeText(text);return true;
7 + }
8 + }catch{/* Fall back for desktop browsers */ }
9 + if(typeof document==='undefined')return false;
10 + const field=document.createElement('textarea');field.value=text;field.readOnly=true;
11 + field.setAttribute('aria-hidden','true');
12 + field.style.cssText='position:fixed;opacity:0;pointer-events:none;left:0;top:0';
13 + try{document.body.appendChild(field);field.focus();field.select();return document.execCommand('copy');}
14 + catch{return false;}finally{field.remove();}
15 +}
src/app/integrations/page.tsx new
+31
@@ -0,0 +1,31 @@
1 +import {QueryEditor} from './query-editor';
2 +export const metadata={title:'اتصال به دیتابیس | TreasuryFlow'};
3 +const requiredColumns=[
4 + {name:'Row_ID',purpose:'کلید ردیف منبع'},
5 + {name:'Destination_IBAN',purpose:'شبای مقصد'},
6 + {name:'Beneficiary_Name',purpose:'نام ذی‌نفع'},
7 + {name:'Amount_IRR',purpose:'مبلغ صحیح به ریال'},
8 + {name:'Client_Reference',purpose:'شناسه یکتا نزد خزانه'},
9 + {name:'Payment_Identifier',purpose:'شناسه پرداخت، در صورت وجود'},
10 + {name:'Deposit_Identifier',purpose:'شناسه واریز، در صورت وجود'}
11 +] as const;
12 +export default function IntegrationsPage(){
13 + return <div className="page-stack">
14 + <header className="page-head"><div><p className="eyebrow">DATABASE INTEGRATION</p>
15 + <h2>اتصال به دیتابیس</h2>
16 + <p>طراحی قرارداد خواندن داده از SQL Server بدون تغییر جداول حسابداری.</p>
17 + </div></header>
18 + <div className="alert-banner">
19 + اتصال زنده در این مرحله فعال نیست؛ برای جلوگیری از افشای داده و تغییر ناخواسته، هیچ تنظیمات محرمانه‌ای در این صفحه دریافت یا ذخیره نمی‌شود.
20 + </div>
21 + <QueryEditor/>
22 + <section className="panel" aria-labelledby="expected-fields">
23 + <div className="section-title"><div><h3 id="expected-fields">قرارداد خروجی پیشنهادی حواله</h3>
24 + <p>ساختار واقعی را می‌توان با SQL View یا نام مستعار ستون‌ها (AS) به این قرارداد نگاشت.</p>
25 + </div></div>
26 + <div className="table-wrap"><table><thead><tr><th scope="col">ستون پیشنهادی</th><th scope="col">کاربرد</th></tr></thead>
27 + <tbody>{requiredColumns.map(item=><tr key={item.name}><td dir="ltr">{item.name}</td><td>{item.purpose}</td></tr>)}</tbody>
28 + </table></div>
29 + </section>
30 + </div>;
31 +}
src/app/integrations/query-editor.test.tsx new
+20
@@ -0,0 +1,20 @@
1 +import {describe,expect,it} from 'vitest';
2 +import {renderToStaticMarkup} from 'react-dom/server';
3 +import {QueryEditor} from './query-editor';
4 +import IntegrationsPage from './page';
5 +describe('read-only integration UI',()=>{
6 + it('renders editable SQL and copy button',()=>{
7 + const html=renderToStaticMarkup(<QueryEditor/>);
8 + expect(html).toContain('id="treasuryflow-sql-editor"');
9 + expect(html).toContain('SELECT TOP (100)');
10 + expect(html).toContain('کپی کوئری');
11 + expect(html).toContain('dir="ltr"');
12 + });
13 + it('explains real data source is not yet linked',()=>{
14 + const html=renderToStaticMarkup(<IntegrationsPage/>);
15 + expect(html).toContain('Destination_IBAN');
16 + expect(html).toContain('Payment_Identifier');
17 + expect(html).toContain('Deposit_Identifier');
18 + expect(html).toContain('اتصال زنده در این مرحله فعال نیست');
19 + });
20 +});
src/app/integrations/query-editor.tsx new
+41
@@ -0,0 +1,41 @@
1 +'use client';
2 +import {useState} from 'react';
3 +import {copyQueryText} from './clipboard';
4 +import {SAMPLE_READ_ONLY_SQL,validateReadOnlySql} from '../../platform/integration/read-only-query';
5 +
6 +/** A local-only editor: no database call and no secret storage. */
7 +export function QueryEditor(){
8 + const [sql,setSql]=useState(SAMPLE_READ_ONLY_SQL);
9 + const [feedback,setFeedback]=useState<'idle'|'copied'|'error'>('idle');
10 + const result=validateReadOnlySql(sql);
11 + async function copy(){const ok=await copyQueryText(sql);setFeedback(ok?'copied':'error');}
12 + return <section className="panel" aria-labelledby="read-only-query-title">
13 + <div className="section-title"><div>
14 + <h3 id="read-only-query-title">Read Only Query — نمونه SQL قابل ویرایش</h3>
15 + <p>نام جدول و ستون‌ها نمونه‌اند؛ آن‌ها را بر اساس ساختار واقعی SQL Server تنظیم کنید.</p>
16 + </div></div>
17 + <label htmlFor="treasuryflow-sql-editor">متن کوئری</label>
18 + <textarea id="treasuryflow-sql-editor" dir="ltr" lang="en"
19 + spellCheck={false} value={sql} rows={13}
20 + onChange={event=>{setSql(event.target.value);setFeedback('idle');}}
21 + style={{width:'100%',minHeight:280,padding:16,border:'1px solid #cbd5e1',borderRadius:10,fontFamily:'Consolas,monospace',fontSize:13,lineHeight:1.7,resize:'vertical',direction:'ltr',textAlign:'left'}}
22 + aria-describedby="sql-readonly-status"/>
23 + <div style={{display:'flex',flexWrap:'wrap',alignItems:'center',gap:10,marginTop:12}}>
24 + <button type="button" className="btn btn-primary" disabled={!sql} onClick={copy}>کپی کوئری</button>
25 + <button type="button" className="btn btn-secondary"
26 + onClick={()=>{setSql(SAMPLE_READ_ONLY_SQL);setFeedback('idle');}}>بازگردانی نمونه</button>
27 + <span id="sql-readonly-status" role="status" aria-live="polite">
28 + {feedback==='copied'?'متن کامل کوئری کپی شد.':
29 + feedback==='error'?'کپی خودکار ممکن نبود؛ متن را انتخاب و با Ctrl+C کپی کنید.':
30 + result.ok?'ساختار اولیه کوئری قابل قبول است؛ این تأیید اتصال یا مجوز SQL نیست.':
31 + 'کوئری باید یک SELECT ساده و فقط‌خواندنی باشد.'}
32 + </span>
33 + </div>
34 + {!result.ok&&<p className="alert-banner danger" role="alert" data-code={result.code}>
35 + کوئری برای اجرای پیش‌نمایش مجاز نیست: {result.message}</p>}
36 + <p style={{fontSize:12,color:'#667085',lineHeight:1.9,marginTop:12}}>
37 + این صفحه هیچ کوئری را اجرا نمی‌کند. اعتبارسنجی محلی جایگزین حساب SQL با دسترسی صرفاً SELECT نیست.
38 + برای خواندن واقعی باید اتصال تست، حساب کم‌اختیار و نگاشت ستون‌ها جداگانه تأیید شود.
39 + </p>
40 + </section>;
41 +}
src/app/ui/navigation.ts
+1
@@ -7,6 +7,7 @@ export const PRIMARY_NAV:readonly NavItem[]=[
7 {labelFa:'مغایرت‌گیری',href:'/reconciliation',group:'controls',icon:'≋'},
8 {labelFa:'صف ارسال',href:'/queue',group:'controls',icon:'↥'},
9 {labelFa:'طرف‌حساب‌ها',href:'/beneficiaries',group:'controls',icon:'◎'},
10 +{labelFa:'اتصال به دیتابیس',href:'/integrations',group:'controls',icon:'▦'},
11 {labelFa:'گزارش‌ها',href:'/reports',group:'reports',icon:'▤'},
12 {labelFa:'رویدادهای حسابرسی',href:'/audit',group:'reports',icon:'◫'}
13 ] as const;
src/platform/integration/read-only-query.test.ts new
+16
@@ -0,0 +1,16 @@
1 +import {describe,expect,it} from 'vitest';
2 +import {prepareReadOnlySql,validateReadOnlySql,SAMPLE_READ_ONLY_SQL} from './read-only-query';
3 +describe('SQL Server read-only query contract',()=>{
4 + it('preserves approved sample',()=>expect(prepareReadOnlySql(SAMPLE_READ_ONLY_SQL)).toBe(SAMPLE_READ_ONLY_SQL));
5 + it('auto limits SELECT without TOP',()=>expect(prepareReadOnlySql('SELECT Name FROM dbo.Users')).toBe('SELECT TOP (100) Name FROM dbo.Users'));
6 + it('keeps TOP <= 100',()=>expect(prepareReadOnlySql('SELECT TOP 15 Id FROM dbo.Users')).toBe('SELECT TOP 15 Id FROM dbo.Users'));
7 + it.each([
8 + 'SELECT * INTO dbo.Copied FROM dbo.Source',
9 + 'SELECT 1; DROP TABLE dbo.Users',
10 + 'SELECT TOP 9999 * FROM dbo.Source',
11 + "SELECT * FROM OPENROWSET(BULK 'f', SINGLE_BLOB)",
12 + 'SELECT 1 -- comment',
13 + 'SELECT 1 UNION SELECT 2',
14 + ])('rejects unsafe SQL %s',q=>expect(validateReadOnlySql(q).ok).toBe(false));
15 + it('does not flag keywords inside SQL string literals',()=>expect(validateReadOnlySql("SELECT Code FROM dbo.Users WHERE Code='DROP;DELETE'").ok).toBe(true));
16 +});
src/platform/integration/read-only-query.ts new
+88
@@ -0,0 +1,88 @@
1 +/**
2 + * SQL Server preview guard: defense in depth, NOT SQL authorization.
3 + * Production execution also requires a verified SELECT-only SQL principal.
4 + */
5 +export const SAMPLE_READ_ONLY_SQL = `SELECT TOP (100)
6 + Row_ID,
7 + Destination_IBAN,
8 + Beneficiary_Name,
9 + Amount_IRR,
10 + Client_Reference,
11 + Payment_Identifier,
12 + Deposit_Identifier
13 +FROM dbo.TreasuryTransferSource
14 +ORDER BY Row_ID`;
15 +export const READ_ONLY_MAX_ROWS = 100;
16 +const MAX_SQL_LENGTH = 12000;
17 +const FORBIDDEN = new Set([
18 + 'INSERT','UPDATE','DELETE','MERGE','TRUNCATE','DROP','ALTER','CREATE',
19 + 'EXEC','EXECUTE','WAITFOR','DBCC','BACKUP','RESTORE','GRANT','REVOKE',
20 + 'DENY','INTO','USE','DECLARE','SET','OPENQUERY','OPENROWSET',
21 + 'OPENDATASOURCE','OPENXML','BULK','SHUTDOWN','RECONFIGURE',
22 + 'UNION','INTERSECT','EXCEPT','APPLY','NEXT'
23 +]);
24 +export class UnsafeReadOnlySqlError extends Error {
25 + readonly code:string;
26 + constructor(code:string,message:string){super(message);this.code=code;this.name='UnsafeReadOnlySqlError';}
27 +}
28 +const unsafe=(code:string,reason:string):never=>{throw new UnsafeReadOnlySqlError(code,reason);};
29 +function maskSql(sql:string):string {
30 + let result='';
31 + for(let index=0;index<sql.length;){
32 + const ch=sql[index];
33 + if(ch==="'"||ch==='"'||ch==='['){
34 + const end=ch==='['?']':ch;let cursor=index+1;let closed=false;
35 + while(cursor<sql.length){
36 + if(sql[cursor]===end){
37 + if(sql[cursor+1]===end){cursor+=2;continue;}
38 + closed=true;cursor++;break;
39 + }cursor++;
40 + }
41 + if(!closed)unsafe('UNCLOSED_LITERAL','Unclosed SQL string or identifier');
42 + result+=' '.repeat(cursor-index);index=cursor;continue;
43 + }
44 + if(ch==='-'&&sql[index+1]==='-'||ch==='/'&&sql[index+1]==='*')
45 + unsafe('COMMENT_FORBIDDEN','SQL comments are not supported');
46 + if(ch===';')unsafe('MULTIPLE_STATEMENTS','Multiple statements are not supported');
47 + if(ch==='@'||ch==='#')unsafe('VARIABLE_FORBIDDEN','SQL variables/temporary tables are not supported');
48 + if(ch==='\0')unsafe('INVALID_CHARACTER','Null character is not allowed');
49 + result+=ch;index++;
50 + }
51 + return result;
52 +}
53 +export function prepareReadOnlySql(input:string):string {
54 + if(typeof input!=='string')unsafe('INVALID_QUERY','SQL query must be text');
55 + const query=input.trim();
56 + if(query.length===0||query.length>MAX_SQL_LENGTH)unsafe('INVALID_LENGTH','SQL query is empty or too long');
57 + const masked=maskSql(query);
58 + if(!/^SELECT\s+/i.test(masked))unsafe('SELECT_ONLY','Only SELECT is supported');
59 + if(/\bGO\b/i.test(masked))unsafe('BATCH_FORBIDDEN','SQL batch separator is not supported');
60 + if(/\.\s*\.\s*\./.test(masked))unsafe('REMOTE_IDENTIFIER','Remote SQL identifiers are not supported');
61 + const tokens=masked.match(/\b[A-Za-z_][A-Za-z_0-9]*\b/g)??[];
62 + for(const word of tokens)if(FORBIDDEN.has(word.toUpperCase()))
63 + unsafe('FORBIDDEN_OPERATION','Disallowed SQL operation: '+word.toUpperCase());
64 + if(/\b(?:xp_|sp_)\w*/i.test(masked))unsafe('PROCEDURE_FORBIDDEN','Stored procedure references are not supported');
65 + const prefix=/^SELECT\s+(?:(?:DISTINCT|ALL)\s+)?/i.exec(query)?.[0];
66 + if(!prefix||!/^SELECT\s+(?:(?:DISTINCT|ALL)\s+)?$/i.test(masked.slice(0,prefix.length)))
67 + unsafe('SELECT_ONLY','Unexpected SQL prefix');
68 + const remaining=query.slice(prefix.length);
69 + const top=/^TOP\s*(?:\(\s*(\d+)\s*\)|(\d+)\b)/i.exec(remaining);
70 + if(top){
71 + const count=Number(top[1]??top[2]);
72 + if(!Number.isSafeInteger(count)||count<1||count>READ_ONLY_MAX_ROWS)
73 + unsafe('ROW_LIMIT','TOP must be between 1 and 100');
74 + if(/\bPERCENT\b|\bWITH\s+TIES\b/i.test(masked.slice(prefix.length)))
75 + unsafe('ROW_LIMIT','TOP PERCENT/WITH TIES are not supported');
76 + return query;
77 + }
78 + if(/^TOP\b/i.test(remaining))unsafe('ROW_LIMIT','TOP must be a numeric constant');
79 + return prefix+'TOP ('+READ_ONLY_MAX_ROWS+') '+remaining;
80 +}
81 +export function validateReadOnlySql(input:string):
82 + {ok:true;preparedSql:string}|{ok:false;code:string;message:string}{
83 + try{return {ok:true,preparedSql:prepareReadOnlySql(input)};}
84 + catch(error){
85 + if(error instanceof UnsafeReadOnlySqlError)return {ok:false,code:error.code,message:error.message};
86 + throw error;
87 + }
88 +}