udf-cli 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/udf-cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{htmlToUdf,markdownToUdf,udfToHtml,udfToMarkdown}from'../chunk-6564CQ7U.js';import{Command}from'commander';import{existsSync,readFileSync,writeFileSync}from'fs';import{fileURLToPath}from'url';import{dirname as a0a,resolve}from'path';import a0b from'open';var DEFAULT_API_BASE='https://api.workos.com',DEFAULT_CLI_CLIENT_ID='client_01KRPJRBTG0YG5BCPMBXRA63QA';function loadAuthConfig(a=process['env']){return{'apiBase':a['WORKOS_API_BASE']??DEFAULT_API_BASE,'clientId':a['YARGI_CLI_CLIENT_ID']??DEFAULT_CLI_CLIENT_ID};}var DEFAULT_SERVER_URL='https://yargi.betaspacestudio.com';function loadServerConfig(a=process['env']){const b=a['YARGI_SERVER_URL']??DEFAULT_SERVER_URL;return{'serverUrl':b['replace'](/\/+$/,'')};}import{chmod,mkdir,readFile,writeFile,unlink,stat}from'fs/promises';import{homedir}from'os';import{dirname,join}from'path';import{z}from'zod';var StoredTokensSchema=z['object']({'accessToken':z['string'](),'refreshToken':z['string'](),'expiresAt':z['number'](),'email':z['string'](),'userId':z['string']()});function defaultTokenPath(a=process['env']){const b=a['XDG_CONFIG_HOME']??join(homedir(),'.config');return join(b,'yargi','token.json');}function decodeJwtExp(a){try{const b=a['split']('.')[0x1];if(!b)throw new Error('no\x20payload');const c=Buffer['from'](b,'base64url')['toString']('utf8'),d=JSON['parse'](c)['exp'];if(typeof d!=='number')throw new Error('no\x20exp');return d*0x3e8;}catch{return Date['now']()+0x5*0xea60;}}var FileTokenStore=class{constructor(a=defaultTokenPath()){this['path']=a;}['path'];async['load'](){let a;try{a=await readFile(this['path'],'utf8');}catch{return null;}try{const d=await stat(this['path']);(d['mode']&0x3f)!==0x0&&process['stderr']['write']('warning:\x20'+this['path']+'\x20has\x20loose\x20permissions;\x20expected\x200600\x0a');}catch{}let b;try{b=JSON['parse'](a);}catch{return null;}const c=StoredTokensSchema['safeParse'](b);return c['success']?c['data']:null;}async['save'](a){await mkdir(dirname(this['path']),{'recursive':!![],'mode':0x1c0}),await writeFile(this['path'],JSON['stringify'](a),{'mode':0x180}),await chmod(this['path'],0x180);}async['clear'](){try{await unlink(this['path']);}catch{}}};import{z as a0c}from'zod';var DeviceAuthorizationResponseSchema=a0c['object']({'device_code':a0c['string'](),'user_code':a0c['string'](),'verification_uri':a0c['string'](),'verification_uri_complete':a0c['string'](),'expires_in':a0c['number'](),'interval':a0c['number']()})['passthrough'](),WorkosUserSchema=a0c['object']({'id':a0c['string'](),'email':a0c['string']()})['passthrough'](),TokenResponseSchema=a0c['object']({'access_token':a0c['string'](),'refresh_token':a0c['string'](),'user':WorkosUserSchema})['passthrough'](),DeviceCodeExpiredError=class extends Error{constructor(){super('Device\x20code\x20expired.\x20Run\x20login\x20again.'),this['name']='DeviceCodeExpiredError';}},AuthorizationDeniedError=class extends Error{constructor(){super('Authorization\x20was\x20denied.'),this['name']='AuthorizationDeniedError';}},RefreshFailedError=class extends Error{constructor(){super('Token\x20refresh\x20failed.'),this['name']='RefreshFailedError';}},DEVICE_GRANT='urn:ietf:params:oauth:grant-type:device_code';async function postForm(a,b){const c=await fetch(a,{'method':'POST','headers':{'content-type':'application/x-www-form-urlencoded'},'body':new URLSearchParams(b)['toString']()}),d=await c['text']();let e=void 0x0;try{e=d?JSON['parse'](d):void 0x0;}catch{e=void 0x0;}return{'status':c['status'],'json':e};}async function startDeviceAuthorization(a){const {status:b,json:c}=await postForm(a['apiBase']+'/user_management/authorize/device',{'client_id':a['clientId']});if(b!==0xc8)throw new Error('device\x20authorization\x20failed\x20('+b+')');return DeviceAuthorizationResponseSchema['parse'](c);}var defaultSleep=a=>new Promise(b=>setTimeout(b,a));async function pollForToken(a,b,c={}){const d=c['sleep']??defaultSleep,e=Date['now']()+b['expiresIn']*0x3e8;let f=b['interval'];for(;;){if(Date['now']()>e)throw new DeviceCodeExpiredError();await d(f*0x3e8);const {status:g,json:h}=await postForm(a['apiBase']+'/user_management/authenticate',{'client_id':a['clientId'],'grant_type':DEVICE_GRANT,'device_code':b['deviceCode']});if(g===0xc8)return TokenResponseSchema['parse'](h);const i=h?.['error'];if(i==='authorization_pending')continue;if(i==='slow_down'){f+=0x5;continue;}if(i==='expired_token')throw new DeviceCodeExpiredError();if(i==='access_denied')throw new AuthorizationDeniedError();throw new Error('device\x20token\x20exchange\x20failed:\x20'+(i??g));}}async function refreshToken(a,b){const {status:c,json:d}=await postForm(a['apiBase']+'/user_management/authenticate',{'client_id':a['clientId'],'grant_type':'refresh_token','refresh_token':b});if(c!==0xc8)throw new RefreshFailedError();const e=TokenResponseSchema['safeParse'](d);if(!e['success'])throw new RefreshFailedError();return e['data'];}var NotLoggedInError=class extends Error{constructor(){super('Önce\x20giriş\x20yapmalısınız:\x20`udf-cli\x20login`'),this['name']='NotLoggedInError';}},AccountBannedError=class extends Error{constructor(a){super('Hesabınız\x20devre\x20dışı\x20bırakıldı'+(a?':\x20'+a:'.')),this['reason']=a,this['name']='AccountBannedError';}['reason'];},ServerUnreachableError=class extends Error{constructor(a){super('Sunucuya\x20ulaşılamadı:\x20'+a+'.\x20İnternet\x20bağlantınızı\x20kontrol\x20edip\x20tekrar\x20deneyin.'),this['name']='ServerUnreachableError';}},EXPIRY_SKEW_MS=0xea60;async function getValidAccessToken(a,b,c={}){const d=c['refresh']??refreshToken,e=await a['load']();if(!e)throw new NotLoggedInError();if(Date['now']()<e['expiresAt']-EXPIRY_SKEW_MS)return e['accessToken'];let f;try{f=await d(b,e['refreshToken']);}catch{await a['clear']();throw new NotLoggedInError();}const g={'accessToken':f['access_token'],'refreshToken':f['refresh_token'],'expiresAt':decodeJwtExp(f['access_token']),'email':f['user']['email'],'userId':f['user']['id']};try{await a['save'](g);}catch{return g['accessToken'];}return g['accessToken'];}async function reportActivation(a){const b=a['serverUrl']+'/api/cli/activations';let c;try{c=await fetch(b,{'method':'POST','headers':{'authorization':'Bearer\x20'+a['accessToken'],'content-type':'application/json'},'body':JSON['stringify']({'command':'udf','metadata':a['metadata']})});}catch(d){throw new ServerUnreachableError(d instanceof Error?d['message']:String(d));}if(c['status']===0x191)throw new NotLoggedInError();if(c['status']===0x193){const e=await c['json']()['catch'](()=>({}));if(e['error']==='banned')throw new AccountBannedError(e['reason']??null);throw new ServerUnreachableError('forbidden\x20('+(e['error']??'unknown')+')');}if(c['status']>=0x1f4)throw new ServerUnreachableError('HTTP\x20'+c['status']);if(!c['ok']){const f=await c['text']()['catch'](()=>'');throw new ServerUnreachableError('HTTP\x20'+c['status']+'\x20'+f['slice'](0x0,0xc8));}return await c['json']();}var cfg=loadAuthConfig(),serverCfg=loadServerConfig(),store=new FileTokenStore();async function gate(a){const b=await getValidAccessToken(store,cfg);await reportActivation({'serverUrl':serverCfg['serverUrl'],'accessToken':b,'metadata':{'action':a}});}async function runLogin(a){const b=await startDeviceAuthorization(cfg);a('Giriş\x20için\x20şu\x20adresi\x20açın:\x20'+b['verification_uri_complete']),a('ve\x20kodu\x20onaylayın:\x20'+b['user_code']);try{await a0b(b['verification_uri_complete']);}catch{a('Tarayıcı\x20otomatik\x20açılamadı;\x20yukarıdaki\x20adresi\x20elle\x20açın.');}const c=await pollForToken(cfg,{'deviceCode':b['device_code'],'interval':b['interval'],'expiresIn':b['expires_in']});await store['save']({'accessToken':c['access_token'],'refreshToken':c['refresh_token'],'expiresAt':decodeJwtExp(c['access_token']),'email':c['user']['email'],'userId':c['user']['id']}),a('Giriş\x20yapıldı:\x20'+c['user']['email']);}async function runWhoami(a){await getValidAccessToken(store,cfg);const b=await store['load']();if(!b)throw new NotLoggedInError();a(b['email']+'\x20('+b['userId']+')');}async function runLogout(a){await store['clear'](),a('Çıkış\x20yapıldı.');}var pkgJson=JSON['parse'](readFileSync(resolve(a0a(fileURLToPath(import.meta.url)),'..','..','package.json'),'utf-8')),program=new Command();program['name']('udf-cli')['description']('Convert\x20between\x20HTML\x20and\x20UYAP\x20UDF\x20file\x20format')['version'](pkgJson['version']),program['command']('html2udf')['description']('Convert\x20HTML\x20to\x20UDF\x20format')['argument']('<input>','HTML\x20input\x20file,\x20-\x20for\x20stdin,\x20or\x20raw\x20HTML\x20string')['argument']('[output]','UDF\x20output\x20file\x20(omit\x20for\x20stdout)')['action'](async(a,b)=>{try{await gate('html2udf');let c;if(a==='-')c=readFileSync(0x0,'utf-8');else a['includes']('<')||!existsSync(a)?c=a:c=readFileSync(a,'utf-8');const d=await htmlToUdf(c);b?writeFileSync(b,d):process['stdout']['write'](d);}catch(e){console['error']('Error:\x20'+(e instanceof Error?e['message']:e)),process['exit'](0x1);}}),program['command']('udf2html')['description']('Convert\x20UDF\x20to\x20HTML\x20format')['argument']('<input>','UDF\x20input\x20file\x20(use\x20-\x20for\x20stdin)')['argument']('[output]','HTML\x20output\x20file\x20(omit\x20for\x20stdout)')['action'](async(a,b)=>{try{await gate('udf2html');const c=a==='-'?readFileSync(0x0):readFileSync(a),d=await udfToHtml(Buffer['from'](c));b?writeFileSync(b,d,'utf-8'):process['stdout']['write'](d);}catch(e){console['error']('Error:\x20'+(e instanceof Error?e['message']:e)),process['exit'](0x1);}}),program['command']('udf2md')['description']('Convert\x20UDF\x20to\x20Markdown\x20format')['argument']('<input>','UDF\x20input\x20file\x20(use\x20-\x20for\x20stdin)')['argument']('[output]','Markdown\x20output\x20file\x20(omit\x20for\x20stdout)')['action'](async(a,b)=>{try{await gate('udf2md');const c=a==='-'?readFileSync(0x0):readFileSync(a),d=await udfToMarkdown(Buffer['from'](c));b?writeFileSync(b,d,'utf-8'):process['stdout']['write'](d);}catch(e){console['error']('Error:\x20'+(e instanceof Error?e['message']:e)),process['exit'](0x1);}}),program['command']('md2udf')['description']('Convert\x20Markdown\x20to\x20UDF\x20format')['argument']('<input>','Markdown\x20input\x20file,\x20-\x20for\x20stdin,\x20or\x20raw\x20Markdown\x20string')['argument']('[output]','UDF\x20output\x20file\x20(omit\x20for\x20stdout)')['action'](async(a,b)=>{try{await gate('md2udf');let c;if(a==='-')c=readFileSync(0x0,'utf-8');else existsSync(a)&&!a['includes']('\x0a')?c=readFileSync(a,'utf-8'):c=a;const d=await markdownToUdf(c);b?writeFileSync(b,d):process['stdout']['write'](d);}catch(e){console['error']('Error:\x20'+(e instanceof Error?e['message']:e)),process['exit'](0x1);}}),program['command']('sign')['description']('Sign\x20one\x20or\x20more\x20.udf\x20files\x20with\x20a\x20PKCS#11\x20e-signature\x20card\x20(CAdES-BES)')['argument']('<files...>','.udf\x20files\x20to\x20sign\x20in\x20place')['option']('-m,\x20--module\x20<path>','PKCS#11\x20driver\x20path\x20(auto-detected\x20if\x20omitted;\x20or\x20set\x20UDF_PKCS11_MODULE)')['option']('-p,\x20--pin\x20<pin>','card\x20PIN\x20(omit\x20to\x20enter\x20it\x20in\x20a\x20native\x20GUI\x20dialog;\x20or\x20set\x20UDF_PIN)')['option']('--extra-certs\x20<paths...>','intermediate\x20CA\x20certificate\x20files\x20(DER\x20or\x20PEM)\x20to\x20embed')['action'](async(a,b)=>{try{await gate('sign');const {resolveModules:c}=await import('../module-resolve-XD725NCC.js'),d=c(b['module']);d['length']===0x0&&(console['error']('Error:\x20no\x20PKCS#11\x20driver\x20found.\x20Install\x20your\x20card\x20software\x20(e.g.\x20AKİS),\x20pass\x20--module,\x20or\x20set\x20UDF_PKCS11_MODULE.'),process['exit'](0x1));let e=b['pin']??process['env']['UDF_PIN'];if(!e){const {promptPinGui:i}=await import('../pin-prompt-FSXBDU36.js');e=i();}const f=(b['extraCerts']??[])['flatMap'](j=>{const k=readFileSync(j),l=k['toString']('latin1'),m=l['match'](/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(m)return m['map'](n=>new Uint8Array(Buffer['from'](n['replace'](/-----[^-]+-----/g,'')['replace'](/\s+/g,''),'base64')));return[new Uint8Array(k)];}),{signUdfFiles:g}=await import('../sign-BNEXYCMC.js'),h=await g({'module':d,'pin':e,'files':a,'extraCertsDer':f});for(const j of h){console['error'](j['ok']?'signed:\x20'+j['file']:'FAILED:\x20'+j['file']+'\x20—\x20'+j['error']);}if(h['some'](k=>!k['ok']))process['exit'](0x1);}catch(k){console['error']('Error:\x20'+(k instanceof Error?k['message']:k)),process['exit'](0x1);}});var log=a=>process['stdout']['write'](a+'\x0a');program['command']('login')['description']('WorkOS\x20cihaz\x20akışıyla\x20giriş\x20yap\x20(dava-cli\x20ile\x20aynı\x20oturum)')['action'](async()=>{try{await runLogin(log);}catch(a){console['error']('Error:\x20'+(a instanceof Error?a['message']:a)),process['exit'](0x1);}}),program['command']('whoami')['description']('Giriş\x20yapılan\x20hesabı\x20göster')['action'](async()=>{try{await runWhoami(log);}catch(a){console['error']('Error:\x20'+(a instanceof Error?a['message']:a)),process['exit'](0x1);}}),program['command']('logout')['description']('Çıkış\x20yap\x20ve\x20kayıtlı\x20oturumu\x20temizle')['action'](async()=>{try{await runLogout(log);}catch(a){console['error']('Error:\x20'+(a instanceof Error?a['message']:a)),process['exit'](0x1);}}),program['parseAsync']();
|
|
2
|
+
import{htmlToUdf,markdownToUdf,udfToHtml,udfToMarkdown}from'../chunk-6564CQ7U.js';import{Command,Option}from'commander';import{existsSync,readFileSync,writeFileSync}from'fs';import{fileURLToPath}from'url';import{dirname as a0a,resolve}from'path';import a0b from'open';var DEFAULT_API_BASE='https://api.workos.com',DEFAULT_CLI_CLIENT_ID='client_01KRPJRBTG0YG5BCPMBXRA63QA';function loadAuthConfig(a=process['env']){return{'apiBase':a['WORKOS_API_BASE']??DEFAULT_API_BASE,'clientId':a['YARGI_CLI_CLIENT_ID']??DEFAULT_CLI_CLIENT_ID};}var DEFAULT_SERVER_URL='https://yargi.betaspacestudio.com';function loadServerConfig(a=process['env']){const b=a['YARGI_SERVER_URL']??DEFAULT_SERVER_URL;return{'serverUrl':b['replace'](/\/+$/,'')};}import{chmod,mkdir,readFile,writeFile,unlink,stat}from'fs/promises';import{homedir}from'os';import{dirname,join}from'path';import{z}from'zod';var StoredTokensSchema=z['object']({'accessToken':z['string'](),'refreshToken':z['string'](),'expiresAt':z['number'](),'email':z['string'](),'userId':z['string']()});function defaultTokenPath(a=process['env']){const b=a['XDG_CONFIG_HOME']??join(homedir(),'.config');return join(b,'yargi','token.json');}function decodeJwtExp(a){try{const b=a['split']('.')[0x1];if(!b)throw new Error('no\x20payload');const c=Buffer['from'](b,'base64url')['toString']('utf8'),d=JSON['parse'](c)['exp'];if(typeof d!=='number')throw new Error('no\x20exp');return d*0x3e8;}catch{return Date['now']()+0x5*0xea60;}}var FileTokenStore=class{constructor(a=defaultTokenPath()){this['path']=a;}['path'];async['load'](){let a;try{a=await readFile(this['path'],'utf8');}catch{return null;}try{const d=await stat(this['path']);(d['mode']&0x3f)!==0x0&&process['stderr']['write']('warning:\x20'+this['path']+'\x20has\x20loose\x20permissions;\x20expected\x200600\x0a');}catch{}let b;try{b=JSON['parse'](a);}catch{return null;}const c=StoredTokensSchema['safeParse'](b);return c['success']?c['data']:null;}async['save'](a){await mkdir(dirname(this['path']),{'recursive':!![],'mode':0x1c0}),await writeFile(this['path'],JSON['stringify'](a),{'mode':0x180}),await chmod(this['path'],0x180);}async['clear'](){try{await unlink(this['path']);}catch{}}};import{z as a0c}from'zod';var DeviceAuthorizationResponseSchema=a0c['object']({'device_code':a0c['string'](),'user_code':a0c['string'](),'verification_uri':a0c['string'](),'verification_uri_complete':a0c['string'](),'expires_in':a0c['number'](),'interval':a0c['number']()})['passthrough'](),WorkosUserSchema=a0c['object']({'id':a0c['string'](),'email':a0c['string']()})['passthrough'](),TokenResponseSchema=a0c['object']({'access_token':a0c['string'](),'refresh_token':a0c['string'](),'user':WorkosUserSchema})['passthrough'](),DeviceCodeExpiredError=class extends Error{constructor(){super('Device\x20code\x20expired.\x20Run\x20login\x20again.'),this['name']='DeviceCodeExpiredError';}},AuthorizationDeniedError=class extends Error{constructor(){super('Authorization\x20was\x20denied.'),this['name']='AuthorizationDeniedError';}},RefreshFailedError=class extends Error{constructor(){super('Token\x20refresh\x20failed.'),this['name']='RefreshFailedError';}},DEVICE_GRANT='urn:ietf:params:oauth:grant-type:device_code';async function postForm(a,b){const c=await fetch(a,{'method':'POST','headers':{'content-type':'application/x-www-form-urlencoded'},'body':new URLSearchParams(b)['toString']()}),d=await c['text']();let e=void 0x0;try{e=d?JSON['parse'](d):void 0x0;}catch{e=void 0x0;}return{'status':c['status'],'json':e};}async function startDeviceAuthorization(a){const {status:b,json:c}=await postForm(a['apiBase']+'/user_management/authorize/device',{'client_id':a['clientId']});if(b!==0xc8)throw new Error('device\x20authorization\x20failed\x20('+b+')');return DeviceAuthorizationResponseSchema['parse'](c);}var defaultSleep=a=>new Promise(b=>setTimeout(b,a));async function pollForToken(a,b,c={}){const d=c['sleep']??defaultSleep,e=Date['now']()+b['expiresIn']*0x3e8;let f=b['interval'];for(;;){if(Date['now']()>e)throw new DeviceCodeExpiredError();await d(f*0x3e8);const {status:g,json:h}=await postForm(a['apiBase']+'/user_management/authenticate',{'client_id':a['clientId'],'grant_type':DEVICE_GRANT,'device_code':b['deviceCode']});if(g===0xc8)return TokenResponseSchema['parse'](h);const i=h?.['error'];if(i==='authorization_pending')continue;if(i==='slow_down'){f+=0x5;continue;}if(i==='expired_token')throw new DeviceCodeExpiredError();if(i==='access_denied')throw new AuthorizationDeniedError();throw new Error('device\x20token\x20exchange\x20failed:\x20'+(i??g));}}async function refreshToken(a,b){const {status:c,json:d}=await postForm(a['apiBase']+'/user_management/authenticate',{'client_id':a['clientId'],'grant_type':'refresh_token','refresh_token':b});if(c!==0xc8)throw new RefreshFailedError();const e=TokenResponseSchema['safeParse'](d);if(!e['success'])throw new RefreshFailedError();return e['data'];}var NotLoggedInError=class extends Error{constructor(){super('Önce\x20giriş\x20yapmalısınız:\x20`udf-cli\x20login`'),this['name']='NotLoggedInError';}},AccountBannedError=class extends Error{constructor(a){super('Hesabınız\x20devre\x20dışı\x20bırakıldı'+(a?':\x20'+a:'.')),this['reason']=a,this['name']='AccountBannedError';}['reason'];},ServerUnreachableError=class extends Error{constructor(a){super('Sunucuya\x20ulaşılamadı:\x20'+a+'.\x20İnternet\x20bağlantınızı\x20kontrol\x20edip\x20tekrar\x20deneyin.'),this['name']='ServerUnreachableError';}},EXPIRY_SKEW_MS=0xea60;async function getValidAccessToken(a,b,c={}){const d=c['refresh']??refreshToken,e=await a['load']();if(!e)throw new NotLoggedInError();if(Date['now']()<e['expiresAt']-EXPIRY_SKEW_MS)return e['accessToken'];let f;try{f=await d(b,e['refreshToken']);}catch{await a['clear']();throw new NotLoggedInError();}const g={'accessToken':f['access_token'],'refreshToken':f['refresh_token'],'expiresAt':decodeJwtExp(f['access_token']),'email':f['user']['email'],'userId':f['user']['id']};try{await a['save'](g);}catch{return g['accessToken'];}return g['accessToken'];}async function reportActivation(a){const b=a['serverUrl']+'/api/cli/activations';let c;try{c=await fetch(b,{'method':'POST','headers':{'authorization':'Bearer\x20'+a['accessToken'],'content-type':'application/json'},'body':JSON['stringify']({'command':'udf','metadata':a['metadata']})});}catch(d){throw new ServerUnreachableError(d instanceof Error?d['message']:String(d));}if(c['status']===0x191)throw new NotLoggedInError();if(c['status']===0x193){const e=await c['json']()['catch'](()=>({}));if(e['error']==='banned')throw new AccountBannedError(e['reason']??null);throw new ServerUnreachableError('forbidden\x20('+(e['error']??'unknown')+')');}if(c['status']>=0x1f4)throw new ServerUnreachableError('HTTP\x20'+c['status']);if(!c['ok']){const f=await c['text']()['catch'](()=>'');throw new ServerUnreachableError('HTTP\x20'+c['status']+'\x20'+f['slice'](0x0,0xc8));}return await c['json']();}var cfg=loadAuthConfig(),serverCfg=loadServerConfig(),store=new FileTokenStore();async function gate(a){const b=await getValidAccessToken(store,cfg);await reportActivation({'serverUrl':serverCfg['serverUrl'],'accessToken':b,'metadata':{'action':a}});}async function runLogin(a){const b=await startDeviceAuthorization(cfg);a('Giriş\x20için\x20şu\x20adresi\x20açın:\x20'+b['verification_uri_complete']),a('ve\x20kodu\x20onaylayın:\x20'+b['user_code']);try{await a0b(b['verification_uri_complete']);}catch{a('Tarayıcı\x20otomatik\x20açılamadı;\x20yukarıdaki\x20adresi\x20elle\x20açın.');}const c=await pollForToken(cfg,{'deviceCode':b['device_code'],'interval':b['interval'],'expiresIn':b['expires_in']});await store['save']({'accessToken':c['access_token'],'refreshToken':c['refresh_token'],'expiresAt':decodeJwtExp(c['access_token']),'email':c['user']['email'],'userId':c['user']['id']}),a('Giriş\x20yapıldı:\x20'+c['user']['email']);}async function runWhoami(a){await getValidAccessToken(store,cfg);const b=await store['load']();if(!b)throw new NotLoggedInError();a(b['email']+'\x20('+b['userId']+')');}async function runLogout(a){await store['clear'](),a('Çıkış\x20yapıldı.');}var pkgJson=JSON['parse'](readFileSync(resolve(a0a(fileURLToPath(import.meta.url)),'..','..','package.json'),'utf-8')),program=new Command();program['name']('udf-cli')['description']('Convert\x20between\x20HTML\x20and\x20UYAP\x20UDF\x20file\x20format')['version'](pkgJson['version']),program['command']('html2udf')['description']('Convert\x20HTML\x20to\x20UDF\x20format')['argument']('<input>','HTML\x20input\x20file,\x20-\x20for\x20stdin,\x20or\x20raw\x20HTML\x20string')['argument']('[output]','UDF\x20output\x20file\x20(omit\x20for\x20stdout)')['action'](async(a,b)=>{try{await gate('html2udf');let c;if(a==='-')c=readFileSync(0x0,'utf-8');else a['includes']('<')||!existsSync(a)?c=a:c=readFileSync(a,'utf-8');const d=await htmlToUdf(c);b?writeFileSync(b,d):process['stdout']['write'](d);}catch(e){console['error']('Error:\x20'+(e instanceof Error?e['message']:e)),process['exit'](0x1);}}),program['command']('udf2html')['description']('Convert\x20UDF\x20to\x20HTML\x20format')['argument']('<input>','UDF\x20input\x20file\x20(use\x20-\x20for\x20stdin)')['argument']('[output]','HTML\x20output\x20file\x20(omit\x20for\x20stdout)')['action'](async(a,b)=>{try{await gate('udf2html');const c=a==='-'?readFileSync(0x0):readFileSync(a),d=await udfToHtml(Buffer['from'](c));b?writeFileSync(b,d,'utf-8'):process['stdout']['write'](d);}catch(e){console['error']('Error:\x20'+(e instanceof Error?e['message']:e)),process['exit'](0x1);}}),program['command']('udf2md')['description']('Convert\x20UDF\x20to\x20Markdown\x20format')['argument']('<input>','UDF\x20input\x20file\x20(use\x20-\x20for\x20stdin)')['argument']('[output]','Markdown\x20output\x20file\x20(omit\x20for\x20stdout)')['action'](async(a,b)=>{try{await gate('udf2md');const c=a==='-'?readFileSync(0x0):readFileSync(a),d=await udfToMarkdown(Buffer['from'](c));b?writeFileSync(b,d,'utf-8'):process['stdout']['write'](d);}catch(e){console['error']('Error:\x20'+(e instanceof Error?e['message']:e)),process['exit'](0x1);}}),program['command']('md2udf')['description']('Convert\x20Markdown\x20to\x20UDF\x20format')['argument']('<input>','Markdown\x20input\x20file,\x20-\x20for\x20stdin,\x20or\x20raw\x20Markdown\x20string')['argument']('[output]','UDF\x20output\x20file\x20(omit\x20for\x20stdout)')['action'](async(a,b)=>{try{const c=!![];console['error']('md2udf\x20is\x20no\x20longer\x20supported;\x20use\x20html2udf\x20instead.');if(c)return;await gate('md2udf');let d;if(a==='-')d=readFileSync(0x0,'utf-8');else existsSync(a)&&!a['includes']('\x0a')?d=readFileSync(a,'utf-8'):d=a;const e=await markdownToUdf(d);b?writeFileSync(b,e):process['stdout']['write'](e);}catch(f){console['error']('Error:\x20'+(f instanceof Error?f['message']:f)),process['exit'](0x1);}}),program['command']('sign')['description']('Sign\x20one\x20or\x20more\x20.udf\x20files\x20with\x20a\x20PKCS#11\x20e-signature\x20card\x20(CAdES-BES)')['argument']('<files...>','.udf\x20files\x20to\x20sign\x20in\x20place')['option']('-m,\x20--module\x20<path>','PKCS#11\x20driver\x20path\x20(auto-detected\x20if\x20omitted;\x20or\x20set\x20UDF_PKCS11_MODULE)')['option']('-p,\x20--pin\x20<pin>','card\x20PIN\x20(omit\x20to\x20enter\x20it\x20in\x20a\x20native\x20GUI\x20dialog;\x20or\x20set\x20UDF_PIN)')['option']('--extra-certs\x20<paths...>','intermediate\x20CA\x20certificate\x20files\x20(DER\x20or\x20PEM)\x20to\x20embed')['addOption'](new Option('--mobile','use\x20mobile\x20signature\x20(UYAP\x20MSS)')['hideHelp']())['addOption'](new Option('--phone\x20<no>','GSM\x20number\x20for\x20--mobile\x20(or\x20UDF_PHONE)')['hideHelp']())['addOption'](new Option('--operator\x20<name>','GSM\x20operator:\x20turkcell|tt|vodafone\x20(or\x20UDF_OPERATOR)')['hideHelp']())['addOption'](new Option('--display\x20<text>','text\x20shown\x20on\x20the\x20phone\x20during\x20mobile\x20signing')['hideHelp']())['action'](async(a,b)=>{try{await gate('sign');if(b['mobile']){const i=b['phone']??process['env']['UDF_PHONE'];!i&&(console['error']('Error:\x20--mobile\x20için\x20telefon\x20gerekli:\x20--phone\x2005XXXXXXXXX\x20(veya\x20UDF_PHONE).'),process['exit'](0x1));const j={'turkcell':0x1,'tt':0x2,'turktelekom':0x2,'türktelekom':0x2,'vodafone':0x3},k=(b['operator']??process['env']['UDF_OPERATOR']??'')['toLowerCase']()['replace'](/\s+/g,''),l=j[k];!l&&(console['error']('Error:\x20--mobile\x20için\x20operatör\x20gerekli:\x20--operator\x20turkcell|tt|vodafone\x20(veya\x20UDF_OPERATOR).'),process['exit'](0x1));const {signUdfFilesMobile:m}=await import('../mobile-4VK2JOUT.js'),n=await m({'files':a,'phone':i,'operator':l,...b['display']?{'displayText':b['display']}:{},'log':o=>console['error'](o)});for(const o of n){console['error'](o['ok']?'signed:\x20'+o['file']:'FAILED:\x20'+o['file']+'\x20—\x20'+o['error']);}if(n['some'](p=>!p['ok']))process['exit'](0x1);return;}const {resolveModules:c}=await import('../module-resolve-XD725NCC.js'),d=c(b['module']);d['length']===0x0&&(console['error']('Error:\x20no\x20PKCS#11\x20driver\x20found.\x20Install\x20your\x20card\x20software\x20(e.g.\x20AKİS),\x20pass\x20--module,\x20or\x20set\x20UDF_PKCS11_MODULE.'),process['exit'](0x1));let e=b['pin']??process['env']['UDF_PIN'];if(!e){const {promptPinGui:p}=await import('../pin-prompt-FSXBDU36.js');e=p();}const f=(b['extraCerts']??[])['flatMap'](q=>{const s=readFileSync(q),t=s['toString']('latin1'),u=t['match'](/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(u)return u['map'](v=>new Uint8Array(Buffer['from'](v['replace'](/-----[^-]+-----/g,'')['replace'](/\s+/g,''),'base64')));return[new Uint8Array(s)];}),{signUdfFiles:g}=await import('../sign-AELEVJHO.js'),h=await g({'module':d,'pin':e,'files':a,'extraCertsDer':f});for(const q of h){console['error'](q['ok']?'signed:\x20'+q['file']:'FAILED:\x20'+q['file']+'\x20—\x20'+q['error']);}if(h['some'](s=>!s['ok']))process['exit'](0x1);}catch(s){console['error']('Error:\x20'+(s instanceof Error?s['message']:s)),process['exit'](0x1);}});var log=a=>process['stdout']['write'](a+'\x0a');program['command']('login')['description']('WorkOS\x20cihaz\x20akışıyla\x20giriş\x20yap\x20(dava-cli\x20ile\x20aynı\x20oturum)')['action'](async()=>{try{await runLogin(log);}catch(a){console['error']('Error:\x20'+(a instanceof Error?a['message']:a)),process['exit'](0x1);}}),program['command']('whoami')['description']('Giriş\x20yapılan\x20hesabı\x20göster')['action'](async()=>{try{await runWhoami(log);}catch(a){console['error']('Error:\x20'+(a instanceof Error?a['message']:a)),process['exit'](0x1);}}),program['command']('logout')['description']('Çıkış\x20yap\x20ve\x20kayıtlı\x20oturumu\x20temizle')['action'](async()=>{try{await runLogout(log);}catch(a){console['error']('Error:\x20'+(a instanceof Error?a['message']:a)),process['exit'](0x1);}}),program['parseAsync']();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import a2a from'jszip';async function readContentXml(a){const b=await a2a['loadAsync'](a),c=b['file']('content.xml');if(!c)throw new Error('content.xml\x20not\x20found\x20in\x20.udf');return new Uint8Array(await c['async']('uint8array'));}async function writeSignature(a,b){const c=await a2a['loadAsync'](a),d=c['file']('content.xml');if(!d)throw new Error('content.xml\x20not\x20found\x20in\x20.udf');return c['file']('sign.sgn',b),c['generateAsync']({'type':'uint8array','compression':'DEFLATE'});}export{readContentXml,writeSignature};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readContentXml,writeSignature}from'./chunk-UMC6EI4C.js';import{readFile,writeFile}from'fs/promises';var DEFAULT_MIMZA_ENDPOINT='https://vatandas.uyap.gov.tr/mimzaclient/services/MImzaSigner',NS='http://client.mimza.uyap.gov.tr';function xmlEscape(a){return a['replace'](/&/g,'&')['replace'](/</g,'<')['replace'](/>/g,'>');}function tag(a,b){const c=a['match'](new RegExp('<(?:\x5cw+:)?'+b+'\x5cb[^>]*>([\x5cs\x5cS]*?)</(?:\x5cw+:)?'+b+'>'));return c?c[0x1]:'';}async function call(a,b,c){const d=c['endpoint']??DEFAULT_MIMZA_ENDPOINT,e='<soapenv:Envelope\x20xmlns:soapenv=\x22http://schemas.xmlsoap.org/soap/envelope/\x22\x20xmlns:cli=\x22'+NS+'\x22><soapenv:Body><cli:'+a+'>'+b+'</cli:'+a+'></soapenv:Body></soapenv:Envelope>',f=new AbortController(),g=setTimeout(()=>f['abort'](),c['timeoutMs']??0x2bf20);let h;try{h=await fetch(d,{'method':'POST','headers':{'content-type':'text/xml;\x20charset=utf-8','soapaction':'\x22\x22'},'body':e,'signal':f['signal']});}catch(j){throw new Error('mobil\x20imza\x20servisine\x20ulaşılamadı:\x20'+(j instanceof Error?j['message']:String(j)));}finally{clearTimeout(g);}const i=await h['text']();if(!h['ok']){const k=tag(i,'faultstring');throw new Error('mobil\x20imza\x20servisi\x20hatası\x20(HTTP\x20'+h['status']+')'+(k?':\x20'+k:''));}return i;}async function getHash(a,b,c,d={}){const e=Buffer['from'](a)['toString']('base64'),f='<dataToBeSigned>'+e+'</dataToBeSigned><telNo>'+xmlEscape(b)+'</telNo><gsmOperator>'+c+'</gsmOperator>',g=await call('getHash',f,d),h=g['match'](/<(?:\w+:)?getHashReturn\b[^>]*>([\s\S]*?)<\/(?:\w+:)?getHashReturn>/)?.[0x1]??g;return{'resultCode':Number(tag(h,'resultCode')||'-1'),'apTransId':tag(h,'apTransId'),'fingerPrint':tag(h,'fingerPrint'),'message':tag(h,'message')};}async function getSignature(a,b,c={}){const d='<dataToBeDisplayed>'+xmlEscape(a)+'</dataToBeDisplayed><apTransId>'+xmlEscape(b)+'</apTransId>',e=await call('getSignature',d,c),f=e['match'](/<(?:\w+:)?getSignatureReturn\b[^>]*>([\s\S]*?)<\/(?:\w+:)?getSignatureReturn>/)?.[0x1]??e,g=tag(f,'data');return{'resultCode':Number(tag(f,'resultCode')||'-1'),'data':g?new Uint8Array(Buffer['from'](g,'base64')):new Uint8Array(0x0),'signerName':tag(f,'signerName'),'message':tag(f,'message')};}async function signUdfFilesMobile(a){const b=[];for(const c of a['files']){try{const d=new Uint8Array(await readFile(c)),e=await readContentXml(d),f=a['displayText']??'UYAP\x20UDF\x20imzalama',g=await getHash(e,a['phone'],a['operator'],a['client']);if(g['resultCode']!==0x0)throw new Error(g['message']||'doğrulama\x20kodu\x20alınamadı\x20(resultCode\x20'+g['resultCode']+')');a['log']('Doğrulama\x20kodu:\x20'+g['fingerPrint']),a['log']('Telefonunuzda\x20bu\x20kodu\x20doğrulayıp\x20PIN\x20ile\x20onaylayın…');const h=await getSignature(f,g['apTransId'],a['client']);if(h['resultCode']!==0x0||h['data']['length']===0x0)throw new Error(h['message']||'imza\x20alınamadı\x20(resultCode\x20'+h['resultCode']+')');const i=await writeSignature(d,h['data']);await writeFile(c,i),b['push']({'file':c,'ok':!![]}),a['log']('imzalandı:\x20'+c+(h['signerName']?'\x20('+h['signerName']+')':''));}catch(j){b['push']({'file':c,'ok':![],'error':j instanceof Error?j['message']:String(j)});}}return b;}export{signUdfFilesMobile};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readContentXml,writeSignature}from'./chunk-UMC6EI4C.js';import{readFile,writeFile}from'fs/promises';import{AsnConvert,OctetString}from'@peculiar/asn1-schema';import{ContentInfo,SignedData,SignerInfo,SignerInfos,SignerIdentifier,IssuerAndSerialNumber,EncapsulatedContentInfo,Attribute,DigestAlgorithmIdentifiers,CertificateSet,CertificateChoices}from'@peculiar/asn1-cms';import{AlgorithmIdentifier,Certificate,GeneralName,GeneralNames}from'@peculiar/asn1-x509';import{SigningCertificateV2,ESSCertIDv2,IssuerSerial}from'@peculiar/asn1-ess';import*as a6a from'asn1js';import{createHash}from'crypto';function sha256(a){return new Uint8Array(createHash('sha256')['update'](a)['digest']());}var OID_PKCS7_DATA='1.2.840.113549.1.7.1',OID_SIGNED_DATA='1.2.840.113549.1.7.2',OID_CONTENT_TYPE='1.2.840.113549.1.9.3',OID_MESSAGE_DIGEST='1.2.840.113549.1.9.4',OID_SIGNING_TIME='1.2.840.113549.1.9.5',OID_SIGNING_CERTIFICATE_V2='1.2.840.113549.1.9.16.2.47',OID_SHA256='2.16.840.1.101.3.4.2.1',OID_SHA256_WITH_RSA='1.2.840.113549.1.1.11',DER_NULL=new Uint8Array([0x5,0x0])['buffer'];function attr(a,b){return new Attribute({'attrType':a,'attrValues':[b]});}function toAb(a){return a['buffer']['slice'](a['byteOffset'],a['byteOffset']+a['byteLength']);}function algoSha256(){return new AlgorithmIdentifier({'algorithm':OID_SHA256});}function algoRsaSha256(){return new AlgorithmIdentifier({'algorithm':OID_SHA256_WITH_RSA,'parameters':DER_NULL});}function derLen(a){if(a<0x80)return new Uint8Array([a]);const b=[];let c=a;while(c>0x0){b['unshift'](c&0xff),c>>=0x8;}return new Uint8Array([0x80|b['length'],...b]);}function derSetOf(a){const b=a['reduce']((g,h)=>g+h['length'],0x0),c=derLen(b),d=new Uint8Array(0x1+c['length']+b);d[0x0]=0x31,d['set'](c,0x1);let f=0x1+c['length'];for(const g of a){d['set'](g,f),f+=g['length'];}return d;}function buildSigningCertificateV2(a,b){const c=new ESSCertIDv2({'certHash':new OctetString(toAb(sha256(b))),'issuerSerial':new IssuerSerial({'issuer':new GeneralNames([new GeneralName({'directoryName':a['tbsCertificate']['issuer']})]),'serialNumber':a['tbsCertificate']['serialNumber']})});return AsnConvert['serialize'](new SigningCertificateV2({'certs':[c]}));}function buildSignSgn(a){const {contentXml:b,certChainDer:c,sign:d,signingTime:e}=a,f=c[0x0],g=AsnConvert['parse'](toAb(f),Certificate),h=new a6a['ObjectIdentifier']({'value':OID_PKCS7_DATA})['toBER'](),i=new a6a['OctetString']({'valueHex':toAb(sha256(b))})['toBER'](),j=new a6a['UTCTime']({'valueDate':e})['toBER'](),k=buildSigningCertificateV2(g,f);let l=[attr(OID_CONTENT_TYPE,h),attr(OID_MESSAGE_DIGEST,i),attr(OID_SIGNING_TIME,j),attr(OID_SIGNING_CERTIFICATE_V2,k)];const m=l['map'](t=>({'a':t,'der':new Uint8Array(AsnConvert['serialize'](t))}))['sort']((t,u)=>cmpBytes(t['der'],u['der']));l=m['map'](t=>t['a']);const n=derSetOf(m['map'](t=>t['der'])),o=d(n),p=new SignerInfo({'version':0x1,'sid':new SignerIdentifier({'issuerAndSerialNumber':new IssuerAndSerialNumber({'issuer':g['tbsCertificate']['issuer'],'serialNumber':g['tbsCertificate']['serialNumber']})}),'digestAlgorithm':algoSha256(),'signedAttrs':l,'signatureAlgorithm':algoRsaSha256(),'signature':new OctetString(toAb(o))}),q=new CertificateSet(c['map'](t=>new CertificateChoices({'certificate':AsnConvert['parse'](toAb(t),Certificate)}))),r=new SignedData({'version':0x1,'digestAlgorithms':new DigestAlgorithmIdentifiers([algoSha256()]),'encapContentInfo':new EncapsulatedContentInfo({'eContentType':OID_PKCS7_DATA}),'certificates':q,'signerInfos':new SignerInfos([p])}),s=new ContentInfo({'contentType':OID_SIGNED_DATA,'content':AsnConvert['serialize'](r)});return new Uint8Array(AsnConvert['serialize'](s));}function cmpBytes(c,d){const e=Math['min'](c['length'],d['length']);for(let f=0x0;f<e;f++){if(c[f]!==d[f])return c[f]-d[f];}return c['length']-d['length'];}import a6b from'koffi';import{AsnConvert as a6c}from'@peculiar/asn1-schema';import{Certificate as a6d,KeyUsage,id_ce_keyUsage}from'@peculiar/asn1-x509';function toAb2(a){return a['buffer']['slice'](a['byteOffset'],a['byteOffset']+a['byteLength']);}function selectSigningCert(a){for(let b=0x0;b<a['length'];b++){const c=a6c['parse'](toAb2(a[b]),a6d),d=(c['tbsCertificate']['extensions']??[])['find'](f=>f['extnID']===id_ce_keyUsage);if(!d)continue;const e=a6c['parse'](d['extnValue']['buffer'],KeyUsage);if(e['toJSON']()['includes']('nonRepudiation'))return b;}return 0x0;}var CKF_SERIAL_SESSION=0x4,CKU_USER=0x1,CKO_CERTIFICATE=0x2,CKO_PRIVATE_KEY=0x3,CKA_CLASS=0x0,CKA_VALUE=0x11,CKA_ID=0x102,CKM_SHA256_RSA_PKCS=0x40,CKM_RSA_PKCS=0x1,CKR_PIN_INCORRECT=0xa0,CKR_PIN_LOCKED=0xa4,CKR_MECHANISM_INVALID=0x70,SHA256_DIGESTINFO_PREFIX=new Uint8Array([0x30,0x31,0x30,0xd,0x6,0x9,0x60,0x86,0x48,0x1,0x65,0x3,0x4,0x2,0x1,0x5,0x0,0x4,0x20]);function openSession(a,b){const c=Array['isArray'](a)?a:[a];if(c['length']===0x0)throw new Error('No\x20PKCS#11\x20driver\x20found.\x20Install\x20your\x20card\x20software\x20(e.g.\x20AKİS),\x20pass\x20--module,\x20or\x20set\x20UDF_PKCS11_MODULE.');let d;const f=[];for(const y of c){try{d=a6b['load'](y);break;}catch(z){f['push'](y+':\x20'+z['message']);}}if(!d)throw new Error('Could\x20not\x20load\x20any\x20PKCS#11\x20driver:\x0a\x20\x20'+f['join']('\x0a\x20\x20')+'\x0aPass\x20--module\x20or\x20set\x20UDF_PKCS11_MODULE.');const g='unsigned\x20long',h=d['func']('unsigned\x20long\x20C_Initialize(void\x20*)'),i=d['func']('unsigned\x20long\x20C_GetSlotList(bool,\x20_Out_\x20'+g+'\x20*,\x20_Inout_\x20'+g+'\x20*)'),j=d['func']('unsigned\x20long\x20C_OpenSession('+g+',\x20'+g+',\x20void\x20*,\x20void\x20*,\x20_Out_\x20'+g+'\x20*)'),k=d['func']('unsigned\x20long\x20C_Login('+g+',\x20'+g+',\x20const\x20char\x20*,\x20'+g+')'),l=d['func']('unsigned\x20long\x20C_FindObjectsInit('+g+',\x20void\x20*,\x20'+g+')'),m=d['func']('unsigned\x20long\x20C_FindObjects('+g+',\x20_Out_\x20'+g+'\x20*,\x20'+g+',\x20_Out_\x20'+g+'\x20*)'),n=d['func']('unsigned\x20long\x20C_FindObjectsFinal('+g+')'),o=d['func']('unsigned\x20long\x20C_GetAttributeValue('+g+',\x20'+g+',\x20void\x20*,\x20'+g+')'),q=d['func']('unsigned\x20long\x20C_SignInit('+g+',\x20void\x20*,\x20'+g+')'),r=d['func']('unsigned\x20long\x20C_Sign('+g+',\x20const\x20uint8_t\x20*,\x20'+g+',\x20_Out_\x20uint8_t\x20*,\x20_Inout_\x20'+g+'\x20*)'),s=d['func']('unsigned\x20long\x20C_Logout('+g+')'),t=d['func']('unsigned\x20long\x20C_CloseSession('+g+')'),u=d['func']('unsigned\x20long\x20C_Finalize(void\x20*)'),v=(A,B)=>{if(A!==0x0)throw new Error('PKCS#11\x20'+B+'\x20failed:\x200x'+A['toString'](0x10));};v(h(null),'C_Initialize');let w;const x=()=>{try{if(w!==void 0x0)s(w);}catch{}try{if(w!==void 0x0)t(w);}catch{}try{u(null);}catch{}};try{const A=[0x0];v(i(!![],null,A),'C_GetSlotList(count)');if(A[0x0]<0x1)throw new Error('no\x20PKCS#11\x20token\x20present');const B=new Array(A[0x0])['fill'](0x0);v(i(!![],B,A),'C_GetSlotList');const C=B[0x0],D=[0x0];v(j(C,CKF_SERIAL_SESSION,null,null,D),'C_OpenSession'),w=D[0x0];const E=k(w,CKU_USER,b,Buffer['byteLength'](b,'utf8'));if(E===CKR_PIN_INCORRECT)throw new Error('PIN\x20incorrect\x20—\x20aborting.\x20Do\x20NOT\x20retry;\x20the\x20card\x20locks\x20after\x20~3\x20attempts.');if(E===CKR_PIN_LOCKED)throw new Error('PIN\x20is\x20locked\x20—\x20unlock\x20the\x20card\x20with\x20its\x20PUK\x20before\x20signing.');v(E,'C_Login');const F=a6b['struct']('CK_ATTRIBUTE',{'type':'unsigned\x20long','pValue':'void\x20*','ulValueLen':'unsigned\x20long'}),G=T=>{const U=T['map'](W=>({'type':W['type'],'pValue':W['value'],'ulValueLen':W['value']?W['value']['length']:0x0}));v(l(w,a6b['as'](U,a6b['array'](F,U['length'])),U['length']),'C_FindObjectsInit');const V=[];for(;;){const W=[0x0],X=[0x0];v(m(w,X,0x1,W),'C_FindObjects');if(W[0x0]===0x0)break;V['push'](X[0x0]);}return v(n(w),'C_FindObjectsFinal'),V;},H=(T,U)=>{const V=[{'type':U,'pValue':null,'ulValueLen':0x0}];v(o(w,T,a6b['as'](V,a6b['array'](F,0x1)),0x1),'C_GetAttributeValue(len)');const W=Number(V[0x0]['ulValueLen']),X=Buffer['alloc'](W),Y=[{'type':U,'pValue':X,'ulValueLen':W}];return v(o(w,T,a6b['as'](Y,a6b['array'](F,0x1)),0x1),'C_GetAttributeValue'),X;},I=a6b['sizeof']('unsigned\x20long'),J=T=>{const U=Buffer['alloc'](I);if(I===0x8)U['writeBigUInt64LE'](BigInt(T));else U['writeUInt32LE'](T);return U;},K=G([{'type':CKA_CLASS,'value':J(CKO_CERTIFICATE)}]);if(K['length']===0x0)throw new Error('no\x20certificate\x20found\x20on\x20token');const L=K['map'](T=>({'der':new Uint8Array(H(T,CKA_VALUE)),'id':H(T,CKA_ID)})),M=L[selectSigningCert(L['map'](T=>T['der']))],N=G([{'type':CKA_CLASS,'value':J(CKO_PRIVATE_KEY)}]);if(N['length']===0x0)throw new Error('no\x20private\x20key\x20found\x20on\x20token');let O;for(const T of N){if(H(T,CKA_ID)['equals'](M['id'])){O=T;break;}}if(O===void 0x0)throw new Error('no\x20private\x20key\x20matches\x20the\x20selected\x20signing\x20certificate\x20(CKA_ID)');const P=[M['der']],Q=a6b['struct']('CK_MECHANISM',{'mechanism':'unsigned\x20long','pParameter':'void\x20*','ulParameterLen':'unsigned\x20long'}),R=(U,V)=>{const W=[{'mechanism':U,'pParameter':null,'ulParameterLen':0x0}],X=q(w,a6b['as'](W,a6b['array'](Q,0x1)),O);if(X===CKR_MECHANISM_INVALID)throw Object['assign'](new Error('mechanism\x20invalid'),{'ckr':CKR_MECHANISM_INVALID});v(X,'C_SignInit');const Y=Buffer['from'](V),Z=[0x0];v(r(w,Y,Y['length'],null,Z),'C_Sign(len)');const a0=Buffer['alloc'](Number(Z[0x0]));return v(r(w,Y,Y['length'],a0,Z),'C_Sign'),new Uint8Array(a0['subarray'](0x0,Number(Z[0x0])));},S=U=>{try{return R(CKM_SHA256_RSA_PKCS,U);}catch(V){if(V['ckr']!==CKR_MECHANISM_INVALID)throw V;const W=new Uint8Array(SHA256_DIGESTINFO_PREFIX['length']+0x20);return W['set'](SHA256_DIGESTINFO_PREFIX,0x0),W['set'](sha256(U),SHA256_DIGESTINFO_PREFIX['length']),R(CKM_RSA_PKCS,W);}};return{'certChainDer':P,'sign':S,'close':x};}catch(U){x();throw U;}}async function signUdfFiles(a){const b=openSession(a['module'],a['pin']),c=[...b['certChainDer'],...a['extraCertsDer']??[]],d=[];try{for(const e of a['files']){try{const f=new Uint8Array(await readFile(e)),g=await readContentXml(f),h=buildSignSgn({'contentXml':g,'certChainDer':c,'sign':b['sign'],'signingTime':new Date()}),i=await writeSignature(f,h);await writeFile(e,i),d['push']({'file':e,'ok':!![]});}catch(j){d['push']({'file':e,'ok':![],'error':j instanceof Error?j['message']:String(j)});}}}finally{b['close']();}return d;}export{signUdfFiles};
|
package/package.json
CHANGED
package/dist/sign-BNEXYCMC.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{readFile,writeFile}from'fs/promises';import a4a from'jszip';async function readContentXml(a){const b=await a4a['loadAsync'](a),c=b['file']('content.xml');if(!c)throw new Error('content.xml\x20not\x20found\x20in\x20.udf');return new Uint8Array(await c['async']('uint8array'));}async function writeSignature(a,b){const c=await a4a['loadAsync'](a),d=c['file']('content.xml');if(!d)throw new Error('content.xml\x20not\x20found\x20in\x20.udf');return c['file']('sign.sgn',b),c['generateAsync']({'type':'uint8array','compression':'DEFLATE'});}import{AsnConvert,OctetString}from'@peculiar/asn1-schema';import{ContentInfo,SignedData,SignerInfo,SignerInfos,SignerIdentifier,IssuerAndSerialNumber,EncapsulatedContentInfo,Attribute,DigestAlgorithmIdentifiers,CertificateSet,CertificateChoices}from'@peculiar/asn1-cms';import{AlgorithmIdentifier,Certificate,GeneralName,GeneralNames}from'@peculiar/asn1-x509';import{SigningCertificateV2,ESSCertIDv2,IssuerSerial}from'@peculiar/asn1-ess';import*as a4b from'asn1js';import{createHash}from'crypto';function sha256(a){return new Uint8Array(createHash('sha256')['update'](a)['digest']());}var OID_PKCS7_DATA='1.2.840.113549.1.7.1',OID_SIGNED_DATA='1.2.840.113549.1.7.2',OID_CONTENT_TYPE='1.2.840.113549.1.9.3',OID_MESSAGE_DIGEST='1.2.840.113549.1.9.4',OID_SIGNING_TIME='1.2.840.113549.1.9.5',OID_SIGNING_CERTIFICATE_V2='1.2.840.113549.1.9.16.2.47',OID_SHA256='2.16.840.1.101.3.4.2.1',OID_SHA256_WITH_RSA='1.2.840.113549.1.1.11',DER_NULL=new Uint8Array([0x5,0x0])['buffer'];function attr(a,b){return new Attribute({'attrType':a,'attrValues':[b]});}function toAb(a){return a['buffer']['slice'](a['byteOffset'],a['byteOffset']+a['byteLength']);}function algoSha256(){return new AlgorithmIdentifier({'algorithm':OID_SHA256});}function algoRsaSha256(){return new AlgorithmIdentifier({'algorithm':OID_SHA256_WITH_RSA,'parameters':DER_NULL});}function derLen(a){if(a<0x80)return new Uint8Array([a]);const b=[];let c=a;while(c>0x0){b['unshift'](c&0xff),c>>=0x8;}return new Uint8Array([0x80|b['length'],...b]);}function derSetOf(a){const b=a['reduce']((g,h)=>g+h['length'],0x0),c=derLen(b),d=new Uint8Array(0x1+c['length']+b);d[0x0]=0x31,d['set'](c,0x1);let f=0x1+c['length'];for(const g of a){d['set'](g,f),f+=g['length'];}return d;}function buildSigningCertificateV2(a,b){const c=new ESSCertIDv2({'certHash':new OctetString(toAb(sha256(b))),'issuerSerial':new IssuerSerial({'issuer':new GeneralNames([new GeneralName({'directoryName':a['tbsCertificate']['issuer']})]),'serialNumber':a['tbsCertificate']['serialNumber']})});return AsnConvert['serialize'](new SigningCertificateV2({'certs':[c]}));}function buildSignSgn(a){const {contentXml:b,certChainDer:c,sign:d,signingTime:e}=a,f=c[0x0],g=AsnConvert['parse'](toAb(f),Certificate),h=new a4b['ObjectIdentifier']({'value':OID_PKCS7_DATA})['toBER'](),i=new a4b['OctetString']({'valueHex':toAb(sha256(b))})['toBER'](),j=new a4b['UTCTime']({'valueDate':e})['toBER'](),k=buildSigningCertificateV2(g,f);let l=[attr(OID_CONTENT_TYPE,h),attr(OID_MESSAGE_DIGEST,i),attr(OID_SIGNING_TIME,j),attr(OID_SIGNING_CERTIFICATE_V2,k)];const m=l['map'](t=>({'a':t,'der':new Uint8Array(AsnConvert['serialize'](t))}))['sort']((t,u)=>cmpBytes(t['der'],u['der']));l=m['map'](t=>t['a']);const n=derSetOf(m['map'](t=>t['der'])),o=d(n),p=new SignerInfo({'version':0x1,'sid':new SignerIdentifier({'issuerAndSerialNumber':new IssuerAndSerialNumber({'issuer':g['tbsCertificate']['issuer'],'serialNumber':g['tbsCertificate']['serialNumber']})}),'digestAlgorithm':algoSha256(),'signedAttrs':l,'signatureAlgorithm':algoRsaSha256(),'signature':new OctetString(toAb(o))}),q=new CertificateSet(c['map'](t=>new CertificateChoices({'certificate':AsnConvert['parse'](toAb(t),Certificate)}))),r=new SignedData({'version':0x1,'digestAlgorithms':new DigestAlgorithmIdentifiers([algoSha256()]),'encapContentInfo':new EncapsulatedContentInfo({'eContentType':OID_PKCS7_DATA}),'certificates':q,'signerInfos':new SignerInfos([p])}),s=new ContentInfo({'contentType':OID_SIGNED_DATA,'content':AsnConvert['serialize'](r)});return new Uint8Array(AsnConvert['serialize'](s));}function cmpBytes(c,d){const e=Math['min'](c['length'],d['length']);for(let f=0x0;f<e;f++){if(c[f]!==d[f])return c[f]-d[f];}return c['length']-d['length'];}import a4c from'koffi';import{AsnConvert as a4d}from'@peculiar/asn1-schema';import{Certificate as a4e,KeyUsage,id_ce_keyUsage}from'@peculiar/asn1-x509';function toAb2(a){return a['buffer']['slice'](a['byteOffset'],a['byteOffset']+a['byteLength']);}function selectSigningCert(a){for(let b=0x0;b<a['length'];b++){const c=a4d['parse'](toAb2(a[b]),a4e),d=(c['tbsCertificate']['extensions']??[])['find'](f=>f['extnID']===id_ce_keyUsage);if(!d)continue;const e=a4d['parse'](d['extnValue']['buffer'],KeyUsage);if(e['toJSON']()['includes']('nonRepudiation'))return b;}return 0x0;}var CKF_SERIAL_SESSION=0x4,CKU_USER=0x1,CKO_CERTIFICATE=0x2,CKO_PRIVATE_KEY=0x3,CKA_CLASS=0x0,CKA_VALUE=0x11,CKA_ID=0x102,CKM_SHA256_RSA_PKCS=0x40,CKM_RSA_PKCS=0x1,CKR_PIN_INCORRECT=0xa0,CKR_PIN_LOCKED=0xa4,CKR_MECHANISM_INVALID=0x70,SHA256_DIGESTINFO_PREFIX=new Uint8Array([0x30,0x31,0x30,0xd,0x6,0x9,0x60,0x86,0x48,0x1,0x65,0x3,0x4,0x2,0x1,0x5,0x0,0x4,0x20]);function openSession(a,b){const c=Array['isArray'](a)?a:[a];if(c['length']===0x0)throw new Error('No\x20PKCS#11\x20driver\x20found.\x20Install\x20your\x20card\x20software\x20(e.g.\x20AKİS),\x20pass\x20--module,\x20or\x20set\x20UDF_PKCS11_MODULE.');let d;const f=[];for(const y of c){try{d=a4c['load'](y);break;}catch(z){f['push'](y+':\x20'+z['message']);}}if(!d)throw new Error('Could\x20not\x20load\x20any\x20PKCS#11\x20driver:\x0a\x20\x20'+f['join']('\x0a\x20\x20')+'\x0aPass\x20--module\x20or\x20set\x20UDF_PKCS11_MODULE.');const g='unsigned\x20long',h=d['func']('unsigned\x20long\x20C_Initialize(void\x20*)'),i=d['func']('unsigned\x20long\x20C_GetSlotList(bool,\x20_Out_\x20'+g+'\x20*,\x20_Inout_\x20'+g+'\x20*)'),j=d['func']('unsigned\x20long\x20C_OpenSession('+g+',\x20'+g+',\x20void\x20*,\x20void\x20*,\x20_Out_\x20'+g+'\x20*)'),k=d['func']('unsigned\x20long\x20C_Login('+g+',\x20'+g+',\x20const\x20char\x20*,\x20'+g+')'),l=d['func']('unsigned\x20long\x20C_FindObjectsInit('+g+',\x20void\x20*,\x20'+g+')'),m=d['func']('unsigned\x20long\x20C_FindObjects('+g+',\x20_Out_\x20'+g+'\x20*,\x20'+g+',\x20_Out_\x20'+g+'\x20*)'),n=d['func']('unsigned\x20long\x20C_FindObjectsFinal('+g+')'),o=d['func']('unsigned\x20long\x20C_GetAttributeValue('+g+',\x20'+g+',\x20void\x20*,\x20'+g+')'),q=d['func']('unsigned\x20long\x20C_SignInit('+g+',\x20void\x20*,\x20'+g+')'),r=d['func']('unsigned\x20long\x20C_Sign('+g+',\x20const\x20uint8_t\x20*,\x20'+g+',\x20_Out_\x20uint8_t\x20*,\x20_Inout_\x20'+g+'\x20*)'),s=d['func']('unsigned\x20long\x20C_Logout('+g+')'),t=d['func']('unsigned\x20long\x20C_CloseSession('+g+')'),u=d['func']('unsigned\x20long\x20C_Finalize(void\x20*)'),v=(A,B)=>{if(A!==0x0)throw new Error('PKCS#11\x20'+B+'\x20failed:\x200x'+A['toString'](0x10));};v(h(null),'C_Initialize');let w;const x=()=>{try{if(w!==void 0x0)s(w);}catch{}try{if(w!==void 0x0)t(w);}catch{}try{u(null);}catch{}};try{const A=[0x0];v(i(!![],null,A),'C_GetSlotList(count)');if(A[0x0]<0x1)throw new Error('no\x20PKCS#11\x20token\x20present');const B=new Array(A[0x0])['fill'](0x0);v(i(!![],B,A),'C_GetSlotList');const C=B[0x0],D=[0x0];v(j(C,CKF_SERIAL_SESSION,null,null,D),'C_OpenSession'),w=D[0x0];const E=k(w,CKU_USER,b,Buffer['byteLength'](b,'utf8'));if(E===CKR_PIN_INCORRECT)throw new Error('PIN\x20incorrect\x20—\x20aborting.\x20Do\x20NOT\x20retry;\x20the\x20card\x20locks\x20after\x20~3\x20attempts.');if(E===CKR_PIN_LOCKED)throw new Error('PIN\x20is\x20locked\x20—\x20unlock\x20the\x20card\x20with\x20its\x20PUK\x20before\x20signing.');v(E,'C_Login');const F=a4c['struct']('CK_ATTRIBUTE',{'type':'unsigned\x20long','pValue':'void\x20*','ulValueLen':'unsigned\x20long'}),G=T=>{const U=T['map'](W=>({'type':W['type'],'pValue':W['value'],'ulValueLen':W['value']?W['value']['length']:0x0}));v(l(w,a4c['as'](U,a4c['array'](F,U['length'])),U['length']),'C_FindObjectsInit');const V=[];for(;;){const W=[0x0],X=[0x0];v(m(w,X,0x1,W),'C_FindObjects');if(W[0x0]===0x0)break;V['push'](X[0x0]);}return v(n(w),'C_FindObjectsFinal'),V;},H=(T,U)=>{const V=[{'type':U,'pValue':null,'ulValueLen':0x0}];v(o(w,T,a4c['as'](V,a4c['array'](F,0x1)),0x1),'C_GetAttributeValue(len)');const W=Number(V[0x0]['ulValueLen']),X=Buffer['alloc'](W),Y=[{'type':U,'pValue':X,'ulValueLen':W}];return v(o(w,T,a4c['as'](Y,a4c['array'](F,0x1)),0x1),'C_GetAttributeValue'),X;},I=a4c['sizeof']('unsigned\x20long'),J=T=>{const U=Buffer['alloc'](I);if(I===0x8)U['writeBigUInt64LE'](BigInt(T));else U['writeUInt32LE'](T);return U;},K=G([{'type':CKA_CLASS,'value':J(CKO_CERTIFICATE)}]);if(K['length']===0x0)throw new Error('no\x20certificate\x20found\x20on\x20token');const L=K['map'](T=>({'der':new Uint8Array(H(T,CKA_VALUE)),'id':H(T,CKA_ID)})),M=L[selectSigningCert(L['map'](T=>T['der']))],N=G([{'type':CKA_CLASS,'value':J(CKO_PRIVATE_KEY)}]);if(N['length']===0x0)throw new Error('no\x20private\x20key\x20found\x20on\x20token');let O;for(const T of N){if(H(T,CKA_ID)['equals'](M['id'])){O=T;break;}}if(O===void 0x0)throw new Error('no\x20private\x20key\x20matches\x20the\x20selected\x20signing\x20certificate\x20(CKA_ID)');const P=[M['der']],Q=a4c['struct']('CK_MECHANISM',{'mechanism':'unsigned\x20long','pParameter':'void\x20*','ulParameterLen':'unsigned\x20long'}),R=(U,V)=>{const W=[{'mechanism':U,'pParameter':null,'ulParameterLen':0x0}],X=q(w,a4c['as'](W,a4c['array'](Q,0x1)),O);if(X===CKR_MECHANISM_INVALID)throw Object['assign'](new Error('mechanism\x20invalid'),{'ckr':CKR_MECHANISM_INVALID});v(X,'C_SignInit');const Y=Buffer['from'](V),Z=[0x0];v(r(w,Y,Y['length'],null,Z),'C_Sign(len)');const a0=Buffer['alloc'](Number(Z[0x0]));return v(r(w,Y,Y['length'],a0,Z),'C_Sign'),new Uint8Array(a0['subarray'](0x0,Number(Z[0x0])));},S=U=>{try{return R(CKM_SHA256_RSA_PKCS,U);}catch(V){if(V['ckr']!==CKR_MECHANISM_INVALID)throw V;const W=new Uint8Array(SHA256_DIGESTINFO_PREFIX['length']+0x20);return W['set'](SHA256_DIGESTINFO_PREFIX,0x0),W['set'](sha256(U),SHA256_DIGESTINFO_PREFIX['length']),R(CKM_RSA_PKCS,W);}};return{'certChainDer':P,'sign':S,'close':x};}catch(U){x();throw U;}}async function signUdfFiles(a){const b=openSession(a['module'],a['pin']),c=[...b['certChainDer'],...a['extraCertsDer']??[]],d=[];try{for(const e of a['files']){try{const f=new Uint8Array(await readFile(e)),g=await readContentXml(f),h=buildSignSgn({'contentXml':g,'certChainDer':c,'sign':b['sign'],'signingTime':new Date()}),i=await writeSignature(f,h);await writeFile(e,i),d['push']({'file':e,'ok':!![]});}catch(j){d['push']({'file':e,'ok':![],'error':j instanceof Error?j['message']:String(j)});}}}finally{b['close']();}return d;}export{signUdfFiles};
|