Ë
    ™•Új,  ã                   ó¤  — U d Z ddlZddlZddlZddlmZ ddlmZmZ ddl	m
Z
 ddlmZmZ ddlmZ ddlmZ  ej$                  d	«      Zd
dddœZeeeeedf   ef   f   ed<    G d„ de«      Zd$d„Zdefd„Zdedefd„Zdedee   fd„Zdedefd„Zdefd„Z defd„Z!defd„Z"dedefd„Z#defd„Z$dededefd„Z%d ed!ede&e   fd"„Z'defd#„Z(y)%uØ  
payment_keys_service.py â€” the Stripe keys, editable from Settings â†’ Sales by the Admin (client brief 2026-10-21,
sheet 2: "change the keys without going through the developer").

Rules from the brief, all enforced here and in admin.py:
  * encrypted in the database (Fernet, key = SECRETS_KEY or derived from ADMIN_JWT_SECRET), never returned in clear:
    the interface only gets `masked` ("â€¢â€¢â€¢â€¢3f2a", the last 4 characters) and `set`;
  * changed by typing the key again (an empty value in a PUT means "keep");
  * visible and editable by the Admin role only (admin.py), every change goes to the Journal;
  * a key saved here wins over the .env one. The .env stays the fallback, so an install that never opens this
    screen behaves exactly as before.
The publishable key is public by nature (the browser needs it to show the card form): `portal_public_key()` hands it
to the gallery, which used to need it baked into the frontend build (VITE_STRIPE_PUBLISHABLE_KEY).
é    N)ÚOptional)ÚFernetÚInvalidToken)Úconfig)ÚTABLE_OPTIONSÚget_db)Ú
jwt_secret)Ú
utcnow_isozmeeconic.payment_keys))Úpk_test_Úpk_live_ÚSTRIPE_PUBLISHABLE_KEY))Úsk_test_Úsk_live_Úrk_test_Úrk_live_ÚSTRIPE_SECRET_KEY))Úwhsec_ÚSTRIPE_WEBHOOK_SECRET)Ústripe_public_keyÚstripe_secret_keyÚstripe_webhook_secret.ÚKEYSc                   ó   — e Zd Zy)Ú	KeyError_N)Ú__name__Ú
__module__Ú__qualname__© ó    ú8/var/www/photos/backend/services/payment_keys_service.pyr   r   %   s   „ Ør   r   Úreturnc                  ó’   — t        «       5 } | j                  dt        › �«       | j                  «        d d d «       y # 1 sw Y   y xY w)Nzò
        CREATE TABLE IF NOT EXISTS app_secrets (
            name       VARCHAR(64) NOT NULL PRIMARY KEY,
            value_enc  MEDIUMTEXT  NOT NULL,
            updated_at VARCHAR(40) NOT NULL,
            updated_by VARCHAR(40)
        ) )r   Úexecuter   Úcommit)Úconns    r    Ú
init_tabler&   )   sF   € Ü	‹ð �TØ�‰ð ô ˆ/ðô 	ð 	�‰Œ÷÷ ñ ús	   ‹)=½Ac                  óÚ   — t         j                  xs
 t        «       } t        t	        j
                  t        j                  d| z   j                  «       «      j                  «       «      «      S )Nzsecrets:)
r   ÚSECRETS_KEYr	   r   Úbase64Úurlsafe_b64encodeÚhashlibÚsha256ÚencodeÚdigest)Úseeds    r    Ú_fernetr0   5   sJ   € Ü×ÑÒ-¤£€DÜ”&×*Ñ*¬7¯>©>¸:ÈÑ;L×:TÑ:TÓ:VÓ+W×+^Ñ+^Ó+`ÓaÓbÐbr   Únamec                 óv   — | dk(  rt         j                  S | dk(  rt         j                  S t         j                  S )Nr   r   )r   r   r   r   ©r1   s    r    Ú
_env_valuer4   :   s8   € àÐ"Ò"Ü×'Ñ'Ð'ØÐ&Ò&Ü×+Ñ+Ð+Ü×(Ñ(Ð(r   c                 ód  — 	 t        «       5 }|j                  d| f«      j                  «       }d d d «       sy 	 t	        «       j                  |d   j                  «       «      j                  «       S # 1 sw Y   ŒExY w# t        $ r Y y w xY w# t        $ r t        j                  d| «       Y y w xY w)Nz.SELECT value_enc FROM app_secrets WHERE name=?Ú	value_encuH   Stored key %s cannot be decrypted â€” re-enter it in Settings â†’ Sales.)r   r#   ÚfetchoneÚ	Exceptionr0   Údecryptr-   Údecoder   ÚlogÚerror)r1   r%   Úrows      r    Ú_storedr>   C   s°   € ðÜ‹Xð 	e˜Ø—,‘,ÐOÐRVÐQXÓY×bÑbÓdˆC÷	eñ ØðÜ‹y× Ñ   [Ñ!1×!8Ñ!8Ó!:Ó;×BÑBÓDÐD÷	eð 	eûäò Ùðûô ò ä�	‰	Ð\Ð^bÔcÙðús8   ‚
A> Œ"A2®A> º7B Á2A;Á7A> Á>	B
Â	B
ÂB/Â.B/c                 ó:   — t        | «      xs t        | «      xs dS )zKThe key in use: the one saved in the interface, else the .env one, else ''.Ú )r>   r4   r3   s    r    ÚgetrA   S   s   € ä�4‹=Ò2œJ tÓ,Ò2°Ð2r   c                  ó   — t        d«      S )Nr   ©rA   r   r   r    Ústripe_secretrD   X   ó   € ÜÐ"Ó#Ð#r   c                  ó   — t        d«      S )Nr   rC   r   r   r    r   r   \   s   € ÜÐ&Ó'Ð'r   c                  ó   — t        d«      S )Nr   rC   r   r   r    Úportal_public_keyrH   `   rE   r   Úvaluec                 ó2   — t        | «      dk\  rd| dd  z   S dS )Né   u   â€¢â€¢â€¢â€¢éüÿÿÿ)Úlen)rI   s    r    Ú_maskrN   d   s"   € Ü*-¨e«*¸ª/ˆ>˜E " #˜JÑ&ÐM¸~ÐMr   c                  ó¢   — i } t         D ]C  }t        |«      }|xs t        |«      }t        |«      |rt	        |«      nd|rdn|rdnddœ| |<   ŒE | S )zkWhat the interface may know: whether each key is set, where from, and its last 4 characters. Never the key.r@   Ú	interfaceÚenv)ÚsetÚmaskedÚsource)r   r>   r4   ÚboolrN   )Úoutr1   ÚstoredrI   s       r    ÚstatusrX   h   s_   € à€CÜò TˆÜ˜“ˆØÒ*œ* TÓ*ˆÜ  ›KÁ5´5¸´<ÈbÙ.4™{ÁE¹5ÈrñTˆˆDŠ	ðTð
 €Jr   c                 ó  — dj                  |xs dj                  «       «      }t        |    d   }|j                  |«      s t	        | › ddj                  |«      › d�«      ‚t        |«      dk  st        |«      dkD  rt	        | › d�«      ‚|S )	Nr@   r   z: must start with z or ú.é   i�  z): that does not look like a complete key.)ÚjoinÚsplitr   Ú
startswithr   rM   )r1   rI   Úprefixess      r    Ú_checkr`   s   s‰   € Ø�G‰G�U’[˜b×'Ñ'Ó)Ó*€EÜ�D‰z˜!‰}€HØ×Ñ˜HÔ%Ü˜4˜&Ð 2°6·;±;¸xÓ3HÐ2IÈÐKÓLÐLÜ
ˆ5ƒz�B‚œ#˜e›* sÒ*Ü˜4˜&Ð IÐJÓKÐKØ€Lr   ÚvaluesÚbyc           
      ó  — i }| j                  «       D ]O  \  }}|t        vrt        d|› �«      ‚|�t        |«      j	                  «       sŒ8t        |t        |«      «      ||<   ŒQ |j                  d«      xs d}|j                  d«      xs d}|xs
 t        «       |xs
 t        «       }}|r|rd|v d|v k7  rt        d«      ‚|r›t        «       t        «       }
}	t        «       5 }|j                  «       D ]F  \  }}|j                  d||	j                  |j                  «       «      j                  «       |
|f«       ŒH |j!                  «        ddd«       t#        |«      S t#        |«      S # 1 sw Y   t#        |«      S xY w)zcSave the keys that were typed (non-empty). Returns their names. Nothing is saved if one is invalid.zUnknown key: Nr   r   Ú_live_zKThe public key and the secret key are not from the same mode (test / live).z]INSERT OR REPLACE INTO app_secrets (name, value_enc, updated_at, updated_by) VALUES (?,?,?,?))Úitemsr   r   ÚstrÚstripr`   rA   rD   rH   r0   r
   r   r#   Úencryptr-   r:   r$   Úlist)ra   rb   Úcleanr1   ÚrawÚsecretÚpublicÚskÚpkÚfÚnowr%   rI   s                r    Úsaverr   }   sh  € à€EØ—\‘\“^ò -‰	ˆˆcØ”tÑÜ˜m¨D¨6Ð2Ó3Ð3Øˆ;œc #›hŸn™nÔ.ØÜ˜T¤3 s£8Ó,ˆˆdŠð-ð �Y‰YÐ*Ó+Ò3¨t€FØ�Y‰YÐ*Ó+Ò3¨t€FàÒ&”}“¨Ò(EÔ2CÓ2Eˆ€BÙ	‰b�x 2�~¨8°r¨>Ò:ÜÐeÓfÐfÙÜ“œJ›Lˆ3ˆÜ‹Xð 	˜Ø$Ÿ{™{›}ò R‘��eØ—‘Ð|Ø" A§I¡I¨e¯l©l«nÓ$=×$DÑ$DÓ$FÈÈRÐPõRðRð �K‰KŒM÷		ô
 �‹;ÐŒ4�‹;Ð÷	ô
 �‹;Ðús   Ã#A*E+Å+E>c                  óz  — ddl } t        «       }|sdddœS 	 | j                  j                  |¬«       t        «       }d
d|v rdndt        |«      t        t        «       «      dœS # | j                  $ r dddœcY S t
        $ r8}t        j                  dt        |«      j                  «       dd	dœcY d}~S d}~ww xY w)z]Ask Stripe who we are with the key in use. `ok` False carries a message that is safe to show.r   NFzNo secret key.)ÚokÚmessage)Úapi_keyzStripe refused this secret key.z!Stripe connection test failed: %szStripe could not be reached.Trd   ÚliveÚtest)rt   ÚmodeÚpublic_key_setÚwebhook_set)ÚstriperD   ÚBalanceÚretrieveÚAuthenticationErrorr8   r;   ÚwarningÚtyper   rH   rU   r   )r|   rn   Úexcro   s       r    Útest_connectionrƒ   –   sÀ   € ãÜ	‹€BÙØÐ(8Ñ9Ð9ðHØ�‰×Ñ¨ÐÔ+ô 
Ó	€BØ¨(°b©.¡¸fÔX\Ð]_ÓX`ÜÔ 5Ó 7Ó8ñ:ð :øð ×%Ñ%ò KØÐ(IÑJÒJÜò HÜ�‰Ð7¼¸c»×9KÑ9KÔLØÐ(FÑGÕGûðHús#   —A$ Á$B:Á:B:Â-B5Â/B:Â5B:)r!   N))Ú__doc__r)   r+   ÚloggingÚtypingr   Úcryptography.fernetr   r   Úcorer   Úcore.dbr   r   Úcore.securityr	   Úcore.timeutilr
   Ú	getLoggerr;   r   Údictrf   ÚtupleÚ__annotations__Ú
ValueErrorr   r&   r0   r4   r>   rA   rD   r   rH   rN   rX   r`   ri   rr   rƒ   r   r   r    ú<module>r‘      sV  ðòó Û Û Ý ç 4å ß )Ý $Ý $à€g×ÑÐ/Ó0€ð RØdØCñ0€€dˆ3��e˜C ˜H‘o sÐ*Ñ+Ð+Ñ,ó ô	�
ô 	ó	ðc�ó cð
)�Sð )˜Só )ð�#ð ˜( 3™-ó ð 3ˆcð 3�có 3ð
$�só $ð(˜só (ð$˜3ó $ðN�ð N˜ó Nð�ó ð�ð ˜Sð  Só ð�ð ˜3ð  4¨¡9ó ð2:˜ô :r   