AgentGrantService.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Models\AiModel;
  4. use Firebase\JWT\JWT;
  5. use Firebase\JWT\Key;
  6. use Illuminate\Auth\Access\AuthorizationException;
  7. use Illuminate\Validation\ValidationException;
  8. /**
  9. * agent 协作:人类授权 AI 模型代自己写入(`/v3/agent-grants`),以及写入时认出「谁授权、谁代写」。
  10. *
  11. * 流程(仿 git 的 Co-Authored-By,记录见根目录 CLAUDE.md「agent 协作」):
  12. * 1. 人类用自己的登录 token 为「自己名下的某个模型 + 某个 channel(可限 book)」签一张授权;
  13. * 2. 模型用自己的模型 token 登录,写入时在 `X-Agent-Grant` 头里带上这张授权;
  14. * 3. 服务端记 editor = 授权人(对内容负责)、co_editor = 模型,权限按授权人判,
  15. * 并且只在授权覆盖的 channel / book 内有效。
  16. *
  17. * 与 v2 `POST /v2/access-token` 的区别:
  18. * - 授权人、模型、范围全由服务端写进 token,不收客户端拼的载荷;
  19. * - 绑定具体模型(act),换个身份拿去用无效;
  20. * - 带模型的 token_version(ver):撤销模型 token 时,它的授权一并失效;
  21. * - 用独立的签名密钥,v2 签出的 access token 在这里一律无效(v2 的载荷由客户端决定,
  22. * 可以伪造任何声明)。
  23. */
  24. class AgentGrantService
  25. {
  26. /** 授权有效期:一次批量写入作业足够,又把泄漏窗口限制住(与 v2 access token 相同) */
  27. public const TTL = 60 * 60 * 24 * 7;
  28. /** 写入请求里携带授权的请求头 */
  29. public const HEADER = 'X-Agent-Grant';
  30. private const TYPE = 'agent-grant';
  31. public function __construct(private readonly ChannelAbilityService $channels) {}
  32. /**
  33. * 人类为自己名下的模型签发 channel 写入授权。
  34. *
  35. * @param array{ai_model: string, target_type: string, target_id: string, book?: int} $data
  36. * @return array{token: string, grantor: string, ai_model: string, target_type: string, target_id: string, book: int, expires_at: string}
  37. */
  38. public function issue(string $userUid, array $data): array
  39. {
  40. if ($this->isModel($userUid)) {
  41. // 授权必须出自人类:模型不能给自己(或别的模型)签授权
  42. throw new AuthorizationException(__('messages.agent_grant_by_model'));
  43. }
  44. $model = AiModel::where('uid', $data['ai_model'])->first(['uid', 'owner_id', 'token_version']);
  45. if (! $model) {
  46. throw ValidationException::withMessages(['ai_model' => __('messages.agent_grant_model_not_found')]);
  47. }
  48. // 与 v2 取模型 token 同一口径(AiModelController::canEdit):模型归属于当前用户
  49. if ($model->owner_id !== $userUid) {
  50. throw new AuthorizationException(__('messages.agent_grant_not_owner'));
  51. }
  52. // 认团队角色:团队 editor 及以上可以为团队名下的 channel 签授权
  53. if (! $this->channels->canWrite($data['target_id'], $userUid)) {
  54. throw new AuthorizationException(__('messages.agent_grant_no_power'));
  55. }
  56. $book = (int) ($data['book'] ?? 0);
  57. $expiresAt = time() + self::TTL;
  58. $token = JWT::encode([
  59. 'typ' => self::TYPE,
  60. 'grantor' => $userUid,
  61. 'act' => $model->uid,
  62. 'ver' => (int) $model->token_version,
  63. 'res_type' => $data['target_type'],
  64. 'res_id' => $data['target_id'],
  65. 'book' => $book,
  66. 'nbf' => time(),
  67. 'exp' => $expiresAt,
  68. ], $this->key(), 'HS512');
  69. return [
  70. 'token' => $token,
  71. 'grantor' => $userUid,
  72. 'ai_model' => $model->uid,
  73. 'target_type' => $data['target_type'],
  74. 'target_id' => $data['target_id'],
  75. 'book' => $book,
  76. 'expires_at' => gmdate('Y-m-d\TH:i:s\Z', $expiresAt),
  77. ];
  78. }
  79. /**
  80. * 写入请求的署名:人类直接写 → editor 是自己;模型代写 → editor 是授权人、co_editor 是模型。
  81. *
  82. * 模型没带授权一律 403:v3 的写入必须有一个对内容负责的人。人类带了授权 422(授权只给模型用)。
  83. *
  84. * @return array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null}
  85. */
  86. public function actor(string $userUid, ?string $grant): array
  87. {
  88. $isModel = $this->isModel($userUid);
  89. if (! $isModel) {
  90. if ($grant !== null && $grant !== '') {
  91. throw ValidationException::withMessages([self::HEADER => __('messages.agent_grant_human')]);
  92. }
  93. return ['editor' => $userUid, 'co_editor' => null, 'scope' => null];
  94. }
  95. if ($grant === null || $grant === '') {
  96. throw new AuthorizationException(__('messages.agent_grant_required'));
  97. }
  98. try {
  99. $claims = JWT::decode($grant, new Key($this->key(), 'HS512'));
  100. } catch (\Throwable) {
  101. // 伪造、过期、未生效、密钥不对,一律当作没有授权
  102. throw new AuthorizationException(__('messages.agent_grant_invalid'));
  103. }
  104. $version = AiModel::where('uid', $userUid)->value('token_version');
  105. if (($claims->typ ?? null) !== self::TYPE
  106. || ($claims->act ?? null) !== $userUid
  107. || (int) ($claims->ver ?? -1) !== (int) $version
  108. || ($claims->res_type ?? null) !== 'channel'
  109. || empty($claims->grantor)) {
  110. throw new AuthorizationException(__('messages.agent_grant_invalid'));
  111. }
  112. return [
  113. 'editor' => (string) $claims->grantor,
  114. 'co_editor' => $userUid,
  115. 'scope' => ['channel' => (string) $claims->res_id, 'book' => (int) ($claims->book ?? 0)],
  116. ];
  117. }
  118. /**
  119. * 授权是否覆盖这次写入落到的 channel / book。人类直接写(scope 为 null)恒为真。
  120. *
  121. * @param array{channel: string, book: int}|null $scope
  122. */
  123. public function covers(?array $scope, ?string $channelUid, ?int $book): bool
  124. {
  125. if ($scope === null) {
  126. return true;
  127. }
  128. return $channelUid === $scope['channel'] && ($scope['book'] === 0 || $book === $scope['book']);
  129. }
  130. /**
  131. * 只许人类操作的写入(channel、团队这类「权限本身」的资源不支持 agent 代写):模型 token 一律 403。
  132. *
  133. * @throws AuthorizationException
  134. */
  135. public function assertHuman(string $uid): void
  136. {
  137. if ($this->isModel($uid)) {
  138. throw new AuthorizationException(__('messages.agent_not_allowed'));
  139. }
  140. }
  141. private function isModel(string $uid): bool
  142. {
  143. return AiModel::where('uid', $uid)->exists();
  144. }
  145. /** 与登录 token 分开的签名密钥:授权 token 不能被当成登录 token 用,反之亦然 */
  146. private function key(): string
  147. {
  148. return hash('sha512', config('mint.app.jwt_secrets_key').'|'.self::TYPE);
  149. }
  150. }