fix(core,extensions): 동적 스크립트 주입 경로 전부에 출처 게이트 적용

레이아웃 scripts[] 에만 있던 원격 스크립트 차단 게이트가 다른 주입 경로에는
없어, 저장측(SafeLayoutExpressions·NoExternalUrls)이 외부 URL 저장을 422 로
막아도 런타임 디스패치 한 번으로 임의 원격 코드가 로드됐다. 저장 검증이
통째로 무의미해지는 상태였고 오류도 경고도 남지 않았다.

판정식을 support/scriptSrcPolicy.ts 로 분리해 런타임 SSoT 를 하나로 두고,
loadScript 액션 · 확장 핸들러 재로드 · 편집기 프리뷰 · 편집기 자산 매니페스트 ·
G7Core.asset.loadScript · PG 플러그인 SDK 주입이 모두 그것을 경유하게 했다.
사본을 두지 않은 이유는 차집합이 그대로 우회로가 되기 때문이다.

- 게이트는 캐시 검사보다 앞에 둔다 (뒤에 두면 이미 로드된 미신뢰 스크립트가
 캐시 히트로 통과한다)
- NoExternalUrls 순회를 9키로 확대 — 번들 레이아웃 601개 사전 스캔으로
 정당한 외부 URL 0건을 확인한 뒤 넓혔다 (저장 회귀 없음)
- callExternal 은 생성자를 참조 동일성으로 거부하고(별칭 전역 포함),
 프로토타입 경로 세그먼트를 읽기·매핑 키 양쪽에서 차단한다
- PG SDK 는 서비스 SDK 라 자체 호스팅이 불가능하므로 manifest 선언 +
 주입 직전 호스트 확인이 게이트다. tosspayments SDK URL 은 확장자가 없어
 정적 검사에 걸리지 않아 그 런타임 확인이 유일한 게이트다
- 함께 드러난 결함: 동시 loadScript 가 로드 전에 완료 처리되던 문제,
 확장 재로드에서 script 기존재가 CSS 까지 건너뛰던 문제, loadCSS 의
 in-flight 미공유
This commit is contained in:
HeuJung committed 2026-09-02 21:43:13 +09:00
1 parent 621cd28376
commit 1e89335258
82 files changed
+2706 -240

No files matched your search

@@ -121,6 +121,7 @@ CBT 인증 URL 로 폼 POST → KG 이니시스가 `sid` 를 콜백으로 전달
- [ ] IP 화이트리스트(`InicisNotifyIpWhitelist`) 대상 라우트를 추가/변경하면 미들웨어 부착 대상(targets)도 함께 갱신
- [ ] 새 결제수단·통화를 추가하면 그 결제수단의 콜백 URL을 관리자 설정 안내(README "콜백/통보 URL 등록")에도 반영
- [ ] 레이아웃·컴포넌트·`data_source` 를 건드렸다면 [`docs/editor-spec.md`](docs/editor-spec.md) 의 동반 의무 표를 따라 `editor-spec.json` 을 함께 갱신 — 샘플이 없는 `data_source` 는 편집기 캔버스에서만 빈 화면이 되고 실제 화면은 정상이라 오류도 경고도 남지 않는다. 반영은 `php artisan plugin:update sirsoft-pay_kginicis --force`
- [ ] KG 이니시스가 SDK 호스트를 바꾸면 `plugin.json` 의 `trusted_script_hosts`(+`trusted_script_hosts_reason`)와 `resources/js/handlers/requestPayment.ts` 의 `KNOWN_SDK_HOSTS` 를 **함께** 갱신 — 두 목록이 어긋나면 테스트가 실패하며, 코드 상수에 없는 호스트는 주입 직전 확인에서 거부되어 결제가 진행되지 않는다(fail-closed). 변경 후 `php artisan ext:docgen --scope=plugin:sirsoft-pay_kginicis` 재실행
## 6. 금지 패턴
@@ -8,6 +8,7 @@
### Security
- 결제창 프로그램을 불러오는 주소가 KG 이니시스의 주소인지 불러오기 직전에 확인합니다. 확인되지 않는 주소면 결제를 진행하지 않고 안내를 표시합니다. 또한 결제창 프로그램이 실제로 준비되었는지를 기준으로 다음 단계를 진행하도록 바꿔, 프로그램이 아직 준비되지 않았는데 결제창이 열리지 않고 멈추던 상황을 없앴습니다.
- 제3자가 남의 주문번호만 알면 결제창을 거치지 않고도 그 주문을 취소시킬 수 있던 문제를 수정했습니다. 결제 결과 콜백은 로그인도 서명 확인도 거치지 않는 경로여서, 위조한 인증 정보를 보내 승인을 일부러 실패시키면 그 주문이 결제 실패로 처리되었습니다. 이제 승인이 성립하지 않은 콜백은 주문 상태를 바꾸지 않고 결제 화면으로 되돌려 보내기만 합니다. PC·모바일·해외결제(CBT) 결제창 모두에 적용됩니다. 구매자가 결제창을 닫아 생기는 정상적인 결제 실패는 종전처럼 기록됩니다.
### Added
@@ -88,6 +88,7 @@ CBT 결제창으로 진입하며, 설정이 부족하면 한국 표준결제로
| 그누보드7 코어 | `>=7.0.10` |
| PHP | `^8.2` |
| 의존 모듈 | `sirsoft-ecommerce` `>=1.1.0` |
| 외부 스크립트 호스트 | `stgstdpay.inicis.com`, `stdpay.inicis.com` |
<!-- @generated:requirements END -->
<!-- @intent START -->
@@ -1,4 +1,4 @@
(function(){"use strict";const x="kginicis_pay_form_",M="__sirsoftKginicisReloadStandardPaySdk",w="__sirsoftKginicisMobilePaymentReturnPending";function ce(){if(typeof document>"u")return 0;const e=document.querySelectorAll(`form[id^="${x}"]`);return e.forEach(t=>t.remove()),e.length}function ze(){typeof window>"u"||(window[M]=!0)}function Xe(){if(typeof window>"u")return!1;const e=window,t=e[M]===!0;return delete e[M],t}function Ze(e){typeof window>"u"||typeof document>"u"||(window.INIStdPay=void 0,document.querySelectorAll(`script[src="${e}"], script[src*="/INIStdPay_third-party.js"]`).forEach(t=>t.remove()))}function Qe(e=Date.now()){if(!(typeof window>"u"))try{window.sessionStorage.setItem(w,String(e))}catch{window[w]=e}}function N(){if(!(typeof window>"u")){try{window.sessionStorage.removeItem(w)}catch{}delete window[w]}}function de(e=Date.now()){if(typeof window>"u")return!1;let t=null;try{const n=window.sessionStorage.getItem(w);t=n?Number(n):null}catch{t=null}if(!Number.isFinite(t)){const n=window[w];t=typeof n=="number"?n:Number(n)}return!Number.isFinite(t)||e-t>18e5?(N(),!1):!0}const L="sirsoft-pay_kginicis",et=L,tt="payment-window-closed",le="__sirsoftKginicisPaymentCloseListenerInstalled",I="__sirsoftKginicisActiveStandardPaymentCloseContext",ue=20,nt=100,O={info:(...e)=>console.info(`[${L}]`,...e),warn:(...e)=>console.warn(`[${L}]`,...e)};function rt(e){if(!e||typeof e!="object")return!1;const t=e;return t.source===et&&t.type===tt}function $(){return/\/shop\/checkout\/?$/.test(window.location.pathname)}function C(){return window}function ot(){const e=C()[I];return!e||typeof e!="object"?null:e}function it(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}const D="g7:sirsoft-pay_kginicis:pendingClose";function G(){try{return window.sessionStorage??null}catch{return null}}function at(e){if(e.closeReportUrl){C()[I]={...e,reported:!1};try{G()?.setItem(D,JSON.stringify({...e,reported:!1}))}catch{}}}function K(){delete C()[I];try{G()?.removeItem(D)}catch{}}function st(){try{const e=G()?.getItem(D);if(!e)return null;const t=JSON.parse(e);return t&&typeof t.oid=="string"&&t.oid!==""&&t.closeReportUrl?t:null}catch{return null}}async function ct(){const e=st();if(!e)return;let t;try{t=new URLSearchParams(window.location.search)}catch{return}const n=t.get("orderId")??"";if(n!==""&&n!==e.oid)return;if(/\/(complete|success)(\/|$|\?)/.test(window.location.pathname)){K();return}const r=t.get("error")??"",o=t.get("message")??"";r===""&&n===""||(C()[I]={...e,reported:!1},await fe(o!==""?o:r||"payment-window-closed",!1))}function me(){K()}async function fe(e="payment-window-closed",t=!0){const n=ot();if(!n||n.reported||t&&!$())return;n.reported=!0;const r={oid:n.oid,price:n.price,buyer_email:n.buyer_email??"",buyer_phone:n.buyer_phone??"",payment_method:n.payment_method??"",reason:e};try{const o=window.G7Core?.api;typeof o?.post=="function"?await o.post(n.closeReportUrl,r):await fetch(it(n.closeReportUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),keepalive:!0})}catch(o){O.warn("failed to report KG payment window close",{reason:e,error:o})}finally{K()}}function pe(e="payment-window-closed",t=!0){if(!$())return!1;const r=window.G7Core?.state?.setLocal;return typeof r!="function"?(t&&O.warn("G7Core.state.setLocal not available while resetting payment submit state"),!1):(ce(),ze(),r({isSubmittingOrder:!1}),O.info("checkout submit state reset after KG payment close",{reason:e}),!0)}function dt(e,t=!1){let n=0;const r=()=>{if(n++,!(t&&!de())){if(pe(e,n>=ue)){t&&N();return}!$()||n>=ue||window.setTimeout(r,nt)}};r()}function v(e){de()&&dt(e,!0)}function lt(){if(typeof window>"u")return;const e=C();e[le]||(window.addEventListener("message",t=>{t.origin===window.location.origin&&rt(t.data)&&(fe(t.data.reason),pe(t.data.reason))}),window.addEventListener("pagehide",()=>{me()}),window.addEventListener("beforeunload",()=>{me()}),window.addEventListener("pageshow",t=>{v(t.persisted?"mobile-payment-bfcache-return":"mobile-payment-page-show")}),window.addEventListener("focus",()=>{v("mobile-payment-window-focus")}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&v("mobile-payment-visibility-return")}),e[le]=!0,v("mobile-payment-listener-installed"))}function ye(){if(typeof navigator>"u")return!1;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase();if(/android|iphone|ipad|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||/iphone|ipad|ipod|ios/.test(n))return!0;const r=e.maxTouchPoints??0;return/macintosh|mac os x/.test(t)&&r>1}function ut(e){return new Promise((t,n)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}const r=document.createElement("script");r.src=e,r.async=!0,r.onload=()=>t(),r.onerror=(Line truncated
(function(){"use strict";const x="kginicis_pay_form_",N="__sirsoftKginicisReloadStandardPaySdk",w="__sirsoftKginicisMobilePaymentReturnPending";function ce(){if(typeof document>"u")return 0;const e=document.querySelectorAll(`form[id^="${x}"]`);return e.forEach(t=>t.remove()),e.length}function ze(){typeof window>"u"||(window[N]=!0)}function Xe(){if(typeof window>"u")return!1;const e=window,t=e[N]===!0;return delete e[N],t}function Ze(e){typeof window>"u"||typeof document>"u"||(window.INIStdPay=void 0,document.querySelectorAll(`script[src="${e}"], script[src*="/INIStdPay_third-party.js"]`).forEach(t=>t.remove()))}function Qe(e=Date.now()){if(!(typeof window>"u"))try{window.sessionStorage.setItem(w,String(e))}catch{window[w]=e}}function M(){if(!(typeof window>"u")){try{window.sessionStorage.removeItem(w)}catch{}delete window[w]}}function de(e=Date.now()){if(typeof window>"u")return!1;let t=null;try{const n=window.sessionStorage.getItem(w);t=n?Number(n):null}catch{t=null}if(!Number.isFinite(t)){const n=window[w];t=typeof n=="number"?n:Number(n)}return!Number.isFinite(t)||e-t>18e5?(M(),!1):!0}const L="sirsoft-pay_kginicis",et=L,tt="payment-window-closed",le="__sirsoftKginicisPaymentCloseListenerInstalled",I="__sirsoftKginicisActiveStandardPaymentCloseContext",ue=20,nt=100,O={info:(...e)=>console.info(`[${L}]`,...e),warn:(...e)=>console.warn(`[${L}]`,...e)};function rt(e){if(!e||typeof e!="object")return!1;const t=e;return t.source===et&&t.type===tt}function $(){return/\/shop\/checkout\/?$/.test(window.location.pathname)}function C(){return window}function ot(){const e=C()[I];return!e||typeof e!="object"?null:e}function it(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}const D="g7:sirsoft-pay_kginicis:pendingClose";function K(){try{return window.sessionStorage??null}catch{return null}}function at(e){if(e.closeReportUrl){C()[I]={...e,reported:!1};try{K()?.setItem(D,JSON.stringify({...e,reported:!1}))}catch{}}}function G(){delete C()[I];try{K()?.removeItem(D)}catch{}}function st(){try{const e=K()?.getItem(D);if(!e)return null;const t=JSON.parse(e);return t&&typeof t.oid=="string"&&t.oid!==""&&t.closeReportUrl?t:null}catch{return null}}async function ct(){const e=st();if(!e)return;let t;try{t=new URLSearchParams(window.location.search)}catch{return}const n=t.get("orderId")??"";if(n!==""&&n!==e.oid)return;if(/\/(complete|success)(\/|$|\?)/.test(window.location.pathname)){G();return}const r=t.get("error")??"",o=t.get("message")??"";r===""&&n===""||(C()[I]={...e,reported:!1},await me(o!==""?o:r||"payment-window-closed",!1))}function fe(){G()}async function me(e="payment-window-closed",t=!0){const n=ot();if(!n||n.reported||t&&!$())return;n.reported=!0;const r={oid:n.oid,price:n.price,buyer_email:n.buyer_email??"",buyer_phone:n.buyer_phone??"",payment_method:n.payment_method??"",reason:e};try{const o=window.G7Core?.api;typeof o?.post=="function"?await o.post(n.closeReportUrl,r):await fetch(it(n.closeReportUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),keepalive:!0})}catch(o){O.warn("failed to report KG payment window close",{reason:e,error:o})}finally{G()}}function pe(e="payment-window-closed",t=!0){if(!$())return!1;const r=window.G7Core?.state?.setLocal;return typeof r!="function"?(t&&O.warn("G7Core.state.setLocal not available while resetting payment submit state"),!1):(ce(),ze(),r({isSubmittingOrder:!1}),O.info("checkout submit state reset after KG payment close",{reason:e}),!0)}function dt(e,t=!1){let n=0;const r=()=>{if(n++,!(t&&!de())){if(pe(e,n>=ue)){t&&M();return}!$()||n>=ue||window.setTimeout(r,nt)}};r()}function v(e){de()&&dt(e,!0)}function lt(){if(typeof window>"u")return;const e=C();e[le]||(window.addEventListener("message",t=>{t.origin===window.location.origin&&rt(t.data)&&(me(t.data.reason),pe(t.data.reason))}),window.addEventListener("pagehide",()=>{fe()}),window.addEventListener("beforeunload",()=>{fe()}),window.addEventListener("pageshow",t=>{v(t.persisted?"mobile-payment-bfcache-return":"mobile-payment-page-show")}),window.addEventListener("focus",()=>{v("mobile-payment-window-focus")}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&v("mobile-payment-visibility-return")}),e[le]=!0,v("mobile-payment-listener-installed"))}function ye(){if(typeof navigator>"u")return!1;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase();if(/android|iphone|ipad|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||/iphone|ipad|ipod|ios/.test(n))return!0;const r=e.maxTouchPoints??0;return/macintosh|mac os x/.test(t)&&r>1}const ut=["stgstdpay.inicis.com","stdpay.inicis.com"];function ft(e,t){const n=window?.G7Core?.t;if(typeof n!="function")return t;const r=`sirsoft-pay_kginicis.${e}`,o=n(r);return typeof o==Line truncated
<div class="row">
<dt>${S(i.label)}</dt>
<dd>${S(i.value)}</dd>
@@ -87,4 +87,4 @@
<div class="actions"><button type="button" onclick="window.print()">인쇄</button></div>
</main>
</body>
</html>`),t.document.close()}function S(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}const j="sirsoft-pay_kginicis",Ee="__kginicisOrderShowInjectorInstalled",Y="kginicis-mp-receipt-row",Se=/^(?:\/mypage\/orders\/([^/]+)|\/shop\/guest\/orders\/([^/]+))$/,B=new Map;function Nt(e){try{const n=window.G7Core?.getState,i=n?.()?.currentDataContext?.order?.data;return i&&(i.order_number===e||i.id!==void 0&&String(i.id)===e)?i:null}catch{return null}}function Lt(){const e=document.getElementById("order_payment_info_panel");if(e)return Array.from(e.children).find(r=>r.className?.includes("space-y"))??e;const t=Array.from(document.querySelectorAll("h3")).find(r=>{const o=r.textContent?.trim()??"";return o.includes("결제 정보")||/^Payment Information$/i.test(o)});if(!t)return null;const n=t.parentElement?.parentElement;return n?Array.from(n.children).find(r=>r.className?.includes("space-y"))??n:null}function Ot(e,t){if(!t)return!1;const n=Array.from(e.querySelectorAll("div"));for(const r of n){const o=Array.from(r.children).filter(a=>a instanceof HTMLElement&&a.tagName==="SPAN");if(o.length<2)continue;const i=o[0].textContent?.trim();if(i!=="결제 방법"&&i!=="결제수단"&&i!=="Payment Method")continue;const s=o[o.length-1];return s.textContent?.trim()===t?(r.dataset.kginicisPaymentMethodRow="true",!0):(s.textContent=t,s.dataset.kginicisPaymentMethodPatched="true",r.dataset.kginicisPaymentMethodRow="true",!0)}return!1}function $t(e,t){const n=document.createElement("div");n.id=Y,n.className="flex items-center justify-between",n.dataset.kginicisReceiptRow="mypage-order";const r=document.createElement("span");r.className="text-gray-500 dark:text-gray-400 text-sm",r.textContent=xt(t);const o=document.createElement("button");return o.type="button",o.dataset.kginicisReceiptButton="mypage-order",o.className="inline-flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",o.textContent=T(t),o.addEventListener("click",async()=>{o.disabled=!0,o.textContent="로딩 중...";const i=await A(e);o.disabled=!1,o.textContent=T(i??t),E(i)&&Ce(i)}),n.appendChild(r),n.appendChild(o),n}async function Dt(e,t){const n=Nt(e),r=n?.payment;if(r&&(r.pg_provider!=="kginicis"||!r.transaction_id))return!0;const o=n?.order_number??(t?e:null);if(!o)return!1;if(!t&&n&&!r)return!0;const i=Lt();if(!i)return!1;const{status:s,info:a}=await ke(o);if(!t&&s===404)return!0;const c=r?.payment_status==="paid",u=a?.receipt_type==="cbt_confirmation";if(r&&!c&&!u)return!0;if(!r&&!E(a))return!1;const d=Ot(i,a?.payment_method_display_label);return!document.getElementById(Y)&&E(a)&&(i.appendChild($t(o,a)),console.info(`[${j}] receipt button injected on mypage order show`)),d&&console.info(`[${j}] payment method display patched on mypage order show`),!!(document.getElementById(Y)||d)}function Gt(e,t){if(B.has(e))return;let n=0;const r=window.setInterval(()=>{n++,Dt(e,t).then(o=>{(o||n>=30)&&(window.clearInterval(r),B.delete(e))})},400);B.set(e,r)}function Kt(){const e=location.pathname.match(Se);if(e){const t=e[1],n=e[2],r=t??n;r&&Gt(r,n!==void 0)}}function jt(){if(typeof window>"u")return;const e=window;if(e[Ee])return;e[Ee]=!0,console.info(`[${j}] mypage order show injector installed`);let t=null;const n=(a=1500)=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,Kt()},a)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>n()):n();const r=history.pushState.bind(history);history.pushState=(...a)=>{r(...a),n(600)};const o=history.replaceState.bind(history);history.replaceState=(...a)=>{o(...a),n(600)},window.addEventListener("popstate",()=>n(500));const i=document.getElementById("app")??document.body;new MutationObserver(()=>{Se.test(location.pathname)&&n(250)}).observe(i,{childList:!0,subtree:!0})}const U="sirsoft-pay_kginicis",Pe="__kginicisAdminPaymentDisplayInjectorInstalled",Yt=/^\/admin\/ecommerce\/orders\/([^/]+)$/;function Bt(){return localStorage.getItem("auth_token")}async function Ut(e){const t=Bt();if(!t)return null;try{const n=await fetch(`/api/plugins/${U}/admin/orders/${e}/transaction-status`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});if(!n.ok)return null;const r=await n.json();return("data"in r?r.data:r)??null}catch{return null}}function Jt(e){return Array.from(e.children).filter(t=>t instanceof HTMLElement)}function Ht(e,t){let n=!1;const r=Array.from(e.querySelectorAll("div"));for(const o of r){const i=Jt(o),s=i.findIndex(l=>l.textContent?.trim()==="결제수단");if(s<0)continue;const a=i.slice(s+1).find(l=>l.textContent?.trim()&&l.textContent.trim()!=="결제수단");if(!a)continue;const c=i.slice(s+2).find(l=>/^\(.+\)$/.test(l.textContent?.trim()??"")),u=c?.textContent?.trim().replace(/^\(|\)$/g,"")??"",d=u&&t.endsWith(")")?t.replace(/\)$/,`, ${u})`):t;a.textContent?.trim()!==d&&(a.textContent=d,a.dataset.kginicisPaymentMethodPatched="true"),o.dataLine truncated
</html>`),t.document.close()}function S(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}const j="sirsoft-pay_kginicis",Ee="__kginicisOrderShowInjectorInstalled",Y="kginicis-mp-receipt-row",Se=/^(?:\/mypage\/orders\/([^/]+)|\/shop\/guest\/orders\/([^/]+))$/,B=new Map;function $t(e){try{const n=window.G7Core?.getState,i=n?.()?.currentDataContext?.order?.data;return i&&(i.order_number===e||i.id!==void 0&&String(i.id)===e)?i:null}catch{return null}}function Dt(){const e=document.getElementById("order_payment_info_panel");if(e)return Array.from(e.children).find(r=>r.className?.includes("space-y"))??e;const t=Array.from(document.querySelectorAll("h3")).find(r=>{const o=r.textContent?.trim()??"";return o.includes("결제 정보")||/^Payment Information$/i.test(o)});if(!t)return null;const n=t.parentElement?.parentElement;return n?Array.from(n.children).find(r=>r.className?.includes("space-y"))??n:null}function Kt(e,t){if(!t)return!1;const n=Array.from(e.querySelectorAll("div"));for(const r of n){const o=Array.from(r.children).filter(a=>a instanceof HTMLElement&&a.tagName==="SPAN");if(o.length<2)continue;const i=o[0].textContent?.trim();if(i!=="결제 방법"&&i!=="결제수단"&&i!=="Payment Method")continue;const s=o[o.length-1];return s.textContent?.trim()===t?(r.dataset.kginicisPaymentMethodRow="true",!0):(s.textContent=t,s.dataset.kginicisPaymentMethodPatched="true",r.dataset.kginicisPaymentMethodRow="true",!0)}return!1}function Gt(e,t){const n=document.createElement("div");n.id=Y,n.className="flex items-center justify-between",n.dataset.kginicisReceiptRow="mypage-order";const r=document.createElement("span");r.className="text-gray-500 dark:text-gray-400 text-sm",r.textContent=Lt(t);const o=document.createElement("button");return o.type="button",o.dataset.kginicisReceiptButton="mypage-order",o.className="inline-flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",o.textContent=T(t),o.addEventListener("click",async()=>{o.disabled=!0,o.textContent="로딩 중...";const i=await A(e);o.disabled=!1,o.textContent=T(i??t),E(i)&&Ce(i)}),n.appendChild(r),n.appendChild(o),n}async function jt(e,t){const n=$t(e),r=n?.payment;if(r&&(r.pg_provider!=="kginicis"||!r.transaction_id))return!0;const o=n?.order_number??(t?e:null);if(!o)return!1;if(!t&&n&&!r)return!0;const i=Dt();if(!i)return!1;const{status:s,info:a}=await ke(o);if(!t&&s===404)return!0;const c=r?.payment_status==="paid",u=a?.receipt_type==="cbt_confirmation";if(r&&!c&&!u)return!0;if(!r&&!E(a))return!1;const d=Kt(i,a?.payment_method_display_label);return!document.getElementById(Y)&&E(a)&&(i.appendChild(Gt(o,a)),console.info(`[${j}] receipt button injected on mypage order show`)),d&&console.info(`[${j}] payment method display patched on mypage order show`),!!(document.getElementById(Y)||d)}function Yt(e,t){if(B.has(e))return;let n=0;const r=window.setInterval(()=>{n++,jt(e,t).then(o=>{(o||n>=30)&&(window.clearInterval(r),B.delete(e))})},400);B.set(e,r)}function Bt(){const e=location.pathname.match(Se);if(e){const t=e[1],n=e[2],r=t??n;r&&Yt(r,n!==void 0)}}function Ut(){if(typeof window>"u")return;const e=window;if(e[Ee])return;e[Ee]=!0,console.info(`[${j}] mypage order show injector installed`);let t=null;const n=(a=1500)=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,Bt()},a)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>n()):n();const r=history.pushState.bind(history);history.pushState=(...a)=>{r(...a),n(600)};const o=history.replaceState.bind(history);history.replaceState=(...a)=>{o(...a),n(600)},window.addEventListener("popstate",()=>n(500));const i=document.getElementById("app")??document.body;new MutationObserver(()=>{Se.test(location.pathname)&&n(250)}).observe(i,{childList:!0,subtree:!0})}const U="sirsoft-pay_kginicis",Pe="__kginicisAdminPaymentDisplayInjectorInstalled",Jt=/^\/admin\/ecommerce\/orders\/([^/]+)$/;function Ht(){return localStorage.getItem("auth_token")}async function Ft(e){const t=Ht();if(!t)return null;try{const n=await fetch(`/api/plugins/${U}/admin/orders/${e}/transaction-status`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});if(!n.ok)return null;const r=await n.json();return("data"in r?r.data:r)??null}catch{return null}}function qt(e){return Array.from(e.children).filter(t=>t instanceof HTMLElement)}function Wt(e,t){let n=!1;const r=Array.from(e.querySelectorAll("div"));for(const o of r){const i=qt(o),s=i.findIndex(l=>l.textContent?.trim()==="결제수단");if(s<0)continue;const a=i.slice(s+1).find(l=>l.textContent?.trim()&&l.textContent.trim()!=="결제수단");if(!a)continue;const c=i.slice(s+2).find(l=>/^\(.+\)$/.test(l.textContent?.trim()??"")),u=c?.textContent?.trim().replace(/^\(|\)$/g,"")??"",d=u&&t.endsWith(")")?t.replace(/\)$/,`, ${u})`):t;a.textContent?.trim()!==d&&(a.textContent=d,a.dataset.kginicisPaymentMethodPatched="true"),o.dataLine truncated
@@ -20,6 +20,14 @@
},
"plugins": {}
},
"trusted_script_hosts": [
"stgstdpay.inicis.com",
"stdpay.inicis.com"
],
"trusted_script_hosts_reason": {
"stgstdpay.inicis.com": "KG 이니시스 테스트 표준결제창 SDK 다. 결제창 스크립트가 KG 이니시스 서버와 통신하므로 자체 호스팅해도 결제가 성립하지 않는다.",
"stdpay.inicis.com": "KG 이니시스 운영 표준결제창 SDK 다. 결제창 스크립트가 KG 이니시스 서버와 통신하므로 자체 호스팅해도 결제가 성립하지 않는다."
},
"assets": {
"js": {
"entry": "resources/js/index.ts",
@@ -5,8 +5,10 @@
* SDK 로드/INIStdPay.pay 호출/모바일 redirect 등 외부 부수효과 의존 흐름은
* tests/scenarios 매니페스트에서 다루며, 본 단위 테스트는 초기 가드 위주.
*/
import { readFileSync } from 'fs';
import { resolve } from 'path';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { requestPaymentHandler } from '../../handlers/requestPayment';
import { assertTrustedSdkUrl, KNOWN_SDK_HOSTS, requestPaymentHandler } from '../../handlers/requestPayment';
import {
clearMobilePaymentReturnPending,
consumeMobilePaymentReturnPending,
@@ -832,3 +834,54 @@ describe('requestPaymentHandler — 모바일 P_INI_PAYMENT 매핑', () => {
);
});
});
/**
* SDK 주입 출처 게이트 (동적 스크립트 주입 정책).
*
* PG SDK 는 서비스 SDK 라 자체 호스팅할 수 없다. 그래서 **주입 직전에** 호스트를
* 확인하는 것이 유일한 게이트다. 확장자 없는 SDK URL 은 정적 검사에도 걸리지 않는다.
*
* manifest `trusted_script_hosts` 와 코드 상수가 어긋나면 그 차집합이 그대로
* 사각이 되므로 두 목록의 일치도 함께 고정한다.
*/
describe('SDK URL 신뢰 호스트 게이트', () => {
const TRUSTED_SDK_URL = 'https://stdpay.inicis.com/stdjs/INIStdPay.js';
it('신뢰 호스트 https URL 은 통과한다', () => {
expect(() => assertTrustedSdkUrl(TRUSTED_SDK_URL)).not.toThrow();
});
it.each([
['미신뢰 호스트', 'https://cdn.evil.com/sdk.js'],
['http (평문)', TRUSTED_SDK_URL.replace('https://', 'http://')],
['protocol-relative', TRUSTED_SDK_URL.replace('https://', '//')],
['상대 경로', '/local/sdk.js'],
['빈 문자열', ''],
['javascript 스킴', 'javascript:alert(1)'],
['신뢰 호스트를 userinfo 로 위장', 'https://evil.com/@' + new URL(TRUSTED_SDK_URL).hostname + '/x.js'],
['신뢰 호스트를 서브도메인 접미로 위장', 'https://' + new URL(TRUSTED_SDK_URL).hostname + '.evil.com/x.js'],
])('%s 는 거부된다', (_label, url) => {
expect(() => assertTrustedSdkUrl(url as string)).toThrow();
});
it('manifest trusted_script_hosts 와 KNOWN_SDK_HOSTS 가 일치한다', () => {
const manifest = JSON.parse(
readFileSync(resolve(__dirname, '../../../../plugin.json'), 'utf-8')
);
expect([...(manifest.trusted_script_hosts ?? [])].sort()).toEqual(
[...KNOWN_SDK_HOSTS].sort()
);
});
it('manifest 가 호스트별 사유를 함께 선언한다', () => {
const manifest = JSON.parse(
readFileSync(resolve(__dirname, '../../../../plugin.json'), 'utf-8')
);
for (const host of KNOWN_SDK_HOSTS) {
expect(typeof manifest.trusted_script_hosts_reason?.[host]).toBe('string');
expect(manifest.trusted_script_hosts_reason[host].length).toBeGreaterThan(0);
}
});
});
@@ -139,13 +139,93 @@ function isMobileUserAgent(): boolean {
return /macintosh|mac os x/.test(ua) && touchPoints > 1;
}
function loadScript(src: string): Promise<void> {
return new Promise((resolve, reject) => {
if (document.querySelector(`script[src="${src}"]`)) {
resolve();
return;
}
/**
* SDK 스크립트를 로드할 수 있는 호스트 (plugin.json `trusted_script_hosts` 미러).
*
* KG 이니시스 결제창은 라이브러리가 아니라 그 회사 서버와 통신하는 서비스 SDK 라
* 자체 호스팅할 수 없다. 대신 **주입 직전에** 호스트를 확인해, 설정·응답이 어떤
* 경로로든 다른 주소를 지시하면 결제를 진행하지 않는다(fail-closed).
*
* PG사가 SDK 호스트를 바꾸면 이 상수와 plugin.json 을 **함께** 갱신한다 —
* 둘이 어긋나면 테스트가 실패한다.
*/
export const KNOWN_SDK_HOSTS: readonly string[] = ['stgstdpay.inicis.com', 'stdpay.inicis.com'];
/**
* 번역 문자열을 얻습니다.
*
* @param key 번역 키 (플러그인 네임스페이스 이하)
* @param fallback 번역 엔진 부재 시 사용할 문구
* @returns 번역된 문자열
*/
function t(key: string, fallback: string): string {
const translate = (window as any)?.G7Core?.t;
if (typeof translate !== 'function') {
return fallback;
}
const full = `sirsoft-pay_kginicis.${key}`;
const result = translate(full);
return typeof result === 'string' && result !== full ? result : fallback;
}
/**
* SDK URL 이 신뢰 호스트인지 확인하고, 아니면 예외를 던집니다.
*
* @param url 주입할 SDK URL
* @throws Error 미신뢰 호스트이거나 https 가 아닌 경우
*/
export function assertTrustedSdkUrl(url: string): void {
let parsed: URL | null = null;
try {
parsed = new URL(url);
} catch {
parsed = null;
}
if (
parsed === null
|| parsed.protocol !== 'https:'
|| !KNOWN_SDK_HOSTS.includes(parsed.hostname.toLowerCase())
) {
throw new Error(
t('payment.error.sdk_url_untrusted', '결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다.')
);
}
}
/**
* SDK 스크립트를 로드합니다.
*
* 완료 판정은 **SDK 전역 확보**로 한다 — DOM 에 태그가 있다는 것은 로드 완료를
* 뜻하지 않는다(로드 중이거나, 실패해 남은 잔재일 수 있다). 종전에는 태그 존재만으로
* 즉시 resolve 해서, 전역이 없는 상태로 다음 단계가 진행되고 결제창이 열리지 않았다.
*
* @param src SDK URL
* @throws Error 미신뢰 호스트이거나 로드에 실패한 경우
*/
async function loadScript(src: string): Promise<void> {
assertTrustedSdkUrl(src);
if (window.INIStdPay) {
return;
}
// 전역이 없는데 태그만 남아 있으면 미완료·실패 잔재다 — 제거 후 새로 로드한다.
document.querySelectorAll(`script[src="${CSS.escape(src)}"]`).forEach((el) => el.remove());
const loader = (window as any)?.G7Core?.asset?.loadScript;
if (typeof loader === 'function') {
await loader(src, {}, { label: 'kginicis SDK' });
return;
}
await new Promise<void>((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.async = true;
@@ -308,5 +308,10 @@
"vbank_notify_hint": "Register this URL as the PC virtual account deposit notification URL in the KG Inicis merchant admin.",
"vbank_notify_copied": "URL copied to clipboard.",
"copy": "Copy"
},
"payment": {
"error": {
"sdk_url_untrusted": "The payment module address is not valid, so the payment cannot proceed. Please contact the administrator."
}
}
}
@@ -311,5 +311,10 @@
"vbank_notify_hint": "KG 이니시스 가맹점 어드민에서 이 URL을 PC 가상계좌 입금통보 URL로 등록해야 합니다.",
"vbank_notify_copied": "URL이 클립보드에 복사되었습니다.",
"copy": "복사"
},
"payment": {
"error": {
"sdk_url_untrusted": "결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다. 관리자에게 문의해 주세요."
}
}
}
@@ -125,6 +125,7 @@ OS 판별 후 `executeCliWindows()`/`executeCliLinux()` 로 분기 → CLI 인
- [ ] IP 화이트리스트(`RestrictKcpIp`) 대상 라우트를 추가/변경하면 미들웨어 부착 대상(targets)도 함께 갱신
- [ ] 새 결제수단·통화를 추가하면 그 결제수단의 콜백 URL을 관리자 설정 안내(README "콜백 및 통보 URL")에도 반영
- [ ] 레이아웃·컴포넌트·`data_source` 를 건드렸다면 [`docs/editor-spec.md`](docs/editor-spec.md) 의 동반 의무 표를 따라 `editor-spec.json` 을 함께 갱신 — 샘플이 없는 `data_source` 는 편집기 캔버스에서만 빈 화면이 되고 실제 화면은 정상이라 오류도 경고도 남지 않는다. 반영은 `php artisan plugin:update sirsoft-pay_nhnkcp --force`
- [ ] NHN KCP 가 SDK 호스트를 바꾸면 `plugin.json` 의 `trusted_script_hosts`(+`trusted_script_hosts_reason`)와 `resources/js/handlers/requestPayment.ts` 의 `KNOWN_SDK_HOSTS` 를 **함께** 갱신 — 두 목록이 어긋나면 테스트가 실패하며, 코드 상수에 없는 호스트는 주입 직전 확인에서 거부되어 결제가 진행되지 않는다(fail-closed). 변경 후 `php artisan ext:docgen --scope=plugin:sirsoft-pay_nhnkcp` 재실행
## 6. 금지 패턴
@@ -8,6 +8,7 @@
### Security
- 결제창 프로그램을 불러오는 주소가 NHN KCP 의 주소인지 불러오기 직전에 확인합니다. 확인되지 않는 주소면 결제를 진행하지 않고 안내를 표시합니다.
- 제3자가 남의 주문번호만 알면 결제창을 거치지 않고도 그 주문을 취소시킬 수 있던 문제를 수정했습니다. 결제 결과 콜백은 로그인도 서명 확인도 거치지 않는 경로여서, 위조한 결제 정보를 보내 승인을 일부러 실패시키면 그 주문이 결제 실패로 처리되었습니다. 이제 실제 결제 승인이 이루어진 뒤의 실패만 주문에 반영하며, 승인 전 단계의 실패는 결제 화면으로 되돌려 보내기만 합니다. 구매자가 결제창을 닫아 생기는 정상적인 결제 실패는 종전처럼 기록됩니다. (KISA 측에서 제보해주셨습니다 — KVE-2026-2018)
- 같은 결제 결과 콜백에서 가상계좌 경로를 통해서도 남의 주문을 건드릴 수 있던 문제를 수정했습니다. 결제수단을 가상계좌라고 주장하는 값을 요청에 섞으면, 카드로 주문한 건도 결제사 확인을 거치지 않는 경로로 흘러 그 주문이 취소되거나 위조된 입금 계좌가 그 주문에 기록될 수 있었습니다. 이제 결제수단은 요청에 실려 온 값이 아니라 주문에 저장된 값으로만 판단하며, 가상계좌 발급이 확인되지 않은 경우에는 주문을 그대로 두고 결제 화면으로 되돌려 보냅니다.
- 취소된 주문을 다시 결제 대기 상태로 되돌리는 처리가, 결제사 승인이 확인되기 전에 이루어지던 문제를 수정했습니다. 주문번호만 알면 남의 취소된 주문을 되살릴 수 있었습니다. 이제 승인이나 계좌 발급이 확인된 뒤에만 되돌립니다.
@@ -86,6 +86,7 @@ PC 결제 승인은 `NhnKcpApiService`가 OS 를 판별해 `pp_cli`/`pp_cli_x64`
| 그누보드7 코어 | `>=7.0.10` |
| PHP | `^8.2` |
| 의존 모듈 | `sirsoft-ecommerce` `>=1.1.0` |
| 외부 스크립트 호스트 | `testpay.kcp.co.kr`, `pay.kcp.co.kr` |
<!-- @generated:requirements END -->
<!-- @intent START -->
+2 -2
View File
@@ -1,4 +1,4 @@
(function(){"use strict";function De(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function Be(e){return e.trim().slice(0,160)}function He(e){if(e)return e.replace(/\/payment\/close-report$/,"/payment/retry")}async function oe(e,t,n=!1){const o=window.G7Core?.api;if(typeof o?.post=="function"){await o.post(e,t);return}const r=await fetch(De(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:n});if(!r.ok){let a=`NHN KCP payment request failed (${r.status})`;try{const s=await r.json(),i=Array.isArray(s?.errors?.message)?s.errors.message[0]:s?.error??s?.message;typeof i=="string"&&i.trim()!==""&&(a=i)}catch{}throw new Error(a)}}async function Fe(e){const t=He(e.closeReportUrl);t&&await oe(t,{oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??""})}const S="g7:sirsoft-pay_nhnkcp:pendingClose";function M(){try{return window.sessionStorage??null}catch{return null}}function Ue(e){const t=M();if(t)try{t.setItem(S,JSON.stringify(e))}catch{}}function re(){const e=M();if(e)try{e.removeItem(S)}catch{}}function qe(){const e=M();if(!e)return null;try{const t=e.getItem(S);if(!t)return null;const n=JSON.parse(t);return n&&typeof n.oid=="string"&&n.oid!==""?n:null}catch{return null}}async function Ge(){const e=qe();if(!e)return;let t;try{t=new URLSearchParams(window.location.search)}catch{return}const n=t.get("orderId")??"";if(n!==""&&n!==e.oid)return;if(/\/(complete|success)(\/|$|\?)/.test(window.location.pathname)){re();return}const o=t.get("error")??"",r=t.get("message")??"";o===""&&n===""||(re(),await ae(e,r!==""?r:o))}async function ae(e,t="kcp-window-closed"){if(!e.closeReportUrl)return;const n={oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??"",reason:Be(t)||"kcp-window-closed"};try{await oe(e.closeReportUrl,n,!0)}catch(o){console.warn("[sirsoft-pay_nhnkcp] failed to report payment window close",o)}}const Ye="nhnkcp_applepay";function T(e){return e===Ye}function x(){if(typeof navigator>"u")return!1;const e=navigator,t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase(),o=e.maxTouchPoints??0;return/iphone|ipad|ipod/.test(t)||/iphone|ipad|ipod|ios/.test(n)?!0:/macintosh|mac os x/.test(t)&&o>1}function R(){return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?"애플페이는 IOS 기기에 모바일결제만 가능합니다.":"Apple Pay is available only for mobile payments on iOS devices."}function L(e){return(e??"KRW").trim().toUpperCase()||"KRW"}function We(e){return L(e)==="KRW"}function ze(e){const t=L(e);return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?`NHN KCP는 KRW 결제만 지원합니다. (${t})`:`NHN KCP supports KRW payments only. (${t})`}function Je(e){const t=Math.max(0,Math.round(Number(e.amount??0))),n=Math.min(Math.max(0,Math.round(Number(e.tax_free_amount??0))),t);if(n<=0)return{};const o=Math.max(0,Math.round(Number(e.tax_amount??0))),r=Math.max(0,Math.round(Number(e.vat_amount??0))),a=Math.max(0,t-n),s=a>0&&o>0&&r>0?Math.min(a,Math.round(a*(r/o))):0,i=a-s;return{tax_flag:"TG03",comm_tax_mny:String(i),comm_vat_mny:String(s),comm_free_mny:String(n)}}class $ extends Error{constructor(t){super(t??"결제가 취소되었습니다."),this.name="KcpCancelledError"}}const Ve={card:"100000000000",bank_transfer:"010000000000",virtual_account:"001000000000",mobile:"000010000000",bank:"010000000000",vbank:"001000000000",phone:"000010000000"},se={nhnkcp_payco:{payco_direct:"Y"},nhnkcp_naverpay:{naverpay_direct:"Y"},nhnkcp_naverpay_point:{naverpay_direct:"Y",naverpay_point_direct:"Y"},nhnkcp_kakaopay:{kakaopay_direct:"Y"},nhnkcp_applepay:{applepay_direct:"Y"}};function Qe(e,t){const n=e.toLowerCase();return!t||!Object.prototype.hasOwnProperty.call(se,n)?{}:{param_opt_1:n,nhnkcp_easy_pay_method:n}}function Xe(e){if(!e.isConnected)return!0;const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!0;const n=e.getBoundingClientRect();return n.width<=0||n.height<=0}function Ze(e,t){let n=!1,o,r;const a=()=>{n=!0,r&&(r.disconnect(),r=void 0),o!==void 0&&(window.clearInterval(o),o=void 0)},s=()=>{n||!Xe(e)||(a(),t())},i=document.body??document.documentElement;return i&&typeof MutationObserver<"u"&&(r=new MutationObserver(s),r.observe(i,{attributes:!0,attributeFilter:["class","hidden","style"],childList:!0,subtree:!0})),o=window.setInterval(s,300),a}function et(){if(typeof navigator>"u")return!1;if(x())return!0;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(navigator.userAgent||"").toLowerCase();return!!(/android|iphone|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||(navigator.maxTouchPoints??0)>1&&!t.includLine truncated
(function(){"use strict";function De(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function Be(e){return e.trim().slice(0,160)}function He(e){if(e)return e.replace(/\/payment\/close-report$/,"/payment/retry")}async function oe(e,t,n=!1){const o=window.G7Core?.api;if(typeof o?.post=="function"){await o.post(e,t);return}const r=await fetch(De(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:n});if(!r.ok){let a=`NHN KCP payment request failed (${r.status})`;try{const s=await r.json(),i=Array.isArray(s?.errors?.message)?s.errors.message[0]:s?.error??s?.message;typeof i=="string"&&i.trim()!==""&&(a=i)}catch{}throw new Error(a)}}async function Fe(e){const t=He(e.closeReportUrl);t&&await oe(t,{oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??""})}const I="g7:sirsoft-pay_nhnkcp:pendingClose";function M(){try{return window.sessionStorage??null}catch{return null}}function Ue(e){const t=M();if(t)try{t.setItem(I,JSON.stringify(e))}catch{}}function re(){const e=M();if(e)try{e.removeItem(I)}catch{}}function qe(){const e=M();if(!e)return null;try{const t=e.getItem(I);if(!t)return null;const n=JSON.parse(t);return n&&typeof n.oid=="string"&&n.oid!==""?n:null}catch{return null}}async function Ge(){const e=qe();if(!e)return;let t;try{t=new URLSearchParams(window.location.search)}catch{return}const n=t.get("orderId")??"";if(n!==""&&n!==e.oid)return;if(/\/(complete|success)(\/|$|\?)/.test(window.location.pathname)){re();return}const o=t.get("error")??"",r=t.get("message")??"";o===""&&n===""||(re(),await ae(e,r!==""?r:o))}async function ae(e,t="kcp-window-closed"){if(!e.closeReportUrl)return;const n={oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??"",reason:Be(t)||"kcp-window-closed"};try{await oe(e.closeReportUrl,n,!0)}catch(o){console.warn("[sirsoft-pay_nhnkcp] failed to report payment window close",o)}}const Ye="nhnkcp_applepay";function T(e){return e===Ye}function x(){if(typeof navigator>"u")return!1;const e=navigator,t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase(),o=e.maxTouchPoints??0;return/iphone|ipad|ipod/.test(t)||/iphone|ipad|ipod|ios/.test(n)?!0:/macintosh|mac os x/.test(t)&&o>1}function R(){return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?"애플페이는 IOS 기기에 모바일결제만 가능합니다.":"Apple Pay is available only for mobile payments on iOS devices."}function L(e){return(e??"KRW").trim().toUpperCase()||"KRW"}function We(e){return L(e)==="KRW"}const ze=["testpay.kcp.co.kr","pay.kcp.co.kr"];function Je(e,t){const n=window?.G7Core?.t;if(typeof n!="function")return t;const o=`sirsoft-pay_nhnkcp.${e}`,r=n(o);return typeof r=="string"&&r!==o?r:t}function Ve(e){let t=null;try{t=new URL(e)}catch{t=null}if(t===null||t.protocol!=="https:"||!ze.includes(t.hostname.toLowerCase()))throw new Error(Je("payment.error.sdk_url_untrusted","결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다."))}function Qe(e){const t=L(e);return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?`NHN KCP는 KRW 결제만 지원합니다. (${t})`:`NHN KCP supports KRW payments only. (${t})`}function Xe(e){const t=Math.max(0,Math.round(Number(e.amount??0))),n=Math.min(Math.max(0,Math.round(Number(e.tax_free_amount??0))),t);if(n<=0)return{};const o=Math.max(0,Math.round(Number(e.tax_amount??0))),r=Math.max(0,Math.round(Number(e.vat_amount??0))),a=Math.max(0,t-n),s=a>0&&o>0&&r>0?Math.min(a,Math.round(a*(r/o))):0,i=a-s;return{tax_flag:"TG03",comm_tax_mny:String(i),comm_vat_mny:String(s),comm_free_mny:String(n)}}class $ extends Error{constructor(t){super(t??"결제가 취소되었습니다."),this.name="KcpCancelledError"}}const Ze={card:"100000000000",bank_transfer:"010000000000",virtual_account:"001000000000",mobile:"000010000000",bank:"010000000000",vbank:"001000000000",phone:"000010000000"},se={nhnkcp_payco:{payco_direct:"Y"},nhnkcp_naverpay:{naverpay_direct:"Y"},nhnkcp_naverpay_point:{naverpay_direct:"Y",naverpay_point_direct:"Y"},nhnkcp_kakaopay:{kakaopay_direct:"Y"},nhnkcp_applepay:{applepay_direct:"Y"}};function et(e,t){const n=e.toLowerCase();return!t||!Object.prototype.hasOwnProperty.call(se,n)?{}:{param_opt_1:n,nhnkcp_easy_pay_method:n}}function tt(e){if(!e.isConnected)return!0;const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!0;const n=e.getBoundingClientRect();return n.width<=0||n.height<=0}function nt(e,t){let n=!1,o,r;const a=()=>{n=!0,r&&(r.disconnect(),r=void 0),o!==void 0&&(window.clearInterval(o),o=void 0)},s=()=>{n||!tt(e)||(a(),t())},i=document.body??document.documentElement;return i&&typeof MutationObserver<"u"&&(r=new MutationObseLine truncated
<script src="${e.sdk_url}"><\/script>
</head><body style="margin:0;padding:0;background:transparent;">
<form name="order_info">${c}</form>
@@ -14,4 +14,4 @@ try {
window.__kcpFail && window.__kcpFail(e);
}
<\/script>
</body></html>`),ee.close(),y=window.setTimeout(()=>{N(new Error("KCP SDK load timeout"))},15e3),f.__kcpReady=()=>{y!==void 0&&(clearTimeout(y),y=void 0)}})}const rt={nhnkcp_payco:"PAYCO",nhnkcp_naverpay:"네이버페이",nhnkcp_naverpay_point:"네이버페이 포인트",nhnkcp_kakaopay:"카카오페이",nhnkcp_applepay:"Apple Pay"},at="0 0 0 2px #ffffff, 0 0 0 5px rgba(0,0,0,0.55)";function ie(){return document.querySelector(".nhnkcp-easy-pay-btns")??null}function ce(){const e=ie();e&&e.querySelectorAll("button").forEach(t=>{t.style.boxShadow="",t.style.outline=""})}function st(e){const t=ie();if(!t)return;const n=rt[e];t.querySelectorAll("button").forEach(o=>{o.textContent?.trim()===n?(o.style.boxShadow=at,o.style.outline="none"):(o.style.boxShadow="",o.style.outline="")})}function it(e){const t=e.params?.paymentMethod;if(!t)return;const n=window.G7Core;if(T(t)&&!x()){const r=R();n?.state?.setLocal?.({paymentErrorMessage:r,isSubmittingOrder:!1}),n?.modal?.open?.("nhnkcp_payment_error_modal"),ce();return}const o=typeof t=="string"&&t.startsWith("nhnkcp_");n?.state?.setLocal?.({paymentMethod:t}),o?st(t):ce()}function ct(e){const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","readonly"),t.style.position="fixed",t.style.left="-9999px",t.style.top="0",document.body.appendChild(t),t.select();try{document.execCommand("copy")}finally{t.remove()}}async function dt(e){const t=String(e.params?.text??"");if(t!==""){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(t);return}ct(t)}}const de={requestPayment:tt,setPaymentMethod:it,copyToClipboard:dt},le="/api/modules/sirsoft-ecommerce/user/orders",O="sirsoft-pay_nhnkcp",ue={info:(...e)=>console.info(`[${O}]`,...e),warn:(...e)=>console.warn(`[${O}]`,...e),error:(...e)=>console.error(`[${O}]`,...e)};function lt(e){return typeof e=="string"?e:e instanceof URL?e.toString():typeof Request<"u"&&e instanceof Request?e.url:String(e)}function ut(e,t){return t?.method?t.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function pt(e,t){if(t!=="POST")return!1;const n=e.split("?")[0].split("#")[0];return n===le||n.endsWith(le)}function mt(e){try{return JSON.parse(e).payment_method}catch{return}}function ft(e){return new Response(JSON.stringify({success:!1,message:e,error:e,errors:{payment_method:[e]}}),{status:422,statusText:"Unprocessable Content",headers:{"Content-Type":"application/json"}})}function yt(){if(typeof window>"u"||typeof window.fetch!="function")return;const e="__sirsoftNhnkcpInterceptorInstalled",t=window;if(t[e])return;t[e]=!0;const n=window.fetch.bind(window);window.fetch=async function(r,a){const s=lt(r),i=ut(r,a);if(!pt(s,i))return n(r,a);let c;if(a?.body&&typeof a.body=="string"&&(c=mt(a.body)),T(c)&&!x()){const d=R();return ue.warn(d),ft(d)}return n(r,a)},ue.info("order request interceptor installed (Apple Pay device guard)")}const K="sirsoft-pay_nhnkcp",pe="__kcpOcReceiptInjectorInstalled",me="kcp-oc-receipt-btn",ht=/^\/shop\/orders\/([^/]+)\/complete$/;function fe(){return localStorage.getItem("auth_token")}async function _t(e){const t=fe();if(!t)return null;try{const n=await fetch(`/api/modules/sirsoft-ecommerce/user/orders/${e}`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?(await n.json())?.data?.payment??null:null}catch{return null}}async function j(e){const t=fe();if(!t)return null;try{const n=await fetch(`/api/plugins/${K}/user/orders/${e}/receipt`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?await n.json():null}catch{return null}}function ye(e,t,n){const o=document.createElement("button");return o.type="button",o.className=t,o.textContent=e,o.addEventListener("click",()=>n(o)),o}function gt(e){if(!e)return!1;const t=Array.from(document.querySelectorAll("div"));for(const n of t){const o=Array.from(n.children).filter(s=>s instanceof HTMLElement&&s.tagName==="SPAN");if(o.length<2)continue;const r=o[0].textContent?.trim();if(r!=="결제 방법"&&r!=="결제수단"&&r!=="결제 방식")continue;const a=o[o.length-1];return a.textContent?.trim()===e?(n.dataset.nhnkcpPaymentMethodRow="true",!0):(a.textContent=e,a.dataset.nhnkcpPaymentMethodPatched="true",n.dataset.nhnkcpPaymentMethodRow="true",!0)}return!1}async function wt(e){if(document.getElementById(me))return;const t=await _t(e);if(!t||t.pg_provider!=="nhnkcp"||!t.transaction_id||!t.paid_at)return;const n=Array.from(document.querySelectorAll('button[type="button"]')).find(c=>c.className.includes("bg-blue-600"));if(!n?.parentElement)return;const o=await j(e);gt(o?.payment_method_display_label);const r=n.parentElement,a=ye("영수증 조회",n.className.replace(/bg-blue-\d+/g,"bg-green-600").replace(/hover:bg-blue-\d+/g,"hover:bg-green-700"),async c=>{c.disabled=!0,c.textContent="로딩 중...";const d=await j(e);if(c.disabled=!1,c.textContent="영수증 조회",d){const l=window.KcpReceiptPopup;l&&new l({url:d.rLine truncated
</body></html>`),ee.close(),y=window.setTimeout(()=>{N(new Error("KCP SDK load timeout"))},15e3),f.__kcpReady=()=>{y!==void 0&&(clearTimeout(y),y=void 0)}})}const it={nhnkcp_payco:"PAYCO",nhnkcp_naverpay:"네이버페이",nhnkcp_naverpay_point:"네이버페이 포인트",nhnkcp_kakaopay:"카카오페이",nhnkcp_applepay:"Apple Pay"},ct="0 0 0 2px #ffffff, 0 0 0 5px rgba(0,0,0,0.55)";function ie(){return document.querySelector(".nhnkcp-easy-pay-btns")??null}function ce(){const e=ie();e&&e.querySelectorAll("button").forEach(t=>{t.style.boxShadow="",t.style.outline=""})}function dt(e){const t=ie();if(!t)return;const n=it[e];t.querySelectorAll("button").forEach(o=>{o.textContent?.trim()===n?(o.style.boxShadow=ct,o.style.outline="none"):(o.style.boxShadow="",o.style.outline="")})}function lt(e){const t=e.params?.paymentMethod;if(!t)return;const n=window.G7Core;if(T(t)&&!x()){const r=R();n?.state?.setLocal?.({paymentErrorMessage:r,isSubmittingOrder:!1}),n?.modal?.open?.("nhnkcp_payment_error_modal"),ce();return}const o=typeof t=="string"&&t.startsWith("nhnkcp_");n?.state?.setLocal?.({paymentMethod:t}),o?dt(t):ce()}function ut(e){const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","readonly"),t.style.position="fixed",t.style.left="-9999px",t.style.top="0",document.body.appendChild(t),t.select();try{document.execCommand("copy")}finally{t.remove()}}async function pt(e){const t=String(e.params?.text??"");if(t!==""){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(t);return}ut(t)}}const de={requestPayment:rt,setPaymentMethod:lt,copyToClipboard:pt},le="/api/modules/sirsoft-ecommerce/user/orders",O="sirsoft-pay_nhnkcp",ue={info:(...e)=>console.info(`[${O}]`,...e),warn:(...e)=>console.warn(`[${O}]`,...e),error:(...e)=>console.error(`[${O}]`,...e)};function mt(e){return typeof e=="string"?e:e instanceof URL?e.toString():typeof Request<"u"&&e instanceof Request?e.url:String(e)}function ft(e,t){return t?.method?t.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function yt(e,t){if(t!=="POST")return!1;const n=e.split("?")[0].split("#")[0];return n===le||n.endsWith(le)}function ht(e){try{return JSON.parse(e).payment_method}catch{return}}function _t(e){return new Response(JSON.stringify({success:!1,message:e,error:e,errors:{payment_method:[e]}}),{status:422,statusText:"Unprocessable Content",headers:{"Content-Type":"application/json"}})}function gt(){if(typeof window>"u"||typeof window.fetch!="function")return;const e="__sirsoftNhnkcpInterceptorInstalled",t=window;if(t[e])return;t[e]=!0;const n=window.fetch.bind(window);window.fetch=async function(r,a){const s=mt(r),i=ft(r,a);if(!yt(s,i))return n(r,a);let c;if(a?.body&&typeof a.body=="string"&&(c=ht(a.body)),T(c)&&!x()){const d=R();return ue.warn(d),_t(d)}return n(r,a)},ue.info("order request interceptor installed (Apple Pay device guard)")}const K="sirsoft-pay_nhnkcp",pe="__kcpOcReceiptInjectorInstalled",me="kcp-oc-receipt-btn",wt=/^\/shop\/orders\/([^/]+)\/complete$/;function fe(){return localStorage.getItem("auth_token")}async function bt(e){const t=fe();if(!t)return null;try{const n=await fetch(`/api/modules/sirsoft-ecommerce/user/orders/${e}`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?(await n.json())?.data?.payment??null:null}catch{return null}}async function j(e){const t=fe();if(!t)return null;try{const n=await fetch(`/api/plugins/${K}/user/orders/${e}/receipt`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?await n.json():null}catch{return null}}function ye(e,t,n){const o=document.createElement("button");return o.type="button",o.className=t,o.textContent=e,o.addEventListener("click",()=>n(o)),o}function kt(e){if(!e)return!1;const t=Array.from(document.querySelectorAll("div"));for(const n of t){const o=Array.from(n.children).filter(s=>s instanceof HTMLElement&&s.tagName==="SPAN");if(o.length<2)continue;const r=o[0].textContent?.trim();if(r!=="결제 방법"&&r!=="결제수단"&&r!=="결제 방식")continue;const a=o[o.length-1];return a.textContent?.trim()===e?(n.dataset.nhnkcpPaymentMethodRow="true",!0):(a.textContent=e,a.dataset.nhnkcpPaymentMethodPatched="true",n.dataset.nhnkcpPaymentMethodRow="true",!0)}return!1}async function Ct(e){if(document.getElementById(me))return;const t=await bt(e);if(!t||t.pg_provider!=="nhnkcp"||!t.transaction_id||!t.paid_at)return;const n=Array.from(document.querySelectorAll('button[type="button"]')).find(c=>c.className.includes("bg-blue-600"));if(!n?.parentElement)return;const o=await j(e);kt(o?.payment_method_display_label);const r=n.parentElement,a=ye("영수증 조회",n.className.replace(/bg-blue-\d+/g,"bg-green-600").replace(/hover:bg-blue-\d+/g,"hover:bg-green-700"),async c=>{c.disabled=!0,c.textContent="로딩 중...";const d=await j(e);if(c.disabled=!1,c.textContent="영수증 조회",d){const l=window.KcpReceiptPopup;l&&new l({url:d.rLine truncated
@@ -14,9 +14,9 @@
| `sirsoft-pay_nhnkcp.escrow.purchase_cancelled` | action | — | `src/Controllers/EscrowCommonNotifyController.php:97` |
| `sirsoft-pay_nhnkcp.escrow.purchase_confirmed` | action | — | `src/Controllers/EscrowCommonNotifyController.php:96` |
| `sirsoft-pay_nhnkcp.payment.after_cancel` | action | KCP 결제 취소 완료 후 | `src/Services/NhnKcpApiService.php:250` |
| `sirsoft-pay_nhnkcp.payment.after_confirm` | action | KCP 결제 승인 확인 완료 후 | `src/Controllers/PaymentCallbackController.php:276` |
| `sirsoft-pay_nhnkcp.payment.after_confirm` | action | KCP 결제 승인 확인 완료 후 | `src/Controllers/PaymentCallbackController.php:278` |
| `sirsoft-pay_nhnkcp.payment.before_cancel` | action | KCP 결제 취소 API 호출 전 (본인인증 등 확장 지점) | `src/Services/NhnKcpApiService.php:229` |
| `sirsoft-pay_nhnkcp.payment.before_confirm` | action | KCP 결제 승인 확인 전 | `src/Controllers/PaymentCallbackController.php:271` |
| `sirsoft-pay_nhnkcp.payment.before_confirm` | action | KCP 결제 승인 확인 전 | `src/Controllers/PaymentCallbackController.php:273` |
<!-- @generated:hooks-published END -->
<!-- @intent START -->
@@ -20,6 +20,14 @@
},
"plugins": {}
},
"trusted_script_hosts": [
"testpay.kcp.co.kr",
"pay.kcp.co.kr"
],
"trusted_script_hosts_reason": {
"testpay.kcp.co.kr": "NHN KCP 테스트 결제창 SDK 다. 스크립트가 KCP 서버와 통신하므로 자체 호스팅해도 결제가 성립하지 않는다.",
"pay.kcp.co.kr": "NHN KCP 운영 결제창 SDK 다. 스크립트가 KCP 서버와 통신하므로 자체 호스팅해도 결제가 성립하지 않는다."
},
"assets": {
"js": {
"entry": "resources/js/index.ts",
@@ -6,8 +6,10 @@
* tests/scenarios 매니페스트(통합 시나리오)에서 다루며, 본 단위 테스트는
* "초기 가드 + catch 블록 정상 호출" 두 축에 집중합니다.
*/
import { readFileSync } from 'fs';
import { resolve } from 'path';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
import { assertTrustedSdkUrl, KNOWN_SDK_HOSTS,
buildKcpEasyPayReturnFields,
buildKcpTaxFields,
isSupportedKcpCurrency,
@@ -223,3 +225,54 @@ describe('requestPaymentHandler', () => {
expect(buildKcpEasyPayReturnFields('nhnkcp_unknown', true)).toEqual({});
});
});
/**
* SDK 주입 출처 게이트 (동적 스크립트 주입 정책).
*
* PG SDK 는 서비스 SDK 라 자체 호스팅할 수 없다. 그래서 **주입 직전에** 호스트를
* 확인하는 것이 유일한 게이트다. 확장자 없는 SDK URL 은 정적 검사에도 걸리지 않는다.
*
* manifest `trusted_script_hosts` 와 코드 상수가 어긋나면 그 차집합이 그대로
* 사각이 되므로 두 목록의 일치도 함께 고정한다.
*/
describe('SDK URL 신뢰 호스트 게이트', () => {
const TRUSTED_SDK_URL = 'https://pay.kcp.co.kr/plugin/payplus_web.jsp';
it('신뢰 호스트 https URL 은 통과한다', () => {
expect(() => assertTrustedSdkUrl(TRUSTED_SDK_URL)).not.toThrow();
});
it.each([
['미신뢰 호스트', 'https://cdn.evil.com/sdk.js'],
['http (평문)', TRUSTED_SDK_URL.replace('https://', 'http://')],
['protocol-relative', TRUSTED_SDK_URL.replace('https://', '//')],
['상대 경로', '/local/sdk.js'],
['빈 문자열', ''],
['javascript 스킴', 'javascript:alert(1)'],
['신뢰 호스트를 userinfo 로 위장', 'https://evil.com/@' + new URL(TRUSTED_SDK_URL).hostname + '/x.js'],
['신뢰 호스트를 서브도메인 접미로 위장', 'https://' + new URL(TRUSTED_SDK_URL).hostname + '.evil.com/x.js'],
])('%s 는 거부된다', (_label, url) => {
expect(() => assertTrustedSdkUrl(url as string)).toThrow();
});
it('manifest trusted_script_hosts 와 KNOWN_SDK_HOSTS 가 일치한다', () => {
const manifest = JSON.parse(
readFileSync(resolve(__dirname, '../../../../plugin.json'), 'utf-8')
);
expect([...(manifest.trusted_script_hosts ?? [])].sort()).toEqual(
[...KNOWN_SDK_HOSTS].sort()
);
});
it('manifest 가 호스트별 사유를 함께 선언한다', () => {
const manifest = JSON.parse(
readFileSync(resolve(__dirname, '../../../../plugin.json'), 'utf-8')
);
for (const host of KNOWN_SDK_HOSTS) {
expect(typeof manifest.trusted_script_hosts_reason?.[host]).toBe('string');
expect(manifest.trusted_script_hosts_reason[host].length).toBeGreaterThan(0);
}
});
});
@@ -47,6 +47,64 @@ export function isSupportedKcpCurrency(currency?: string): boolean {
return normalizeCurrency(currency) === 'KRW';
}
/**
* SDK 스크립트를 로드할 수 있는 호스트 (plugin.json `trusted_script_hosts` 미러).
*
* NHN KCP 결제창은 라이브러리가 아니라 그 회사 서버와 통신하는 서비스 SDK 라
* 자체 호스팅할 수 없다. 대신 **주입 직전에** 호스트를 확인해, 설정·응답이 어떤
* 경로로든 다른 주소를 지시하면 결제를 진행하지 않는다(fail-closed).
*
* PG사가 SDK 호스트를 바꾸면 이 상수와 plugin.json 을 **함께** 갱신한다 —
* 둘이 어긋나면 테스트가 실패한다.
*/
export const KNOWN_SDK_HOSTS: readonly string[] = ['testpay.kcp.co.kr', 'pay.kcp.co.kr'];
/**
* 번역 문자열을 얻습니다.
*
* @param key 번역 키 (플러그인 네임스페이스 이하)
* @param fallback 번역 엔진 부재 시 사용할 문구
* @returns 번역된 문자열
*/
function t(key: string, fallback: string): string {
const translate = (window as any)?.G7Core?.t;
if (typeof translate !== 'function') {
return fallback;
}
const full = `sirsoft-pay_nhnkcp.${key}`;
const result = translate(full);
return typeof result === 'string' && result !== full ? result : fallback;
}
/**
* SDK URL 이 신뢰 호스트인지 확인하고, 아니면 예외를 던집니다.
*
* @param url 주입할 SDK URL
* @throws Error 미신뢰 호스트이거나 https 가 아닌 경우
*/
export function assertTrustedSdkUrl(url: string): void {
let parsed: URL | null = null;
try {
parsed = new URL(url);
} catch {
parsed = null;
}
if (
parsed === null
|| parsed.protocol !== 'https:'
|| !KNOWN_SDK_HOSTS.includes(parsed.hostname.toLowerCase())
) {
throw new Error(
t('payment.error.sdk_url_untrusted', '결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다.')
);
}
}
function unsupportedCurrencyMessage(currency?: string): string {
const normalized = normalizeCurrency(currency);
const isKo = ((typeof document !== 'undefined' ? document.documentElement.lang : '') || '')
@@ -468,6 +526,11 @@ async function handlePcPayment(
.map(([n, v]) => `<input type="hidden" name="${n}" value="${v.replace(/"/g, '&quot;')}">`)
.join('');
// SDK 주입 직전 출처 확인 — 아래 iframe `document.write` 는 코어 로더를 쓸 수 없으므로
// (동기 실행 순서가 KCP_Pay_Execute 호출 계약이다) 검증만 선행한다. 실패 시 결제를
// 진행하지 않는다(fail-closed).
assertTrustedSdkUrl(config.sdk_url);
await new Promise<void>((resolve, reject) => {
// 기존 요소 정리
document.getElementById('kcp-sdk-iframe')?.remove();
@@ -154,5 +154,10 @@
},
"easy_pay": {
"section_title": "Easy Pay"
},
"payment": {
"error": {
"sdk_url_untrusted": "The payment module address is not valid, so the payment cannot proceed. Please contact the administrator."
}
}
}
@@ -154,5 +154,10 @@
},
"easy_pay": {
"section_title": "간편결제"
},
"payment": {
"error": {
"sdk_url_untrusted": "결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다. 관리자에게 문의해 주세요."
}
}
}
@@ -118,6 +118,7 @@ API 와 동기화하는 역할만 합니다. 등록은 훅 기반입니다
- [ ] IP 화이트리스트(`VbankNotifyIpWhitelist`) 대상 라우트를 추가/변경하면 미들웨어 부착 대상(targets)도 함께 갱신
- [ ] 새 간편결제 수단을 추가하면 그 결제수단의 계약 상태를 관리자 안내에도 반영
- [ ] 레이아웃·컴포넌트·`data_source` 를 건드렸다면 [`docs/editor-spec.md`](docs/editor-spec.md) 의 동반 의무 표를 따라 `editor-spec.json` 을 함께 갱신 — 샘플이 없는 `data_source` 는 편집기 캔버스에서만 빈 화면이 되고 실제 화면은 정상이라 오류도 경고도 남지 않는다. 반영은 `php artisan plugin:update sirsoft-pay_nicepayments --force`
- [ ] 나이스페이먼츠가 SDK 호스트를 바꾸면 `plugin.json` 의 `trusted_script_hosts`(+`trusted_script_hosts_reason`)와 `resources/js/handlers/requestPayment.ts` 의 `KNOWN_SDK_HOSTS` 를 **함께** 갱신 — 두 목록이 어긋나면 테스트가 실패하며, 코드 상수에 없는 호스트는 주입 직전 확인에서 거부되어 결제가 진행되지 않는다(fail-closed). 변경 후 `php artisan ext:docgen --scope=plugin:sirsoft-pay_nicepayments` 재실행
## 6. 금지 패턴
@@ -8,6 +8,7 @@
### Security
- 결제창 프로그램을 불러오는 주소가 나이스페이먼츠의 주소인지 불러오기 직전에 확인합니다. 확인되지 않는 주소면 결제를 진행하지 않고 안내를 표시합니다. 또한 결제창 프로그램이 실제로 준비되었는지를 기준으로 다음 단계를 진행하도록 바꿔, 프로그램이 아직 준비되지 않았는데 결제창이 열리지 않고 멈추던 상황을 없앴습니다.
- 결제창이 넘겨준 승인 요청 주소에 마침표·빗금처럼 보이는 특수문자를 섞으면, 나이스페이먼츠 도메인 검사를 통과하면서 실제로는 다른 서버로 승인 요청이 나갈 수 있던 문제를 수정했습니다. 그 요청에는 인증 토큰과 상점 아이디가 실려 있어 외부로 유출될 수 있었습니다. 이제 검사와 실제 연결이 주소를 같은 방식으로 해석하며, 로그인 정보가 포함된 주소도 거부합니다. 정상적인 나이스페이먼츠 주소는 그대로 사용됩니다.
### Added
@@ -79,6 +79,7 @@ URL로 결과를 POST 하면 결제 완료 처리됩니다.
| 그누보드7 코어 | `>=7.0.10` |
| PHP | `^8.2` |
| 의존 모듈 | `sirsoft-ecommerce` `>=1.1.0` |
| 외부 스크립트 호스트 | `web.nicepay.co.kr` |
<!-- @generated:requirements END -->
<!-- @intent START -->
@@ -1,7 +1,7 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"identifier": "sirsoft-pay_nicepayments",
"version": "1.0.1",
"version": "1.0.3",
"components": {
"basic": [],
"composite": [],
@@ -1 +1 @@
(function(){"use strict";function le(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function de(e){return e.trim().slice(0,160)}async function ue(e,t="nicepay-window-closed"){if(!e.closeReportUrl)return;const n={oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??"",reason:de(t)||"nicepay-window-closed"};try{const a=window.G7Core?.api;if(typeof a?.post=="function"){await a.post(e.closeReportUrl,n);return}await fetch(le(e.closeReportUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),keepalive:!0})}catch(a){console.warn("[sirsoft-pay_nicepayments] failed to report payment window close",a)}}function pe(e){return new Promise((t,n)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}const a=document.createElement("script");a.src=e,a.onload=()=>t(),a.onerror=()=>n(new Error(`Failed to load script: ${e}`)),document.head.appendChild(a)})}function me(e,t){const n=document.createElement("form");n.id="nicepayForm",n.method="post",n.action=e,n.acceptCharset="utf-8";for(const[a,r]of Object.entries(t)){const o=document.createElement("input");o.type="hidden",o.name=a,o.value=r,n.appendChild(o)}return document.body.appendChild(n),n}const ye="/plugins/sirsoft-pay_nicepayments/payment/callback",fe="https://web.nicepay.co.kr/v3/v3Payment.jsp";function he(){if(typeof navigator>"u")return!1;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(navigator.userAgent||"").toLowerCase();return!!(/android|iphone|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||(navigator.maxTouchPoints??0)>1&&!t.includes("windows")&&!t.includes("macintosh"))}async function be(e,t){const{pgPaymentData:n,paymentMethod:a}=e.params??{},r=window.__templateApp?.globalState?._local,o=a??n?.payment_method??r?.paymentMethod??"card";if(!n){console.error("[sirsoft-pay_nicepayments] pgPaymentData is required");return}const i=window.G7Core;try{const s=await i.api.get("/modules/sirsoft-ecommerce/payments/client-config/nicepayments");if(!s.data){console.error("[sirsoft-pay_nicepayments] Failed to fetch client config",s);return}const l=s.data,d=he();if(!d&&(await pe(l.sdk_url),typeof window.goPay!="function")){i?.toast?.error?.("나이스페이먼츠 SDK를 불러올 수 없습니다. 잠시 후 다시 시도해주세요."),i?.state?.setLocal?.({isSubmittingOrder:!1,paymentMethod:o});return}const _=window.location.origin+l.sign_data_url,u=typeof localStorage<"u"?localStorage.getItem("auth_token"):null,te={"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest",Accept:"application/json"};u&&(te.Authorization=`Bearer ${u}`);const ne=await fetch(_,{method:"POST",credentials:"include",headers:te,body:JSON.stringify({amt:n.amount,moid:n.order_number,buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??""})});if(!ne.ok)throw new Error("SignData 생성에 실패했습니다.");const L=await ne.json(),ae=window.location.origin+ye,M=typeof o=="string"&&o.startsWith("nicepay_"),oe=M?"CARD":{card:"CARD",vbank:"VBANK",bank:"BANK",phone:"CELLPHONE"}[o??"card"]??"CARD",c={PayMethod:oe,GoodsName:n.order_name,Amt:String(n.amount),MID:L.mid,Moid:n.order_number,BuyerName:n.customer_name??"",BuyerEmail:n.customer_email??"",BuyerTel:n.customer_phone??"",ReturnURL:ae,EdiDate:L.ediDate,SignData:L.signData,CharSet:"utf-8",GoodsCl:"1",DirectShowOpt:"",DirectEasyPay:"",NicepayReserved:"",EasyPayMethod:"",MallReserved:"",MallReserved1:""};oe==="CELLPHONE"&&(c.GoodsCl=n.goods_cl??"1");const ft=l.useEscrow&&!M;if(c.TransType=ft?"1":"0",M)switch(c.DirectShowOpt="CARD",c.MallReserved=`nicepay_easy_pay_method=${encodeURIComponent(o)}`,c.MallReserved1=o,o){case"nicepay_naverpay":c.DirectEasyPay="E020",c.EasyPayMethod="E020=CARD";break;case"nicepay_kakaopay":c.NicepayReserved="DirectKakao=Y";break;case"nicepay_samsungpay":c.DirectEasyPay="E021";break;case"nicepay_applepay":c.DirectEasyPay="E025";break;case"nicepay_payco":c.NicepayReserved="DirectPayco=Y";break;case"nicepay_skpay":c.NicepayReserved="DirectPay11=Y";break;case"nicepay_ssgpay":c.DirectEasyPay="E007";break;case"nicepay_lpay":c.DirectEasyPay="E018";break}try{const m=(await i.api.get(`/modules/sirsoft-ecommerce/user/orders/${n.order_number}`))?.data;if(m){const P=Number(m.total_tax_amount??0),h=Number(m.total_vat_amount??0),ce=Number(m.total_tax_free_amount??0);(P>0||h>0||ce>0)&&(c.TaxAmt=String(P),c.VatAmt=String(h),c.TaxFreeAmt=String(ce))}}catch{}const p=me(ae,c);if(d){p.action=fe,p.acceptCharset="euc-kr";const f=p.querySelector('input[name="CharSet"]');f&&(f.value="euc-kr"),p.submit();return}window.nicepaySubmit=()=>{p.submit()};let re=!1;const ht=new Set(document.body.children),ie=(f,m)=>{if(re)return;re=!0;const P=[f,m].filter(Boolean).join(": ")||"nicepay-window-closed";ue({closeReportUrl:l.close_report_url,oid:n.order_number,price:Number(n.aLine truncated
(function(){"use strict";function le(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function de(e){return e.trim().slice(0,160)}async function ue(e,t="nicepay-window-closed"){if(!e.closeReportUrl)return;const n={oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??"",reason:de(t)||"nicepay-window-closed"};try{const a=window.G7Core?.api;if(typeof a?.post=="function"){await a.post(e.closeReportUrl,n);return}await fetch(le(e.closeReportUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),keepalive:!0})}catch(a){console.warn("[sirsoft-pay_nicepayments] failed to report payment window close",a)}}const pe=["web.nicepay.co.kr"];function me(e,t){const n=window?.G7Core?.t;if(typeof n!="function")return t;const a=`sirsoft-pay_nicepayments.${e}`,r=n(a);return typeof r=="string"&&r!==a?r:t}function ye(e){let t=null;try{t=new URL(e)}catch{t=null}if(t===null||t.protocol!=="https:"||!pe.includes(t.hostname.toLowerCase()))throw new Error(me("payment.error.sdk_url_untrusted","결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다."))}async function fe(e){if(ye(e),typeof window.goPay=="function")return;document.querySelectorAll(`script[src="${CSS.escape(e)}"]`).forEach(n=>n.remove());const t=window?.G7Core?.asset?.loadScript;if(typeof t=="function"){await t(e,{},{label:"nicepayments SDK"});return}await new Promise((n,a)=>{const r=document.createElement("script");r.src=e,r.onload=()=>n(),r.onerror=()=>a(new Error(`Failed to load script: ${e}`)),document.head.appendChild(r)})}function he(e,t){const n=document.createElement("form");n.id="nicepayForm",n.method="post",n.action=e,n.acceptCharset="utf-8";for(const[a,r]of Object.entries(t)){const o=document.createElement("input");o.type="hidden",o.name=a,o.value=r,n.appendChild(o)}return document.body.appendChild(n),n}const we="/plugins/sirsoft-pay_nicepayments/payment/callback",be="https://web.nicepay.co.kr/v3/v3Payment.jsp";function ge(){if(typeof navigator>"u")return!1;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(navigator.userAgent||"").toLowerCase();return!!(/android|iphone|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||(navigator.maxTouchPoints??0)>1&&!t.includes("windows")&&!t.includes("macintosh"))}async function _e(e,t){const{pgPaymentData:n,paymentMethod:a}=e.params??{},r=window.__templateApp?.globalState?._local,o=a??n?.payment_method??r?.paymentMethod??"card";if(!n){console.error("[sirsoft-pay_nicepayments] pgPaymentData is required");return}const i=window.G7Core;try{const s=await i.api.get("/modules/sirsoft-ecommerce/payments/client-config/nicepayments");if(!s.data){console.error("[sirsoft-pay_nicepayments] Failed to fetch client config",s);return}const l=s.data,d=ge();if(!d&&(await fe(l.sdk_url),typeof window.goPay!="function")){i?.toast?.error?.("나이스페이먼츠 SDK를 불러올 수 없습니다. 잠시 후 다시 시도해주세요."),i?.state?.setLocal?.({isSubmittingOrder:!1,paymentMethod:o});return}const _=window.location.origin+l.sign_data_url,u=typeof localStorage<"u"?localStorage.getItem("auth_token"):null,te={"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest",Accept:"application/json"};u&&(te.Authorization=`Bearer ${u}`);const ne=await fetch(_,{method:"POST",credentials:"include",headers:te,body:JSON.stringify({amt:n.amount,moid:n.order_number,buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??""})});if(!ne.ok)throw new Error("SignData 생성에 실패했습니다.");const I=await ne.json(),ae=window.location.origin+we,M=typeof o=="string"&&o.startsWith("nicepay_"),oe=M?"CARD":{card:"CARD",vbank:"VBANK",bank:"BANK",phone:"CELLPHONE"}[o??"card"]??"CARD",c={PayMethod:oe,GoodsName:n.order_name,Amt:String(n.amount),MID:I.mid,Moid:n.order_number,BuyerName:n.customer_name??"",BuyerEmail:n.customer_email??"",BuyerTel:n.customer_phone??"",ReturnURL:ae,EdiDate:I.ediDate,SignData:I.signData,CharSet:"utf-8",GoodsCl:"1",DirectShowOpt:"",DirectEasyPay:"",NicepayReserved:"",EasyPayMethod:"",MallReserved:"",MallReserved1:""};oe==="CELLPHONE"&&(c.GoodsCl=n.goods_cl??"1");const bt=l.useEscrow&&!M;if(c.TransType=bt?"1":"0",M)switch(c.DirectShowOpt="CARD",c.MallReserved=`nicepay_easy_pay_method=${encodeURIComponent(o)}`,c.MallReserved1=o,o){case"nicepay_naverpay":c.DirectEasyPay="E020",c.EasyPayMethod="E020=CARD";break;case"nicepay_kakaopay":c.NicepayReserved="DirectKakao=Y";break;case"nicepay_samsungpay":c.DirectEasyPay="E021";break;case"nicepay_applepay":c.DirectEasyPay="E025";break;case"nicepay_payco":c.NicepayReserved="DirectPayco=Y";break;case"nicepay_skpay":c.NicepayReserved="DirectPay11=Y";break;case"nicepay_ssgpay":c.DirectEasyPay="E007";break;case"nicepay_lpay":c.DirectEasyPay="E018";break}try{const m=(await i.api.get(`/modules/sirsoft-ecommerc Line truncated
@@ -20,6 +20,12 @@
},
"plugins": {}
},
"trusted_script_hosts": [
"web.nicepay.co.kr"
],
"trusted_script_hosts_reason": {
"web.nicepay.co.kr": "나이스페이먼츠 결제창 SDK 다. 스크립트가 나이스페이먼츠 서버와 통신하므로 자체 호스팅해도 결제가 성립하지 않는다."
},
"assets": {
"js": {
"entry": "resources/js/index.ts",
@@ -6,8 +6,10 @@
* tests/scenarios 매니페스트(통합 시나리오)에서 다루며, 본 단위 테스트는
* "초기 가드 + catch 블록 정상 호출" 두 축에 집중합니다.
*/
import { readFileSync } from 'fs';
import { resolve } from 'path';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { requestPaymentHandler } from '../../handlers/requestPayment';
import { assertTrustedSdkUrl, KNOWN_SDK_HOSTS, requestPaymentHandler } from '../../handlers/requestPayment';
const PG_PAYMENT = {
order_number: 'ORD-001',
@@ -283,3 +285,54 @@ describe('requestPaymentHandler', () => {
});
});
});
/**
* SDK 주입 출처 게이트 (동적 스크립트 주입 정책).
*
* PG SDK 는 서비스 SDK 라 자체 호스팅할 수 없다. 그래서 **주입 직전에** 호스트를
* 확인하는 것이 유일한 게이트다. 확장자 없는 SDK URL 은 정적 검사에도 걸리지 않는다.
*
* manifest `trusted_script_hosts` 와 코드 상수가 어긋나면 그 차집합이 그대로
* 사각이 되므로 두 목록의 일치도 함께 고정한다.
*/
describe('SDK URL 신뢰 호스트 게이트', () => {
const TRUSTED_SDK_URL = 'https://web.nicepay.co.kr/v3/webstd/js/nicepay-3.0.js';
it('신뢰 호스트 https URL 은 통과한다', () => {
expect(() => assertTrustedSdkUrl(TRUSTED_SDK_URL)).not.toThrow();
});
it.each([
['미신뢰 호스트', 'https://cdn.evil.com/sdk.js'],
['http (평문)', TRUSTED_SDK_URL.replace('https://', 'http://')],
['protocol-relative', TRUSTED_SDK_URL.replace('https://', '//')],
['상대 경로', '/local/sdk.js'],
['빈 문자열', ''],
['javascript 스킴', 'javascript:alert(1)'],
['신뢰 호스트를 userinfo 로 위장', 'https://evil.com/@' + new URL(TRUSTED_SDK_URL).hostname + '/x.js'],
['신뢰 호스트를 서브도메인 접미로 위장', 'https://' + new URL(TRUSTED_SDK_URL).hostname + '.evil.com/x.js'],
])('%s 는 거부된다', (_label, url) => {
expect(() => assertTrustedSdkUrl(url as string)).toThrow();
});
it('manifest trusted_script_hosts 와 KNOWN_SDK_HOSTS 가 일치한다', () => {
const manifest = JSON.parse(
readFileSync(resolve(__dirname, '../../../../plugin.json'), 'utf-8')
);
expect([...(manifest.trusted_script_hosts ?? [])].sort()).toEqual(
[...KNOWN_SDK_HOSTS].sort()
);
});
it('manifest 가 호스트별 사유를 함께 선언한다', () => {
const manifest = JSON.parse(
readFileSync(resolve(__dirname, '../../../../plugin.json'), 'utf-8')
);
for (const host of KNOWN_SDK_HOSTS) {
expect(typeof manifest.trusted_script_hosts_reason?.[host]).toBe('string');
expect(manifest.trusted_script_hosts_reason[host].length).toBeGreaterThan(0);
}
});
});
@@ -82,13 +82,93 @@ declare global {
}
}
function loadScript(src: string): Promise<void> {
return new Promise((resolve, reject) => {
if (document.querySelector(`script[src="${src}"]`)) {
resolve();
return;
}
/**
* SDK 스크립트를 로드할 수 있는 호스트 (plugin.json `trusted_script_hosts` 미러).
*
* 나이스페이먼츠 결제창은 라이브러리가 아니라 그 회사 서버와 통신하는 서비스 SDK 라
* 자체 호스팅할 수 없다. 대신 **주입 직전에** 호스트를 확인해, 설정·응답이 어떤
* 경로로든 다른 주소를 지시하면 결제를 진행하지 않는다(fail-closed).
*
* PG사가 SDK 호스트를 바꾸면 이 상수와 plugin.json 을 **함께** 갱신한다 —
* 둘이 어긋나면 테스트가 실패한다.
*/
export const KNOWN_SDK_HOSTS: readonly string[] = ['web.nicepay.co.kr'];
/**
* 번역 문자열을 얻습니다.
*
* @param key 번역 키 (플러그인 네임스페이스 이하)
* @param fallback 번역 엔진 부재 시 사용할 문구
* @returns 번역된 문자열
*/
function t(key: string, fallback: string): string {
const translate = (window as any)?.G7Core?.t;
if (typeof translate !== 'function') {
return fallback;
}
const full = `sirsoft-pay_nicepayments.${key}`;
const result = translate(full);
return typeof result === 'string' && result !== full ? result : fallback;
}
/**
* SDK URL 이 신뢰 호스트인지 확인하고, 아니면 예외를 던집니다.
*
* @param url 주입할 SDK URL
* @throws Error 미신뢰 호스트이거나 https 가 아닌 경우
*/
export function assertTrustedSdkUrl(url: string): void {
let parsed: URL | null = null;
try {
parsed = new URL(url);
} catch {
parsed = null;
}
if (
parsed === null
|| parsed.protocol !== 'https:'
|| !KNOWN_SDK_HOSTS.includes(parsed.hostname.toLowerCase())
) {
throw new Error(
t('payment.error.sdk_url_untrusted', '결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다.')
);
}
}
/**
* SDK 스크립트를 로드합니다.
*
* 완료 판정은 **SDK 전역 확보**로 한다 — DOM 에 태그가 있다는 것은 로드 완료를
* 뜻하지 않는다(로드 중이거나, 실패해 남은 잔재일 수 있다). 종전에는 태그 존재만으로
* 즉시 resolve 해서, 전역이 없는 상태로 다음 단계가 진행되고 결제창이 열리지 않았다.
*
* @param src SDK URL
* @throws Error 미신뢰 호스트이거나 로드에 실패한 경우
*/
async function loadScript(src: string): Promise<void> {
assertTrustedSdkUrl(src);
if (typeof window.goPay === 'function') {
return;
}
// 전역이 없는데 태그만 남아 있으면 미완료·실패 잔재다 — 제거 후 새로 로드한다.
document.querySelectorAll(`script[src="${CSS.escape(src)}"]`).forEach((el) => el.remove());
const loader = (window as any)?.G7Core?.asset?.loadScript;
if (typeof loader === 'function') {
await loader(src, {}, { label: 'nicepayments SDK' });
return;
}
await new Promise<void>((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = () => resolve();
@@ -150,5 +150,10 @@
"amount_mismatch": "Payment amount does not match.",
"authorize_failed": "Payment authorization failed."
}
},
"payment": {
"error": {
"sdk_url_untrusted": "The payment module address is not valid, so the payment cannot proceed. Please contact the administrator."
}
}
}
@@ -150,5 +150,10 @@
"amount_mismatch": "결제 금액이 일치하지 않습니다.",
"authorize_failed": "결제 승인에 실패했습니다."
}
},
"payment": {
"error": {
"sdk_url_untrusted": "결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다. 관리자에게 문의해 주세요."
}
}
}
@@ -127,6 +127,7 @@
- [ ] `order_sheet_mode` 관련 로직을 고칠 때 `RegisterPgProviderListener`(enabled_methods)와 `RegisterTossPaymentMethodsListener`(builtin 결제수단 주입) 양쪽을 함께 갱신 — 한쪽만 고치면 설정과 노출 목록이 어긋난다
- [ ] `ValidateTossSettingsListener`에 새 범위 검증을 추가하면 `core.plugin_settings.before_save` 의 `sync: true`를 유지
- [ ] 레이아웃·컴포넌트·`data_source` 를 건드렸다면 [`docs/editor-spec.md`](docs/editor-spec.md) 를 확인 — 이 확장은 편집기 스펙이 없어도 되는 상태(공용 ID 만 사용)다. 이 확장만 쓰는 `data_source` 를 새로 붙이는 순간 `editor-spec.json` 신설이 필요해진다
- [ ] 토스페이먼츠가 SDK 호스트를 바꾸면 `plugin.json` 의 `trusted_script_hosts`(+`trusted_script_hosts_reason`)와 `resources/js/handlers/requestPayment.ts` 의 `KNOWN_SDK_HOSTS` 를 **함께** 갱신 — 두 목록이 어긋나면 테스트가 실패하며, 코드 상수에 없는 호스트는 주입 직전 확인에서 거부되어 결제가 진행되지 않는다(fail-closed). 변경 후 `php artisan ext:docgen --scope=plugin:sirsoft-tosspayments` 재실행
## 6. 금지 패턴
@@ -151,7 +152,7 @@
| PHPUnit | 13개 | `plugins/_bundled/sirsoft-tosspayments/tests` |
| Vitest | 6개 | `vitest.config.ts` |
| Playwright | 0개 | — |
| 시나리오 매니페스트 | 3개 | `tests/scenarios` |
| 시나리오 매니페스트 | 4개 | `tests/scenarios` |
기저 TestCase: `tests/PluginTestCase.php` — 확장 테스트는 이 클래스를 상속합니다 (`Tests\TestCase` 직접 상속 금지).
@@ -8,6 +8,7 @@
### Security
- 결제창 프로그램을 불러오는 주소가 토스페이먼츠의 주소인지 불러오기 직전에 확인합니다. 확인되지 않는 주소면 결제를 진행하지 않고 안내를 표시합니다. 또한 결제창 프로그램이 실제로 준비되었는지를 기준으로 다음 단계를 진행하도록 바꿔, 프로그램이 아직 준비되지 않았는데 결제창이 열리지 않고 멈추던 상황을 없앴습니다.
- 제3자가 남의 주문번호만 알면 주소 하나로 그 주문을 취소시킬 수 있던 문제를 수정했습니다. 결제 실패 안내 주소는 로그인도 서명 확인도 거치지 않고 주문번호와 실패 사유를 주소에 담아 받는 경로여서, 그 주소를 열기만 해도 해당 주문이 결제 실패로 처리되었습니다. 이제 이 주소는 주문 상태를 바꾸지 않고 결제 화면으로 되돌려 보내기만 합니다. 결제 성립은 종전처럼 서버 승인 확인으로, 결제완료 후 취소는 서명이 확인된 입금·취소 통보로 처리됩니다.
### Added
@@ -75,6 +75,7 @@ flowchart LR
| 그누보드7 코어 | `>=7.0.10` |
| PHP | `^8.2` |
| 의존 모듈 | `sirsoft-ecommerce` `>=1.1.0` |
| 외부 스크립트 호스트 | `js.tosspayments.com` |
<!-- @generated:requirements END -->
## 설치
@@ -1 +1 @@
(function(){"use strict";const q="sirsoft-tosspayments",y="g7:sirsoft-tosspayments:pendingClose",I="/api/plugins/sirsoft-tosspayments/payment/close-report";function f(){try{return window.sessionStorage??null}catch{return null}}function G(e){const t=f();if(t)try{t.setItem(y,JSON.stringify(e))}catch{}}function E(){const e=f();if(e)try{e.removeItem(y)}catch{}}function K(){const e=f();if(!e)return null;try{const t=e.getItem(y);if(!t)return null;const s=JSON.parse(t);return s&&typeof s.orderId=="string"&&s.orderId!==""?s:null}catch{return null}}async function B(e,t,s){const n={orderId:e.orderId,amount:Number(e.amount),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",code:t.slice(0,60),reason:s.trim().slice(0,160)},o=window.G7Core?.api;if(typeof o?.post=="function"){await o.post(I,n);return}await fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n),keepalive:!0})}async function j(){const e=K();if(!e)return;let t;try{t=new URLSearchParams(window.location.search)}catch{return}const s=t.get("orderId")??"";if(s!==""&&s!==e.orderId)return;if(/\/(complete|success)(\/|$|\?)/.test(window.location.pathname)){E();return}const n=t.get("error")??"",o=t.get("message")??"";if(!(n===""&&s==="")){E();try{await B(e,n,o!==""?o:n)}catch(r){console.warn(`[${q}] failed to report payment failure`,r)}}}function H(e){return new Promise((t,s)=>{if(document.querySelector(`script[src="${e}"]`)){t();return}const n=document.createElement("script");n.src=e,n.async=!0,n.onload=()=>t(),n.onerror=()=>s(new Error(`Failed to load script: ${e}`)),document.head.appendChild(n)})}function Y(e,t){if(!e.order_sheet_mode||!t)return{method:"CARD",easyPay:null};const s=(e.enabled_methods??[]).find(n=>n.id===t);return s?{method:s.method,easyPay:s.easy_pay_provider}:{method:"CARD",easyPay:null}}function A(e){if(e==="on")return!0;if(e==="off")return!1}function W(e,t){const s={validHours:e.vbank?.valid_hours??24},n=e.vbank?.cash_receipt_type??"";n&&(s.cashReceipt={type:n});const o=A(e.use_escrow);return o!==void 0&&(s.useEscrow=o),s}function C(e,t,s){if(t.use_escrow==="off")return;const n=s.escrow_products??[];n.length>0&&(e.escrowProducts=n)}async function J(e,t){const s=e.params||{},{pgPaymentData:n}=s;if(!n){console.error("[sirsoft-tosspayments] pgPaymentData is required");return}const o=window.G7Core,r=s.paymentMethod??o?.state?.getLocal?.()?.paymentMethod;try{const a=await o.api.get("/modules/sirsoft-ecommerce/payments/client-config/tosspayments");if(!a.data){console.error("[sirsoft-tosspayments] Failed to fetch client config",a);return}const i=a.data;if(window.TossPayments||await H(i.sdk_url),window.TossPayments||await new Promise(m=>setTimeout(m,100)),!window.TossPayments){console.error("[sirsoft-tosspayments] TossPayments SDK not available");return}const de=window.TossPayments(i.client_key).payment({customerKey:n.customer_key??window.TossPayments.ANONYMOUS}),T=n.currency??"KRW",{method:d,easyPay:S}=Y(i,r);if(T!=="KRW"&&(d!=="CARD"||S!==null)){console.warn("[sirsoft-tosspayments] non-KRW currency supports card only",{currency:T,method:d}),o?.state?.setLocal?.({paymentErrorMessage:o?.t?.("sirsoft-tosspayments.errors.non_krw_method")??"This payment method is available for KRW only.",isSubmittingOrder:!1}),o?.modal?.open?.("tosspayments_payment_error_modal");return}const F=window.location.origin,c={method:d,amount:{currency:T,value:n.amount},orderId:n.order_number,orderName:n.order_name,successUrl:F+i.callback_urls.success,failUrl:F+i.callback_urls.fail,customerEmail:n.customer_email??void 0,customerName:n.customer_name??void 0,customerMobilePhone:n.customer_phone??void 0};if(d==="CARD")c.card={flowMode:"DEFAULT",useCardPoint:!1,useAppCardOnly:!1},S&&(c.card.flowMode="DIRECT",c.card.easyPay=S);else if(d==="VIRTUAL_ACCOUNT")c.virtualAccount=W(i,n),C(c,i,n);else if(d==="TRANSFER"){const m=A(i.use_escrow);m!==void 0&&(c.transfer={useEscrow:m}),C(c,i,n)}G({orderId:n.order_number,amount:n.amount,buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??""}),await de.requestPayment(c)}catch(a){if(console.error("[sirsoft-tosspayments] requestPayment error",a),a?.code==="USER_CANCEL"){console.info("[sirsoft-tosspayments] Payment cancelled by user");try{await o.api.post(`/modules/sirsoft-ecommerce/orders/${n.order_number}/cancel-payment`,{cancel_code:a.code,cancel_message:a.message})}catch(U){console.warn("[sirsoft-tosspayments] Failed to record cancellation",U)}o?.state?.setLocal?.({isSubmittingOrder:!1}),o?.modal?.open?.("tosspayments_payment_cancel_modal");return}const i=a?.message??"Unknown error";o?.state?.setLocal?.({paymentErrorMessage:i,isSubmittingOrder:!1}),o?.modal?.open?.("tosspayments_payment_error_modal")}}const v={requestPayment:J},V="sirsoft-tosspayments",L="__tossAdminPaymentMethodBrandInjectorInstalled",N="__tossAdminPaymentMethodBrandSyncListenerAttached",z=/^\/admin\/ecommerce\/settings\/?$/,R='[data-toss-admin-payment-brand-mark="true"]',Q=200,X=120,Z=[{id:"toss_tosLine truncated
(function(){"use strict";const F="sirsoft-tosspayments",y="g7:sirsoft-tosspayments:pendingClose",C="/api/plugins/sirsoft-tosspayments/payment/close-report";function f(){try{return window.sessionStorage??null}catch{return null}}function G(e){const t=f();if(t)try{t.setItem(y,JSON.stringify(e))}catch{}}function E(){const e=f();if(e)try{e.removeItem(y)}catch{}}function q(){const e=f();if(!e)return null;try{const t=e.getItem(y);if(!t)return null;const s=JSON.parse(t);return s&&typeof s.orderId=="string"&&s.orderId!==""?s:null}catch{return null}}async function j(e,t,s){const n={orderId:e.orderId,amount:Number(e.amount),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",code:t.slice(0,60),reason:s.trim().slice(0,160)},o=window.G7Core?.api;if(typeof o?.post=="function"){await o.post(C,n);return}await fetch(C,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n),keepalive:!0})}async function B(){const e=q();if(!e)return;let t;try{t=new URLSearchParams(window.location.search)}catch{return}const s=t.get("orderId")??"";if(s!==""&&s!==e.orderId)return;if(/\/(complete|success)(\/|$|\?)/.test(window.location.pathname)){E();return}const n=t.get("error")??"",o=t.get("message")??"";if(!(n===""&&s==="")){E();try{await j(e,n,o!==""?o:n)}catch(r){console.warn(`[${F}] failed to report payment failure`,r)}}}const H=["js.tosspayments.com"];function Y(e,t){const s=window?.G7Core?.t;if(typeof s!="function")return t;const n=`sirsoft-tosspayments.${e}`,o=s(n);return typeof o=="string"&&o!==n?o:t}function W(e){let t=null;try{t=new URL(e)}catch{t=null}if(t===null||t.protocol!=="https:"||!H.includes(t.hostname.toLowerCase()))throw new Error(Y("payment.error.sdk_url_untrusted","결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다."))}async function J(e){if(W(e),window.TossPayments)return;document.querySelectorAll(`script[src="${CSS.escape(e)}"]`).forEach(s=>s.remove());const t=window?.G7Core?.asset?.loadScript;if(typeof t=="function"){await t(e,{},{label:"tosspayments SDK"});return}await new Promise((s,n)=>{const o=document.createElement("script");o.src=e,o.async=!0,o.onload=()=>s(),o.onerror=()=>n(new Error(`Failed to load script: ${e}`)),document.head.appendChild(o)})}function V(e,t){if(!e.order_sheet_mode||!t)return{method:"CARD",easyPay:null};const s=(e.enabled_methods??[]).find(n=>n.id===t);return s?{method:s.method,easyPay:s.easy_pay_provider}:{method:"CARD",easyPay:null}}function I(e){if(e==="on")return!0;if(e==="off")return!1}function z(e,t){const s={validHours:e.vbank?.valid_hours??24},n=e.vbank?.cash_receipt_type??"";n&&(s.cashReceipt={type:n});const o=I(e.use_escrow);return o!==void 0&&(s.useEscrow=o),s}function v(e,t,s){if(t.use_escrow==="off")return;const n=s.escrow_products??[];n.length>0&&(e.escrowProducts=n)}async function Q(e,t){const s=e.params||{},{pgPaymentData:n}=s;if(!n){console.error("[sirsoft-tosspayments] pgPaymentData is required");return}const o=window.G7Core,r=s.paymentMethod??o?.state?.getLocal?.()?.paymentMethod;try{const a=await o.api.get("/modules/sirsoft-ecommerce/payments/client-config/tosspayments");if(!a.data){console.error("[sirsoft-tosspayments] Failed to fetch client config",a);return}const i=a.data;if(window.TossPayments||await J(i.sdk_url),window.TossPayments||await new Promise(m=>setTimeout(m,100)),!window.TossPayments){console.error("[sirsoft-tosspayments] TossPayments SDK not available");return}const ye=window.TossPayments(i.client_key).payment({customerKey:n.customer_key??window.TossPayments.ANONYMOUS}),T=n.currency??"KRW",{method:d,easyPay:S}=V(i,r);if(T!=="KRW"&&(d!=="CARD"||S!==null)){console.warn("[sirsoft-tosspayments] non-KRW currency supports card only",{currency:T,method:d}),o?.state?.setLocal?.({paymentErrorMessage:o?.t?.("sirsoft-tosspayments.errors.non_krw_method")??"This payment method is available for KRW only.",isSubmittingOrder:!1}),o?.modal?.open?.("tosspayments_payment_error_modal");return}const K=window.location.origin,c={method:d,amount:{currency:T,value:n.amount},orderId:n.order_number,orderName:n.order_name,successUrl:K+i.callback_urls.success,failUrl:K+i.callback_urls.fail,customerEmail:n.customer_email??void 0,customerName:n.customer_name??void 0,customerMobilePhone:n.customer_phone??void 0};if(d==="CARD")c.card={flowMode:"DEFAULT",useCardPoint:!1,useAppCardOnly:!1},S&&(c.card.flowMode="DIRECT",c.card.easyPay=S);else if(d==="VIRTUAL_ACCOUNT")c.virtualAccount=z(i,n),v(c,i,n);else if(d==="TRANSFER"){const m=I(i.use_escrow);m!==void 0&&(c.transfer={useEscrow:m}),v(c,i,n)}G({orderId:n.order_number,amount:n.amount,buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??""}),await ye.requestPayment(c)}catch(a){if(console.error("[sirsoft-tosspayments] requestPayment error",a),a?.code==="USER_CANCEL"){console.info("[sirsoft-tosspayments] Payment cancelled by user");try{await o.api.post(`/modules/sirsoft-ecommerce/orders/${n.order_number}/cancel-payment`,{cancel_code:a.code,cancel_meLine truncated
@@ -20,6 +20,12 @@
},
"github_url": "https://github.com/gnuboard/g7-plugin-sirsoft-tosspayments",
"github_changelog_url": "https://github.com/gnuboard/g7-plugin-sirsoft-tosspayments/blob/main/CHANGELOG.md",
"trusted_script_hosts": [
"js.tosspayments.com"
],
"trusted_script_hosts_reason": {
"js.tosspayments.com": "토스페이먼츠 결제위젯 SDK 다. 스크립트가 토스페이먼츠 서버와 통신하므로 자체 호스팅해도 결제가 성립하지 않는다."
},
"assets": {
"js": {
"entry": "resources/js/index.ts",
@@ -11,8 +11,10 @@
* escrow_products_absent_when_escrow_off,
* escrow_products_absent_for_card
*/
import { readFileSync } from 'fs';
import { resolve } from 'path';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { requestPaymentHandler } from '../../handlers/requestPayment';
import { assertTrustedSdkUrl, KNOWN_SDK_HOSTS, requestPaymentHandler } from '../../handlers/requestPayment';
const CLIENT_CONFIG_DATA = {
data: {
@@ -419,3 +421,54 @@ describe('requestPaymentHandler', () => {
});
});
});
/**
* SDK 주입 출처 게이트 (동적 스크립트 주입 정책).
*
* PG SDK 는 서비스 SDK 라 자체 호스팅할 수 없다. 그래서 **주입 직전에** 호스트를
* 확인하는 것이 유일한 게이트다. 확장자 없는 SDK URL 은 정적 검사에도 걸리지 않는다.
*
* manifest `trusted_script_hosts` 와 코드 상수가 어긋나면 그 차집합이 그대로
* 사각이 되므로 두 목록의 일치도 함께 고정한다.
*/
describe('SDK URL 신뢰 호스트 게이트', () => {
const TRUSTED_SDK_URL = 'https://js.tosspayments.com/v2/standard';
it('신뢰 호스트 https URL 은 통과한다', () => {
expect(() => assertTrustedSdkUrl(TRUSTED_SDK_URL)).not.toThrow();
});
it.each([
['미신뢰 호스트', 'https://cdn.evil.com/sdk.js'],
['http (평문)', TRUSTED_SDK_URL.replace('https://', 'http://')],
['protocol-relative', TRUSTED_SDK_URL.replace('https://', '//')],
['상대 경로', '/local/sdk.js'],
['빈 문자열', ''],
['javascript 스킴', 'javascript:alert(1)'],
['신뢰 호스트를 userinfo 로 위장', 'https://evil.com/@' + new URL(TRUSTED_SDK_URL).hostname + '/x.js'],
['신뢰 호스트를 서브도메인 접미로 위장', 'https://' + new URL(TRUSTED_SDK_URL).hostname + '.evil.com/x.js'],
])('%s 는 거부된다', (_label, url) => {
expect(() => assertTrustedSdkUrl(url as string)).toThrow();
});
it('manifest trusted_script_hosts 와 KNOWN_SDK_HOSTS 가 일치한다', () => {
const manifest = JSON.parse(
readFileSync(resolve(__dirname, '../../../../plugin.json'), 'utf-8')
);
expect([...(manifest.trusted_script_hosts ?? [])].sort()).toEqual(
[...KNOWN_SDK_HOSTS].sort()
);
});
it('manifest 가 호스트별 사유를 함께 선언한다', () => {
const manifest = JSON.parse(
readFileSync(resolve(__dirname, '../../../../plugin.json'), 'utf-8')
);
for (const host of KNOWN_SDK_HOSTS) {
expect(typeof manifest.trusted_script_hosts_reason?.[host]).toBe('string');
expect(manifest.trusted_script_hosts_reason[host].length).toBeGreaterThan(0);
}
});
});
@@ -78,14 +78,96 @@ declare global {
* @param src 스크립트 URL
* @returns Promise
*/
function loadScript(src: string): Promise<void> {
return new Promise((resolve, reject) => {
// 이미 로드된 스크립트인지 확인
if (document.querySelector(`script[src="${src}"]`)) {
resolve();
return;
}
/**
* SDK 스크립트를 로드할 수 있는 호스트 (plugin.json `trusted_script_hosts` 미러).
*
* 토스페이먼츠 결제위젯은 라이브러리가 아니라 그 회사 서버와 통신하는 서비스 SDK 라
* 자체 호스팅할 수 없다. 대신 **주입 직전에** 호스트를 확인해, 설정·응답이 어떤
* 경로로든 다른 주소를 지시하면 결제를 진행하지 않는다(fail-closed).
*
* PG사가 SDK 호스트를 바꾸면 이 상수와 plugin.json 을 **함께** 갱신한다 —
* 둘이 어긋나면 테스트가 실패한다.
*
* 이 SDK URL(`/v2/standard`)은 확장자가 없어 정적 검사에 걸리지 않는다 —
* 이 런타임 검증이 유일한 게이트다.
*/
export const KNOWN_SDK_HOSTS: readonly string[] = ['js.tosspayments.com'];
/**
* 번역 문자열을 얻습니다.
*
* @param key 번역 키 (플러그인 네임스페이스 이하)
* @param fallback 번역 엔진 부재 시 사용할 문구
* @returns 번역된 문자열
*/
function t(key: string, fallback: string): string {
const translate = (window as any)?.G7Core?.t;
if (typeof translate !== 'function') {
return fallback;
}
const full = `sirsoft-tosspayments.${key}`;
const result = translate(full);
return typeof result === 'string' && result !== full ? result : fallback;
}
/**
* SDK URL 이 신뢰 호스트인지 확인하고, 아니면 예외를 던집니다.
*
* @param url 주입할 SDK URL
* @throws Error 미신뢰 호스트이거나 https 가 아닌 경우
*/
export function assertTrustedSdkUrl(url: string): void {
let parsed: URL | null = null;
try {
parsed = new URL(url);
} catch {
parsed = null;
}
if (
parsed === null
|| parsed.protocol !== 'https:'
|| !KNOWN_SDK_HOSTS.includes(parsed.hostname.toLowerCase())
) {
throw new Error(
t('payment.error.sdk_url_untrusted', '결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다.')
);
}
}
/**
* SDK 스크립트를 로드합니다.
*
* 완료 판정은 **SDK 전역 확보**로 한다 — DOM 에 태그가 있다는 것은 로드 완료를
* 뜻하지 않는다(로드 중이거나, 실패해 남은 잔재일 수 있다). 종전에는 태그 존재만으로
* 즉시 resolve 해서, 전역이 없는 상태로 다음 단계가 진행되고 결제창이 열리지 않았다.
*
* @param src SDK URL
* @throws Error 미신뢰 호스트이거나 로드에 실패한 경우
*/
async function loadScript(src: string): Promise<void> {
assertTrustedSdkUrl(src);
if (window.TossPayments) {
return;
}
// 전역이 없는데 태그만 남아 있으면 미완료·실패 잔재다 — 제거 후 새로 로드한다.
document.querySelectorAll(`script[src="${CSS.escape(src)}"]`).forEach((el) => el.remove());
const loader = (window as any)?.G7Core?.asset?.loadScript;
if (typeof loader === 'function') {
await loader(src, {}, { label: 'tosspayments SDK' });
return;
}
await new Promise<void>((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.async = true;
@@ -90,5 +90,10 @@
"vbank_due_label": "Deposit deadline",
"receipt_label": "Receipt",
"receipt_view": "View receipt"
},
"payment": {
"error": {
"sdk_url_untrusted": "The payment module address is not valid, so the payment cannot proceed. Please contact the administrator."
}
}
}
@@ -90,5 +90,10 @@
"vbank_due_label": "입금 기한",
"receipt_label": "영수증",
"receipt_view": "영수증 보기"
},
"payment": {
"error": {
"sdk_url_untrusted": "결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다. 관리자에게 문의해 주세요."
}
}
}