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

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 prefixMatch=/^SELECT\s+(?:(?:DISTINCT|ALL)\s+)?/i.exec(query);
66 if(!prefixMatch)throw new UnsafeReadOnlySqlError('SELECT_ONLY','Unexpected SQL prefix');
67 const prefix=prefixMatch[0];
68 if(!/^SELECT\s+(?:(?:DISTINCT|ALL)\s+)?$/i.test(masked.slice(0,prefix.length)))
69 unsafe('SELECT_ONLY','Unexpected SQL prefix');
70 const remaining=query.slice(prefix.length);
71 const top=/^TOP\s*(?:\(\s*(\d+)\s*\)|(\d+)\b)/i.exec(remaining);
72 if(top){
73 const count=Number(top[1]??top[2]);
74 if(!Number.isSafeInteger(count)||count<1||count>READ_ONLY_MAX_ROWS)
75 unsafe('ROW_LIMIT','TOP must be between 1 and 100');
76 if(/\bPERCENT\b|\bWITH\s+TIES\b/i.test(masked.slice(prefix.length)))
77 unsafe('ROW_LIMIT','TOP PERCENT/WITH TIES are not supported');
78 return query;
79 }
80 if(/^TOP\b/i.test(remaining))unsafe('ROW_LIMIT','TOP must be a numeric constant');
81 return prefix+'TOP ('+READ_ONLY_MAX_ROWS+') '+remaining;
82 }
83 export function validateReadOnlySql(input:string):
84 {ok:true;preparedSql:string}|{ok:false;code:string;message:string}{
85 try{return {ok:true,preparedSql:prepareReadOnlySql(input)};}
86 catch(error){
87 if(error instanceof UnsafeReadOnlySqlError)return {ok:false,code:error.code,message:error.message};
88 throw error;
89 }
90 }