Add kyc tool library
Some checks failed
Client CMS Check Build (NixCN CMS) TeamCity build failed
Backend Check Build (NixCN CMS) TeamCity build finished

Signed-off-by: Asai Neko <sugar@sne.moe>
This commit is contained in:
2026-01-30 11:27:50 +08:00
parent 88a14bfced
commit 2aa344a11f
7 changed files with 179 additions and 88 deletions

120
internal/kyc/cnrid.go Normal file
View File

@@ -0,0 +1,120 @@
package kyc
import (
"crypto/md5"
"encoding/hex"
"fmt"
"unicode/utf8"
alicloudauth20190307 "github.com/alibabacloud-go/cloudauth-20190307/v4/client"
aliopenapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
aliutil "github.com/alibabacloud-go/tea-utils/v2/service"
alitea "github.com/alibabacloud-go/tea/tea"
alicredential "github.com/aliyun/credentials-go/credentials"
"github.com/spf13/viper"
)
func CNRidMD5AliEnc(kyc *KycInfo) (*AliCloudAuth, error) {
if kyc.Type != "Chinese" {
return nil, nil
}
// MD5 Legal Name rule: First Chinese char md5enc, remaining plain, at least 2 Chinese chars
if len(kyc.CNRidInfo.LegalName) < 2 || utf8.RuneCountInString(kyc.CNRidInfo.LegalName) < 2 {
return nil, fmt.Errorf("input string must have at least 2 Chinese characters")
}
lnFirstRune, size := utf8.DecodeRuneInString(kyc.CNRidInfo.LegalName)
if lnFirstRune == utf8.RuneError {
return nil, fmt.Errorf("invalid first character")
}
lnHash := md5.New()
lnHash.Write([]byte(string(lnFirstRune)))
lnFirstHash := hex.EncodeToString(lnHash.Sum(nil))
lnRemaining := kyc.CNRidInfo.LegalName[size:]
ln := lnFirstHash + lnRemaining
// MD5 Resident Id rule: First 6 char plain, middle birthdate md5enc, last 4 char plain, at least 18 chars
if len(kyc.CNRidInfo.ResidentId) < 18 {
return nil, fmt.Errorf("input string must have at least 18 characters")
}
ridPrefix := kyc.CNRidInfo.ResidentId[:6]
ridSuffix := kyc.CNRidInfo.ResidentId[len(kyc.CNRidInfo.ResidentId)-4:]
ridMiddle := kyc.CNRidInfo.ResidentId[6 : len(kyc.CNRidInfo.ResidentId)-4]
ridHash := md5.New()
ridHash.Write([]byte(ridMiddle))
ridMiddleHash := hex.EncodeToString(ridHash.Sum(nil))
rid := ridPrefix + ridMiddleHash + ridSuffix
// Aliyun Id2MetaVerify API Params
var kycAli AliCloudAuth
kycAli.ParamType = "md5"
kycAli.UserName = ln
kycAli.IdentifyNum = rid
return &kycAli, nil
}
func AliId2MetaVerify(kycAli *AliCloudAuth) (*string, error) {
// Create aliyun openapi credential
credentialConfig := new(alicredential.Config).
SetType("access_key").
SetAccessKeyId(viper.GetString("kyc.ali_access_key_id")).
SetAccessKeySecret(viper.GetString("kyc.ali_access_key_secret"))
credential, err := alicredential.NewCredential(credentialConfig)
if err != nil {
return nil, err
}
// Create aliyun cloudauth client
config := &aliopenapi.Config{
Credential: credential,
}
config.Endpoint = alitea.String("cloudauth.aliyuncs.com")
client := &alicloudauth20190307.Client{}
client, err = alicloudauth20190307.NewClient(config)
if err != nil {
return nil, err
}
// Create Id2MetaVerify request
id2MetaVerifyRequest := &alicloudauth20190307.Id2MetaVerifyRequest{
ParamType: &kycAli.ParamType,
UserName: &kycAli.UserName,
IdentifyNum: &kycAli.IdentifyNum,
}
// Create client runtime request
runtime := &aliutil.RuntimeOptions{}
resp, tryErr := func() (*alicloudauth20190307.Id2MetaVerifyResponse, error) {
defer func() {
if r := alitea.Recover(recover()); r != nil {
err = r
}
}()
resp, err := client.Id2MetaVerifyWithOptions(id2MetaVerifyRequest, runtime)
if err != nil {
return nil, err
}
return resp, nil
}()
// Try error handler ??? from ali generated sdk
if tryErr != nil {
var error = &alitea.SDKError{}
if t, ok := tryErr.(*alitea.SDKError); ok {
error = t
} else {
error.Message = alitea.String(tryErr.Error())
}
return nil, error
}
return resp.Body.ResultObject.BizCode, err
}

39
internal/kyc/crypto.go Normal file
View File

@@ -0,0 +1,39 @@
package kyc
import (
"encoding/json"
"errors"
"nixcn-cms/internal/cryptography"
"github.com/spf13/viper"
)
func EncodeAES(kyc *KycInfo) (*string, error) {
plainJson, err := json.Marshal(kyc)
if err != nil {
return nil, err
}
aesKey := viper.GetString("secrets.kyc_info_key")
encrypted, err := cryptography.AESCBCEncrypt(plainJson, []byte(aesKey))
if err != nil {
return nil, err
}
return &encrypted, nil
}
func DecodeAES(cipherStr string) (*KycInfo, error) {
aesKey := viper.GetString("secrets.kyc_info_key")
plainBytes, err := cryptography.AESCBCDecrypt(cipherStr, []byte(aesKey))
if err != nil {
return nil, err
}
var kycInfo KycInfo
if err := json.Unmarshal(plainBytes, &kycInfo); err != nil {
return nil, errors.New("[KYC] invalid decrypted json")
}
return &kycInfo, nil
}

88
internal/kyc/passport.go Normal file
View File

@@ -0,0 +1,88 @@
package kyc
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/spf13/viper"
)
func CreateSession() (*PassportReaderSessionResponse, error) {
publicKey := viper.GetString("kyc.passport_reader_public_key")
secret := viper.GetString("kyc.passport_reader_secret")
apiURL := "https://passportreader.app/api/v1/session.create"
client := &http.Client{
Timeout: 10 * time.Second,
}
req, err := http.NewRequest("POST", apiURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.SetBasicAuth(publicKey, secret)
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("api returned error: %d, body: %s", resp.StatusCode, string(body))
}
var sessionResp PassportReaderSessionResponse
if err := json.NewDecoder(resp.Body).Decode(&sessionResp); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
return &sessionResp, nil
}
func GetSessionDetails(sessionID int) (*PassportReaderSessionDetailResponse, error) {
publicKey := viper.GetString("kyc.passport_reader_public_key")
secret := viper.GetString("kyc.passport_reader_secret")
apiURL := "https://passportreader.app/api/v1/session.get"
reqPayload := PassportReaderGetSessionRequest{ID: sessionID}
jsonData, err := json.Marshal(reqPayload)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.SetBasicAuth(publicKey, secret)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 15 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("api error: %d, response: %s", resp.StatusCode, string(body))
}
var detailResp PassportReaderSessionDetailResponse
if err := json.NewDecoder(resp.Body).Decode(&detailResp); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
return &detailResp, nil
}

View File

@@ -1,17 +1,48 @@
package kyc
type KycInfo struct {
Type string `json:"type"` // cnrid/passport
LegalName string `json:"legal_name"`
ResidentId string `json:"rsident_id"`
PassportInfo PassportInfo `json:"passport_info"`
Type string `json:"type"` // cnrid/passport
CNRidInfo *CNRidInfo `json:"CNRodInfo"`
PassportInfo *PassportInfo `json:"passport_info"`
}
type CNRidInfo struct {
LegalName string `json:"legal_name"`
ResidentId string `json:"resident_id"`
}
type PassportInfo struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
DateOfExpire string `json:"date_of_expire"`
GivenNames string `json:"given_names"`
Surname string `json:"surname"`
Nationality string `json:"nationality"`
DateOfBirth string `json:"date_of_birth"`
DocumentType string `json:"document_type"`
DocumentNumber string `json:"document_number"`
ExpiryDate string `json:"expiry_date"`
}
type AliCloudAuth struct {
ParamType string `json:"param_type"`
IdentifyNum string `json:"identify_num"`
UserName string `json:"user_name"`
}
type PassportReaderSessionResponse struct {
ID int `json:"id"`
Token string `json:"token"`
}
type PassportReaderGetSessionRequest struct {
ID int `json:"id"`
}
type PassportReaderSessionDetailResponse struct {
State string `json:"state"`
GivenNames string `json:"given_names"`
Surname string `json:"surname"`
Nationality string `json:"nationality"`
DateOfBirth string `json:"date_of_birth"`
DocumentType string `json:"document_type"`
DocumentNumber string `json:"document_number"`
ExpiryDate string `json:"expiry_date"`
}