feat: 上线前安全加固与发布工程化;appmall 由插件迁移为独立应用

安全(P0)
- 发布包签名:新增 scripts/package_keygen.php、scripts/package_verify.php、
  ywxapp\service\PackageVerifier;FrameworkService::apply() 解压前强制验签
  (ywxapp.framework_package_verify,默认开启)
- JWT 收紧:config/jwt.php 移除公开默认密钥,JwtService::assertStrongSecret()
  校验非空 / 长度≥32 / 已知弱值;.env.production.example 键名由 JWT_SECRET_KEY 修正为 JWT_SECRET
- /api/v1/Article:免登录白名单收窄为只读接口,写操作字段白名单 + assertOwner() 越权校验
- 开发者令牌:查找接口不再回显明文、统一失败文案 + 限流
- TemplateInstaller:文件名白名单 + realpath 归一化 + 目录内断言,修复 Zip Slip;补 use ZipArchive
- 后台登录:接入验证码、失败锁定与登录限流(config/ratelimit.php)
- 缓存 / Session 驱动可由 .env 覆盖(CACHE_DRIVER / SESSION_TYPE),集群部署改 redis
- paycenter 支付日志开关改为 PAY_LOG,不再跟随 APP_DEBUG

工程化 / 交付
- 新增 CHANGELOG.md 与 .env.production.example;composer.lock 入库锁定依赖版本
- 插件离线安装 CLI 增加 --uid,后台上传安装透传 uid,付费插件授权校验可通过
- 授权拒绝文案区分「未携带 uid」与「未找到有效授权」,便于排障
- .gitignore 放行 .env.production.example / .env.addon.example / .gitattributes / public/.htaccess

结构
- appmall 由 addon/appmall 迁移为独立应用 app/appmall(市场 / 开发者中心 / 审核 / 分润)
This commit is contained in:
yangwx committed 2026-10-22 00:53:39 +08:00
1 parent 1d49e6f5ee
commit 18101cf11a
636 files changed
+58517 -9519

No files matched your search

File diff suppressed because it is too large. Load diff
+5 -1
View File
@@ -250,7 +250,11 @@ class AddonMake extends Make
}
$this->buildRouteFile($app, $namespace);
$this->buildMenuJson($app);
$appPublicPath = public_path() . 'static' . DIRECTORY_SEPARATOR . ($app ? $app . DIRECTORY_SEPARATOR : '');
// 静态资源统一目录:public/static/addon/<name>/{img,css,js}
// (与 AddonService::initPaths() / package() / uninstall() 保持同一口径,
// 旧脚手架建在 public/static/<name>/,会与安装落地路径分裂,已统一)
$appPublicPath = public_path() . 'static' . DIRECTORY_SEPARATOR . 'addon'
. DIRECTORY_SEPARATOR . ($app ? $app . DIRECTORY_SEPARATOR : '');
if (! is_dir($appPublicPath)) {
mkdir($appPublicPath, 0755, true);
mkdir($appPublicPath . 'img', 0755, true);
+9 -2
View File
@@ -26,7 +26,7 @@ use think\facade\Env;
*
* 用法:
* php think addon:manage <插件名> -a develop
* php think addon:manage <插件名> -a install [--local=<zip>] [--force]
* php think addon:manage <插件名> -a install [--local=<zip>] [--uid=<会员ID>] [--force]
* php think addon:manage [<插件名>] -a reload [--force] [--status]
*
* 说明:
@@ -47,6 +47,9 @@ class AddonManage extends Command
->addOption('action', 'a', Option::VALUE_REQUIRED, '动作: develop|install|reload')
// install
->addOption('local', 'l', Option::VALUE_REQUIRED, '离线 zip 路径(install 离线安装)')
// 离线安装付费插件时的授权校验身份:中心站 Market::valid() 按 uid 查授权,
// CLI 下无会话,必须显式指定,否则 uid=0 会被判「请先购买」。
->addOption('uid', 'u', Option::VALUE_REQUIRED, '授权校验用市场会员 ID(离线装付费插件时需携带,默认 0)')
->addOption('force', 'f', Option::VALUE_NONE, '强制(install 在线强制覆盖 / reload 强制重载)')
// reload
->addOption('status', 's', Option::VALUE_NONE, '查看重载状态(reload)')
@@ -119,10 +122,14 @@ class AddonManage extends Command
return 1;
}
// 离线安装付费插件时,中心站 Market::valid() 按 uid 查授权;
// CLI 没有会话,install_user 恒为 0,必须先从 --uid 取身份再一起透传。
$uid = (int) $input->getOption('uid');
$extend = [
'install_user' => 0,
'install_user' => $uid,
'install_ip' => 'cli',
'install_time' => time(),
'uid' => $uid,
];
try {
+1 -1
View File
@@ -195,7 +195,7 @@ class AppCommand extends Make
} elseif ('__file__' == $path) {
foreach ($file as $fname) {
if (!is_file($appPath . $fname)) {
file_put_contents($appPath . $fname, 'php' == pathinfo($fname, PATHINFO_EXTENSION) ? '<?php' . PHP_EOL : '');
file_put_contents($appPath . $fname, 'php' == pathinfo($fname, PATHINFO_EXTENSION) ? '<?php' . PHP_EOL . 'return [];' : '');
}
}
} else {
+130
View File
@@ -0,0 +1,130 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace ywxapp\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Option;
use think\facade\Db;
use ywxapp\service\FileStorageService;
/**
* 附件孤儿清理
*
* 「孤儿」= 磁盘上存在、但 common_attachment 里没有对应记录的文件:
* 上传成功却落库失败、记录被硬删、手工拷进去的文件都会留下这类残留。
*
* 默认只统计不删除(安全),加 --delete 才真正清理;删除同样走
* FileStorageService::delete(),OSS / FTP 等自定义存储由 FileDelete 事件接管。
*
* 用法:
* php think attachment:clean # 只看不删
* php think attachment:clean --delete # 真删
* php think attachment:clean --days=30 # 只处理 30 天前的文件
*
* @author ywxapp <admin@ywxapp.cn>
*/
class AttachmentCleanCommand extends Command
{
protected function configure()
{
$this->setName('attachment:clean')
->addOption('delete', null, Option::VALUE_NONE, '真正删除孤儿文件(默认只统计)')
->addOption('days', null, Option::VALUE_OPTIONAL, '只处理 N 天前的文件(按修改时间),0=不限')
->addOption('dir', null, Option::VALUE_OPTIONAL, '扫描目录,默认 public/storage')
->setDescription('清理磁盘上没有附件记录的孤儿文件(默认只统计不删除)');
}
protected function execute(Input $input, Output $output)
{
$doDelete = (bool) $input->getOption('delete');
$days = max(0, (int) $input->getOption('days'));
$root = rtrim((string) ($input->getOption('dir') ?: public_path() . 'storage'), '/\\');
if (!is_dir($root)) {
$output->writeln('<error>目录不存在:' . $root . '</error>');
return 1;
}
// 库里所有在用的相对路径
$known = [];
try {
$rows = Db::name('common_attachment')->where('delete_at', 0)->field('path')->select()->toArray();
} catch (\Throwable $e) {
$output->writeln('<error>附件表不可用:' . $e->getMessage() . '</error>');
return 1;
}
foreach ($rows as $r) {
$known[ltrim(str_replace('\\', '/', (string) $r['path']), '/')] = true;
}
$deadline = $days > 0 ? (time() - $days * 86400) : 0;
$orphans = [];
$total = 0;
$size = 0;
$it = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($root, \FilesystemIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST
);
foreach ($it as $file) {
if (! $file->isFile()) {
continue;
}
$total++;
$rel = ltrim(str_replace('\\', '/', substr($file->getPathname(), strlen($root) + 1)), '/');
if (isset($known[$rel])) {
continue;
}
if ($deadline && $file->getMTime() > $deadline) {
continue;
}
$orphans[] = $rel;
$size += $file->getSize();
}
$output->writeln('扫描目录:' . $root);
$output->writeln('磁盘文件:' . $total . ',已登记附件:' . count($known) . ',孤儿:' . count($orphans));
$output->writeln('孤儿占用:' . round($size / 1024 / 1024, 2) . ' MB');
foreach (array_slice($orphans, 0, 20) as $rel) {
$output->writeln(' ' . $rel);
}
if (count($orphans) > 20) {
$output->writeln(' … 另有 ' . (count($orphans) - 20) . ' 个');
}
if (! $doDelete) {
$output->writeln('<comment>未删除(如需清理请加 --delete)</comment>');
return 0;
}
if (empty($orphans)) {
$output->writeln('<info>没有需要清理的孤儿文件</info>');
return 0;
}
$storage = new FileStorageService();
$ok = 0;
foreach ($orphans as $rel) {
try {
if ($storage->delete($rel)) {
$ok++;
}
} catch (\Throwable $e) {
// 单个失败不中断
}
}
$output->writeln('<info>已删除 ' . $ok . ' / ' . count($orphans) . ' 个孤儿文件</info>');
return 0;
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace ywxapp\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Option;
use ywxapp\library\DbBackup;
/**
* 数据库备份命令(纯 PHP 实现,可直接挂到定时任务)
*
* 用法:
* php think db:backup # 备份全部表
* php think db:backup -t member -t member_rule # 只备份指定表
* php think db:backup --part=5242880 --keep=7 # 5MB 分卷,只保留最近 7 份
*
* 还原走后台「数据库备份」页面(有二次确认,比 CLI 更安全)。
*
* @author ywxapp <admin@ywxapp.cn>
*/
class DbBackupCommand extends Command
{
protected function configure()
{
$this->setName('db:backup')
->addOption('table', 't', Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, '表名,可多次传入;不传=全部表')
->addOption('part', null, Option::VALUE_OPTIONAL, '分卷字节数,默认 2097152(2MB)')
->addOption('keep', null, Option::VALUE_OPTIONAL, '保留最近 N 份备份,超出按时间清理旧的')
->setDescription('数据库备份(纯 PHP 实现,可用于定时任务)');
}
protected function execute(Input $input, Output $output)
{
$tables = array_values(array_filter((array) $input->getOption('table')));
$part = (int) ($input->getOption('part') ?: 2097152);
$keep = (int) ($input->getOption('keep') ?: 0);
$bak = new DbBackup(null, $part);
try {
$res = $bak->backup($tables);
} catch (\Throwable $e) {
$output->writeln('<error>备份失败:' . $e->getMessage() . '</error>');
return 1;
}
$output->writeln('<info>备份完成</info>');
$output->writeln(' 备份名:' . $res['name']);
$output->writeln(' 分卷:' . count($res['files']) . '(' . implode(', ', $res['files']) . ')');
$output->writeln(' 表数:' . $res['tables'] . ',行数:' . $res['rows']);
$output->writeln(' 大小:' . round($res['size'] / 1024, 2) . ' KB');
$output->writeln(' 目录:' . $bak->dir() . DIRECTORY_SEPARATOR . $res['name']);
if ($keep > 0) {
$list = $bak->backups();
$drop = array_slice($list, $keep);
foreach ($drop as $item) {
$bak->delete($item['name']);
$output->writeln('<comment> 清理旧备份:' . $item['name'] . '</comment>');
}
}
return 0;
}
}
+128
View File
@@ -0,0 +1,128 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | {%title%}(由 addon:crud 生成,可按需修改)
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace {%namespace%};
use think\facade\Request;
use think\Validate;
use ywxapp\controller\BackendBase;
// 模型与控制器同名,必须用别名导入,否则「类名已占用」编译错误
use {%modelNs%} as {%modelAlias%};
/**
* {%title%}
*
* 权限节点(menu.json 注入后由 php think addon:manage <插件> -a reload 生效):
* 列表 index
* 新增 add
* 编辑 update
* 删除 delete
*/
class {%className%} extends BackendBase
{
/**
* 免登录动作
* @var array
*/
protected $noNeedLogin = [];
/**
* 免鉴权动作
* @var array
*/
protected $noNeedVerify = [];
protected function initialize()
{
parent::initialize();
}
/**
* 列表(AJAX 返回 layui 表格数据)
*/
public function index()
{
if ($this->request->isAjax()) {
$page = (int) $this->request->param('page', 1);
$limit = (int) $this->request->param('limit', 15);
$query = {%modelAlias%}::where('{%pk%}', '>', 0);{%search%}
$data = $query->order('{%pk%}', 'desc')->paginate([
'page' => $page,
'list_rows' => $limit,
]);
// 必须回传 count,否则 layui 表格分页失效
return json(['code' => 0, 'msg' => '', 'count' => $data->total(), 'data' => $data->items()]);
}
return $this->view->fetch('{%viewDir%}/index');
}
/**
* 新增
*/
public function add()
{
return $this->saveRow(0);
}
/**
* 更新
*/
public function update()
{
return $this->saveRow((int) Request::post('id', 0));
}
/**
* 删除(软删除字段存在时为软删除)
*/
public function delete()
{
$id = (int) Request::post('id', 0);
if ($id <= 0) {
return json(['code' => 0, 'msg' => '参数错误']);
}
$row = {%modelAlias%}::find($id);
if (!$row) {
return json(['code' => 0, 'msg' => '记录不存在']);
}
$row->delete();
return json(['code' => 1, 'msg' => '已删除']);
}
/**
* 写入(新增 / 更新共用)
*/
protected function saveRow(int $id)
{
$data = Request::post();
$validate = new Validate([{%rules%}]);
if (!$validate->check($data)) {
return json(['code' => 0, 'msg' => $validate->getError()]);
}
// 字段白名单,避免把非表字段写进 SQL
$allow = [{%allow%}];
try {
if ($id > 0) {
$row = {%modelAlias%}::find($id);
if (!$row) {
return json(['code' => 0, 'msg' => '记录不存在']);
}
$row->allowField($allow)->save($data);
} else {
{%modelAlias%}::create($data, $allow);
}
} catch (\Throwable $e) {
return json(['code' => 0, 'msg' => '保存失败:' . $e->getMessage()]);
}
return json(['code' => 1, 'msg' => '保存成功']);
}
}
+132
View File
@@ -0,0 +1,132 @@
/**
* {%title%} —— 由 addon:crud 生成
*
* 权限:auth.setController('{%perm%}') 与后端权限节点 {%perm%}:add|update|delete 对齐,
* 表格渲染后由 auth.filterDom() 移除无权限按钮。
*/
layui.define(['table', 'layer', 'form', 'laytpl', 'util', 'auth', 'http', 'jquery'], function (exports) {
var table = layui.table,
layer = layui.layer,
form = layui.form,
laytpl = layui.laytpl,
auth = layui.auth,
http = layui.http,
$ = layui.jquery;
// 权限控制器前缀(与 backend_power.name 对齐)
auth.setController('{%perm%}');
// 请求地址只写动作名:http 的 baseURL 为空,URL 由浏览器按「当前页面所在目录」
// 解析,而后台页面本身就是 /.../<控制器>/index.html。写成 <控制器>/index
// 会拼成 /.../<控制器>/<控制器>/index → 404(插件与核心后台都一样)。
var FUNC = {
index: 'index',
add: 'add',
update: 'update',
delete: 'delete'
},
FORM_ID = '{%var%}-form';
/**
* 打开新增 / 编辑弹窗
*/
function openForm(data) {
var html = laytpl($('#dataFormTpl').html()).render(data || {});
layer.open({
type: 1,
title: (data && data.id) ? '编辑' : '新增',
area: ['720px', 'auto'],
content: html,
success: function () {
form.render();
form.on('submit(' + FORM_ID + '-submit)', function (obj) {
var url = obj.field.id ? FUNC.update : FUNC.add;
http.post(url, obj.field).then(function (res) {
if (res && res.code === 1) {
layer.msg(res.msg || '保存成功', {icon: 1});
layer.closeAll('page');
table.reload('dataTable');
} else {
layer.msg((res && res.msg) || '保存失败', {icon: 2});
}
}).catch(function (err) {
layer.msg('请求失败:' + (err && err.message ? err.message : '网络异常'), {icon: 2});
});
return false;
});
}
});
}
var obj = {
render: function () {
table.render({
elem: '#dataTable',
url: FUNC.index,
toolbar: '#toolbar',
defaultToolbar: ['filter', 'print', 'exports'],
method: 'get',
cols: [[
{%cols%},
{title: '操作', width: 130, templet: '#action', fixed: 'right'}
]],
page: true,
limit: 15,
limits: [15, 30, 50, 100],
response: {statusCode: 0},
parseData: function (res) {
return {
code: res.code,
msg: res.msg,
count: res.count,
data: res.data || []
};
},
done: function () {
// 按权限移除无权限按钮(工具条 / 行操作按钮)
var view = $('#dataTable').next('.layui-table-view');
auth.filterDom(view);
auth.filterDom('.layui-btn[data-perm]');
}
});
},
events: function () {
// 顶部工具条
table.on('toolbar(dataTable)', function (o) {
if (o.event === 'add') {
if (!auth.has('{%permPrefix%}add')) { return layer.msg('无权限', {icon: 2}); }
openForm({});
}
});
// 行内操作
table.on('tool(dataTable)', function (o) {
if (o.event === 'edit') {
if (!auth.has('{%permPrefix%}update')) { return layer.msg('无权限', {icon: 2}); }
openForm(o.data);
} else if (o.event === 'delete') {
if (!auth.has('{%permPrefix%}delete')) { return layer.msg('无权限', {icon: 2}); }
layer.confirm('确定删除该记录吗?', {title: '提示'}, function (index) {
http.post(FUNC.delete, {id: o.data.id}).then(function (res) {
if (res && res.code === 1) {
layer.msg(res.msg || '已删除', {icon: 1});
table.reload('dataTable');
} else {
layer.msg((res && res.msg) || '删除失败', {icon: 2});
}
}).catch(function (err) {
layer.msg('请求失败:' + (err && err.message ? err.message : '网络异常'), {icon: 2});
});
layer.close(index);
});
}
});
{%searchEvent%} }
};
obj.render();
obj.events();
exports('{%module%}', obj);
});
+25
View File
@@ -0,0 +1,25 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | 由 addon:crud 生成,可按需修改
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace {%namespace%};
{%use%}use ywxapp\model\BaseModel;
class {%className%} extends BaseModel
{{%traits%}
{%options%}
/**
* 表结构自愈:从 public/install/install.sql 提取本表 CREATE TABLE 执行。
* 建表责任绑定在模型本身,核心库不再按业务域聚合自愈。
*/
public static function ensureSchema(): void
{
self::ensureTableFromInstall(self::currentPrefix(), '{%table%}');
}
}
+41
View File
@@ -0,0 +1,41 @@
<div class="layui-fluid">
<div class="layui-card">
<div class="layui-card-header">{%title%}</div>
<div class="layui-card-body">
{%searchBar%} <table class="layui-hide" id="dataTable" lay-filter="dataTable"></table>
</div>
</div>
</div>
<!-- 表格顶部工具条 -->
<script type="text/html" id="toolbar">
<div class="layui-btn-group">
<button class="layui-btn layui-btn-sm" lay-event="add" data-perm="{%permPrefix%}add">
<i class="layui-icon layui-icon-add-1"></i> 新增
</button>
</div>
</script>
<!-- 行操作按钮 -->
<script type="text/html" id="action">
<div class="layui-btn-group">
<button class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit" data-perm="{%permPrefix%}update">编辑</button>
<button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete" data-perm="{%permPrefix%}delete">删除</button>
</div>
</script>
{%statusTpl%}
<!-- 新增 / 编辑表单模板(弹窗渲染) -->
<script type="text/html" id="dataFormTpl">
<form class="layui-form layui-form-pane" lay-filter="{%var%}-form" id="{%var%}-form" style="padding:15px">
<input type="hidden" name="id" value="{{d.id||''}}">
{%formItems%}
<div class="layui-form-item layui-hide">
<button class="layui-btn" lay-submit lay-filter="{%var%}-form-submit" id="{%var%}-form-submit">提交</button>
</div>
</form>
</script>
<script>
layui.use(['{%module%}'], function () {});
</script>