Mac公证脚本-Web公证方式

2024-02-20 23:28
文章标签 mac web 方式 脚本 公证

本文主要是介绍Mac公证脚本-Web公证方式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

公证方式

Mac 公证方式有三种

公证方法

优点

缺点

阐述

Xcode

Xcode携带的图形界面,使用方便

无法进行自动化公证

单个App应用上架使用较多

altool(旧版)

支持pkg,dmg,脚本自动化

2023/11/01 将会过期

已经是弃用,不建议使用 Mac开发-公证流程记录Notarization-附带脚本_xcrun altool --notarize-app --primary-bundle-id-CSDN博客

notarytool(新版)

支持pkg,dmg,脚本自动化

必须依赖macos环境

必须要依赖macos环境,并且更新Xcode版本和mac版本,有一定的环境限制

Notary API

支持pkg,dmg,脚本自动化

无需依赖macos环境

使用的是苹果官方提供的Web API进行公证,不受运行环境限制

这里 Notary API 有较大的优势,之前 altool 脚本公证的方式我们已经做过,由于 2023/11/01 将被弃用,考虑后续跨平台的需要,使用 notary API 进行脚本自动化公证

https://developer.apple.com/documentation/notaryapi/submitting_software_for_notarization_over_the_web

流程

具体的流程大概如下:

  1. 获取 API密钥 (Private Key)
  2. 使用 API密钥 (Private Key) 生成 JSON Web Token (JWT) , 相当于授权令牌 token
  3. 请求 Notary API 并在 HTTP 请求头中,携带 JWT 内容
  4. 得到请求结果

1. 获取 API密钥

https://developer.apple.com/documentation/appstoreconnectapi/creating_api_keys_for_app_store_connect_api

官方文档阐述

  1. 登录App Store Connect
  2. 选择 [用户和访问] 这栏 ,然后选择API Keys选项卡
  3. 单击生成API密钥或添加(+)按钮。
  4. 输入密钥的名称。
  5. 在Access下,为密钥选择角色
  6. 点击生成
  7. 点击下载秘钥 (注意下载后苹果不再保存,你只能下载一次)

根据上述流程获取你的 API 秘钥

2. 生成令牌 Token

https://developer.apple.com/documentation/appstoreconnectapi/generating_tokens_for_api_requests

2.1. 环境安装
  1. 根据 https://jwt.io/libraries 所述,安装 pyjwt 库
  2. 由于本地环境 python3, 使用 pip3 install pyjwt 安装, 并参考官网使用说明 https://pyjwt.readthedocs.io/en/stable/usage.html#encoding-decoding-tokens-with-hs256
  3. pyjwt 依赖 cryptography 库,需要额外安装 pip3 install cryptography
  4. 文件上传依赖 boto3 库,pip3 install boto3

2.2. JWT Encode/Decode

参考 https://developer.apple.com/documentation/appstoreconnectapi/generating_tokens_for_api_requests 所述进行设置,值得注意的是,苹果会拒绝大多数设置过期时间为 20 分钟以上的 JWT 票据,所以我们需要间隔生成 JWT

  1. header
{"alg": "ES256","kid": "2X9R4HXF34","typ": "JWT"
}
  1. body
{"iss": "57246542-96fe-1a63-e053-0824d011072a","iat": 1528407600,"exp": 1528408800,"aud": "appstoreconnect-v1","scope": ["GET /notary/v2/submissions","POST /notary/v2/submissions",]
}
  1. API 秘钥

对应的生成逻辑如下

def get_jwt_token():# 读取私钥文件内容with open('./AuthKey_xxxxx.p8', 'rb') as f:jwt_secret_key = f.read()# 获取当前时间now = datetime.datetime.now()# 计算过期时间(当前时间往后 20 分钟)expires = now + datetime.timedelta(minutes=20)# 设置 JWT 的 headerjwt_header = {"alg": "ES256","kid": "2X9R4HXF34","typ": "JWT"}# 检查文件是否存在if os.path.exists("./jwt_token"):# 读取with open('./jwt_token', 'rb') as f:jwt_pre_token = f.read()print('[info]','jwt token %s' % (jwt_pre_token))try:decoded = jwt.decode(jwt_pre_token,jwt_secret_key,algorithms="ES256",audience="appstoreconnect-v1")except Exception as e:print('[error]', 'decode exception %s' % (e))else:exp = datetime.datetime.fromtimestamp(decoded["exp"])if exp - datetime.timedelta(seconds=60) < now:print("jwt token 已过期,重新生成")else:print("jwt token 有效,使用之前token")return jwt_pre_token# 设置 JWT 的 payloadjwt_payload = {"iss": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx","iat": int(now.timestamp()),"exp": int(expires.timestamp()),"aud": "appstoreconnect-v1","scope": ["GET /notary/v2/submissions","POST /notary/v2/submissions",]}print('[info]', 'jwt_header %s' % (jwt_header), 'jwt_payload %s' % jwt_payload)token = jwt.encode(jwt_payload,jwt_secret_key,algorithm="ES256",headers=jwt_header,)# 打开文件,如果文件不存在则创建文件with open("./jwt_token", "w") as f:# 将 token 写入文件f.write(token)print('[info]', 'jwt token is %s' % (token))return token

3. 公证上传

公证处理的流程如下

  1. POST https://appstoreconnect.apple.com/notary/v2/submissions 请求submission s3 上传凭证
  2. 使用 boto3 框架根据获取的凭证信息,查询一次公证状态,如果非 Accepted 状态,进行上传文件。(阻塞式)
file_md5=None
def post_submissison(filepath): global file_md5body = get_body(filepath)token = get_jwt_token()file_md5 = get_md5(filepath)# 指定文件夹路径folder_path = './output'# 缓存路径cache_path = f"{folder_path}/{file_md5}"# 检查文件夹是否存在if not os.path.exists(folder_path):# 如果文件夹不存在,则创建文件夹os.makedirs(folder_path)else:# 如果文件夹已经存在,则进行相应的处理print("[info]", '%s 已经存在' % folder_path)# 检查文件是否存在if os.path.exists(cache_path):# 读取with open(cache_path, 'rb') as f:string = f.read().decode()output = json.loads(string)print('[info]', '使用上次 submission s3 上传凭证 = %s' % (output))else:resp = requests.post("https://appstoreconnect.apple.com/notary/v2/submissions", json=body, headers={"Authorization": "Bearer " + token})resp.raise_for_status()output = resp.json()print('[info]', '获取 submission s3上传凭证 = %s' % (output))# 打开文件,如果文件不存在则创建文件with open(cache_path, "w") as f:# 将 resp 写入文件f.write(resp.content.decode())# 读取 output 中的内容aws_info = output["data"]["attributes"]bucket = aws_info["bucket"]key = aws_info["object"]# sub_id = output["data"]["id"]# 如果已经完成了公证state = get_submission_state(filepath, True)if state == True:print('[info]', 'file %s alreay finished notarization' % (filepath))staple_pkg(filepath)exit(0)s3 = boto3.client("s3",aws_access_key_id=aws_info["awsAccessKeyId"],aws_secret_access_key=aws_info["awsSecretAccessKey"],aws_session_token=aws_info["awsSessionToken"],config=Config(s3={"use_accelerate_endpoint": True}))print('[info]', 'start upload files ...... please wait 2-15 mins')# 上传文件s3.upload_file(filepath, bucket, key)print('[info]', 'upload file complete ...')
  1. 查询公证状态,Accepted 、In Progress、Invalid 目前探测到这三种状态
def get_submission_state(filepath, once=False):print('[info]', 'get_submission_state %s %s ' % (filepath, once))global file_md5if not file_md5:file_md5 = get_md5(filepath)# 指定文件夹路径folder_path = './output'# 缓存路径cache_path = f"{folder_path}/{file_md5}"# 检查文件是否存在if os.path.exists(cache_path):# 获取文件大小file_size = os.path.getsize(cache_path)if file_size == 0:# 文件内容为空print('[info]', ' %s 内容为空,未获取到submission信息' % (filepath))return Falseelse:# 读取缓存内容with open(cache_path, 'rb') as f:string = f.read().decode()output = json.loads(string)else:return Falsesub_id = output["data"]["id"]url = f"https://appstoreconnect.apple.com/notary/v2/submissions/{sub_id}"ret = Falsewhile True:try:# 获取submissiontoken = get_jwt_token()resp = requests.get(url, headers={"Authorization": "Bearer " + token})resp.raise_for_status()except Exception as e:# 异常处理print("[Error]", ' %s get status failed, code = %s ' % filepath % resp.status_code)return Falseelse:# 200 正常返回处理# 检查 statusresp_json = resp.json()print('[info]', 'GET %s resp is %s , header is %s' % (url,resp_json,resp.headers))status = resp_json["data"]["attributes"]["status"]if status == "Accepted":print("[info]", ' %s notarization succesfull' % filepath)ret = Truebreakif status == "Invalid":print("[info]", ' %s notarization failed' % filepath)ret = Falsebreakif once == False:# 暂停 30 秒time.sleep(30)else:print("[info]", 'get_submission_state run once')breakif once == False:print_submission_logs(sub_id)return ret
  1. 获取日志内容
def print_submission_logs(identifier):try:url = f"https://appstoreconnect.apple.com/notary/v2/submissions/{identifier}/logs"token = get_jwt_token()resp = requests.get(url, headers={"Authorization": "Bearer " + token})resp.raise_for_status()except Exception as e:print("[Error]", '/notary/v2/submissions/%s/logs failed, code = %s ' % (identifier, resp.status_code))else:resp_json = resp.json()print('[info]', 'notarization %s logs is %s' % (identifier, resp_json))
  1. 如果 步骤3 查询到结果为 Accepted,则使用 stapler 工具打上票据,进行分发
def staple_pkg(filepath):global file_md5if not file_md5:file_md5 = get_md5(filepath)# 完成公证subprocess.run(["xcrun", "stapler", "staple", filepath])now = datetime.datetime.now()# 验证公证结果temp_output_file = f"./temp_file_{file_md5}"with open(temp_output_file, "w") as f:subprocess.run(["xcrun", "stapler", "validate", filepath], stdout=f, stderr=subprocess.STDOUT)# 读取验证结果with open(temp_output_file, "r") as f:validate_result = f.read()os.remove(temp_output_file)# 检查验证结果if "The validate action worked!" not in validate_result:print('[error]',"\033[31m[error] stapler validate invalid, may be notarization failed!\033[0m")return Falseelse:print('[info]','staple_pkg succesfull')return True

4. 脚本使用方式

脚本文件  https://github.com/CaicaiNo/Apple-Mac-Notarized-script/blob/master/notarize-web/notarize.py

在执行下列步骤前,请先阅读 Generating Tokens for API Requests | Apple Developer Documentation

  1. 替换你的秘钥文件 (例如 AuthKey_2X9R4HXF34.p8)
private_key = f"./../../res/AuthKey_2X9R4HXF34.p8"
  1. 设置你的 kid
 # 设置 JWT 的 headerjwt_header = {"alg": "ES256","kid": "2X9R4HXF34","typ": "JWT"}
  1. 设置你的 iss
# 设置 JWT 的 payloadjwt_payload = {"iss": "57246542-96fe-1a63-e053-0824d011072a","iat": int(now.timestamp()),"exp": int(expires.timestamp()),"aud": "appstoreconnect-v1","scope": ["GET /notary/v2/submissions","POST /notary/v2/submissions",]}
  1. 调用脚本
python3 -u ./notarize.py --pkg "./Output/${PACKAGE_NAME}_$TIME_INDEX.pkg" --private-key "./../../res/AuthKey_2X9R4HXF34.p8"if [ $? -eq 0 ]; thenecho "./Output/aTrustInstaller_$TIME_INDEX.pkg notarization successful"// 公证成功
else// 公证失败echo "./Output/aTrustInstaller_$TIME_INDEX.pkg notarization failed"exit 1
fi

这篇关于Mac公证脚本-Web公证方式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/729875

相关文章

Debezium 与 Apache Kafka 的集成方式步骤详解

《Debezium与ApacheKafka的集成方式步骤详解》本文详细介绍了如何将Debezium与ApacheKafka集成,包括集成概述、步骤、注意事项等,通过KafkaConnect,D... 目录一、集成概述二、集成步骤1. 准备 Kafka 环境2. 配置 Kafka Connect3. 安装 D

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

SQL 中多表查询的常见连接方式详解

《SQL中多表查询的常见连接方式详解》本文介绍SQL中多表查询的常见连接方式,包括内连接(INNERJOIN)、左连接(LEFTJOIN)、右连接(RIGHTJOIN)、全外连接(FULLOUTER... 目录一、连接类型图表(ASCII 形式)二、前置代码(创建示例表)三、连接方式代码示例1. 内连接(I

Android里面的Service种类以及启动方式

《Android里面的Service种类以及启动方式》Android中的Service分为前台服务和后台服务,前台服务需要亮身份牌并显示通知,后台服务则有启动方式选择,包括startService和b... 目录一句话总结:一、Service 的两种类型:1. 前台服务(必须亮身份牌)2. 后台服务(偷偷干

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动

解决JavaWeb-file.isDirectory()遇到的坑问题

《解决JavaWeb-file.isDirectory()遇到的坑问题》JavaWeb开发中,使用`file.isDirectory()`判断路径是否为文件夹时,需要特别注意:该方法只能判断已存在的文... 目录Jahttp://www.chinasem.cnvaWeb-file.isDirectory()遇

JS 实现复制到剪贴板的几种方式小结

《JS实现复制到剪贴板的几种方式小结》本文主要介绍了JS实现复制到剪贴板的几种方式小结,包括ClipboardAPI和document.execCommand这两种方法,具有一定的参考价值,感兴趣的... 目录一、Clipboard API相关属性方法二、document.execCommand优点:缺点:

Python创建Excel的4种方式小结

《Python创建Excel的4种方式小结》这篇文章主要为大家详细介绍了Python中创建Excel的4种常见方式,文中的示例代码简洁易懂,具有一定的参考价值,感兴趣的小伙伴可以学习一下... 目录库的安装代码1——pandas代码2——openpyxl代码3——xlsxwriterwww.cppcns.c

Deepseek使用指南与提问优化策略方式

《Deepseek使用指南与提问优化策略方式》本文介绍了DeepSeek语义搜索引擎的核心功能、集成方法及优化提问策略,通过自然语言处理和机器学习提供精准搜索结果,适用于智能客服、知识库检索等领域... 目录序言1. DeepSeek 概述2. DeepSeek 的集成与使用2.1 DeepSeek API