Skip to content

Commit 98ba756

Browse files
feat(auth): an AI service account is a sys_user row of kind agent that never signs in (#31779)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9H3PTJ3DC1WnJJ1S3UcQwgg)_ Part of #31739 Clause-②: yes Metadata-protocol: none Clause-② measured: the published face widens by two `sys_user` columns (`principal_kind`, `accountable_user_id`), one `ReconcileOutcome` member (`agent-account`) and one new plugin-auth module (`service-account-identity.ts`). No authorable metadata key changes, so the changeset level is `patch`. ## 维护者速读 - 改了什么:`sys_user` 新增「主体类型」与「负责人」两列,AI 服务账号是一条 `agent` 类型的用户记录;它不能登录、不能被模拟登录、不能持有密码或第三方登录绑定,成员关系自动绑定也跳过它。 - 为什么改:ADR-0151 第一步(D1 记录、D2 不登录),PR-2 的权限上限和 PR-3 的注册与密钥入口都建在这条记录上。 - 风险与回滚:每次建会话多读一次本人的 `sys_user` 行;读失败时仍拒绝(宁拒勿放),但返回 503「用户记录读取失败,请重试」并记录原因,不会把人误报成 AI 服务账号。现有用户都按「人」处理,行为不变。回滚即还原本 PR。 - 先看:`packages/plugins/plugin-auth/src/service-account-identity.ts`(拒绝与行守卫,留意 catch 分支)、`auth-manager-database-hooks.ts`(会话与凭证钩子的接入点)、`reconcile-membership.ts`。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run src/service-account-sign-in-refusal.test.ts src/service-account-identity.test.ts`,应见 32 个用例全绿。 - 需要你做的:无,席位落地。 ## What changes - **D1, the row.** `sys_user` gains `principal_kind` (`human` default, or `agent`) and `accountable_user_id` (a lookup to `sys_user`). Both are `readonly` and listed in the D7 managed-extension set, so the generic data path never writes them. - **D1 rules, every writer including the system.** A new `sys_user` row guard (priority 4, before the identity write guard) holds three rules. A user's kind is set at creation and never changes. An `agent` row names an existing person as its owner, never itself and never another account. A person names no owner. Refusals are `400 VALIDATION_FAILED` with ADR-0114 field codes (`required`, `reference_not_found`, `invalid_value`). - **D2, no session.** `session.create.before` first refuses an `agent` user with `403 PERMISSION_DENIED`. better-auth routes every session through `internalAdapter.createSession`, so this covers password, magic link, one-time code, passkey, social and SSO sign-in, impersonation and the server-side principal-session mint. - **D2, no credential.** `account.create.before` refuses a `sys_account` row (a password or a provider link) for an `agent` user. - **A failed read of the user row.** Both refusals fail closed, but as an outage: `503 SERVICE_UNAVAILABLE` with "the user record could not be read … try again", and the cause logged once (class and message, never the session or credential). A person never sees the AI service account refusal because the database blinked. - **Membership.** `reconcileMembership` answers the new outcome `agent-account` and binds nothing. The one-time backfill skips `agent` rows. - **Translations.** The two new columns are translated in all ten locales; `en` is regenerated. Nothing registers an AI service account yet. The agent ceiling and key admission (PR-2) and the registration, key and lifecycle doors (PR-3) follow, each from a fresh main. ## Tests New, 32 cases: - `service-account-identity.test.ts` (19, real ObjectQL + SQLite): born with its kind, kind immutable for system, multi-row and user-context writes, the owner rules, the reconciler and backfill exemption, and CONTROLs for people. - `service-account-sign-in-refusal.test.ts` (13, AuthManager on the shared memory engine): password, magic link, impersonation, principal-session mint, `internalAdapter.createSession`, `createAccount`/`linkAccount` refused with no row written; a failed row read refuses both as a 503 read fault with the cause logged; CONTROLs where a person signs in, is impersonated and links a provider as before. Forced test edits, all in `first-session-membership-ordering.test.ts`, because the session hook now reads the user's own row first: - `a no-bind sign-in costs NO extra membership read — the re-read is gated on the outcome`: `find` was "never called"; it is now "called exactly once, with the `sys_user` principal-kind read". The membership read count is unchanged. - `a sign-in that created nobody costs no read beyond the original selection`: the same edit. - `a broken engine never breaks session create`: the double's `find` now answers the `sys_user` read and still fails every membership read. A failed principal-kind read refuses the session on purpose, pinned in the new sign-in refusal file. ## Acceptance notes - PR-1 of the approved three-PR serial split (D1+D2). The card stays open. - The same-organisation rule for the owner is left to the PR-3 registration door, which knows the organisation. - ADR-0151's status line still reads "Proposed" although it merged; flagged to the seat, not touched here. - Seat: CONTRACT_REVIEW_TIER review owed on this PR. ## Verification <details><summary>Tests and typecheck</summary> - `pnpm --filter @objectstack/plugin-auth test` (lock): 248 files passed, 4438 passed / 10 skipped, at 9a03a66 and again at d2d101d. - `pnpm --filter @objectstack/platform-objects test`: 120 files, 1931 passed. - `tsc --noEmit` for plugin-auth and platform-objects: exit 0. - `eslint packages/plugins/plugin-auth packages/platform-objects --no-inline-config`: exit 0. - `check-i18n-bundles`: all bundles in sync. - After the read-fault change: `check:dispatcher-error-vocabulary`, `check:error-status-conformance`, `check:error-code-casing` and plugin-auth eslint exit 0. - After merging main (9a03a66): the three touched test files, 52 passed; full `pnpm build` 119/119. </details> <details><summary>Ablations (each red, then restored: blob == HEAD, `git diff HEAD` empty)</summary> Each through `scripts/ablation-replace.mjs`; the named pin went red and the file came back with blob == HEAD. 1. Session refusal removed from `session.create.before`: password, magic link, impersonation, mint and createSession pins red. 2. Credential refusal removed from `account.create.before`: createAccount/linkAccount pin red. 3. Kind-change check removed from the row guard: immutability pins red. 4. Owner-required check removed: owner pins red. 5. Reconciler exemption removed: reconciler pin red. 6. Backfill skip removed: backfill pin red. 7. Person-with-owner check removed: person-owner pin red. 8. Session refusal fails open on a read error: "a session whose user row cannot be read is refused" red. 9. Credential refusal fails open on a read error: "a credential whose user row cannot be read is refused" red. After seat review (read-fault refusal, d2d101d): 10. Session read fault answers the AI service account refusal instead: "a session whose user row cannot be read is refused as a read fault, and the cause is logged" red. 11. Credential read fault answers the AI service account refusal instead: the credential twin red. 12. The cause log removed (`console.warn(` → `String(`): both read-fault pins red. A first attempt at this leg (`void (` with a trailing comma) failed to transform, so it measured nothing; it was replaced by this one. </details> <details><summary>Dispatch gates</summary> `node scripts/pm/dispatch-gates.mjs --repo objectstack-ai/objectstack --ran`: 77 derived, 77 run, 0 NOT-MEASURED, every exit 0. - `check:dispatcher-error-vocabulary` first flagged the three field codes stamped through a parameter; the refusal helper now takes one literal ADR-0114 field entry, and the gate passes. - `check:dual-build-cjs-loads` and the teardown self-test ran after a full build and a fetch of their pinned commit. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 <!-- signed: domain:server#1 · os-steve · session_01ADHkmPK8RUPmLyYjQGCe58 --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 75d7fb1 commit 98ba756

23 files changed

Lines changed: 1232 additions & 8 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/platform-objects': patch
3+
'@objectstack/plugin-auth': patch
4+
---
5+
6+
feat(auth): an AI service account is a `sys_user` row of kind `agent` that never signs in (ADR-0151 D1, D2)
7+
8+
Clause-②: yes
9+
Metadata-protocol: none
10+
11+
`sys_user` gains two columns. `principal_kind` is `human` (the default, and what every existing row reads as) or `agent`, an AI service account. `accountable_user_id` names the person accountable for an AI service account. Both are system-managed: the generic data path never writes them.
12+
13+
Rules that hold for every writer, the system included:
14+
15+
- A user is created with its kind and the kind never changes. An update that turns a person into an AI service account, or the reverse, is refused `400 VALIDATION_FAILED` on `principal_kind`.
16+
- An AI service account names an existing person as its accountable owner; a person names none. Creating or updating a row against that is refused `400 VALIDATION_FAILED` on `accountable_user_id` (`required`, `reference_not_found` or `invalid_value`).
17+
- An AI service account never holds a session: password, magic link, one-time code, passkey, social and SSO sign-in, impersonation and every server-minted session are refused `403 PERMISSION_DENIED`. It never holds a password or a sign-in provider link either.
18+
- The membership reconciler and the one-time membership backfill never bind an AI service account (`reconcileMembership` answers the new outcome `agent-account`).
19+
20+
Nothing registers an AI service account yet: the registration, key and lifecycle doors, and the account's own authority under the agent ceiling, follow in later changes. Every existing user, sign-in and membership behaves as before.

‎packages/platform-objects/src/apps/translations/ar.objects.generated.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,18 @@ export const arObjects: NonNullable<TranslationData['objects']> = {
8888
label: "الوصول إلى الذكاء الاصطناعي",
8989
help: "ما إذا كان هذا المستخدم يشغل مقعد ذكاء اصطناعي. يمنح المقعد صلاحية `ai_seat` التي تفتح مساعدي الذكاء الاصطناعي في التطبيق (البناء والسؤال). يحدّ عدد المقاعد المضمّنة في ترخيصك عدد المستخدمين الذين يمكنهم شغل مقعد."
9090
},
91+
principal_kind: {
92+
label: "نوع الكيان",
93+
help: "ما إذا كان هذا المستخدم شخصًا أم حساب خدمة ذكاء اصطناعي. لا يسجّل حساب خدمة الذكاء الاصطناعي الدخول أبدًا، ويعمل فقط عبر مفاتيح API الخاصة به. يُحدَّد عند إنشاء المستخدم ولا يتغيّر أبدًا.",
94+
options: {
95+
human: "شخص",
96+
agent: "حساب خدمة ذكاء اصطناعي"
97+
}
98+
},
99+
accountable_user_id: {
100+
label: "المالك المسؤول",
101+
help: "لحساب خدمة الذكاء الاصطناعي، الشخص المسؤول عنه. فارغ للشخص. لا تنتقل صلاحيات المالك نفسه إلى الحساب أبدًا."
102+
},
91103
image: {
92104
label: "صورة الملف الشخصي"
93105
},

‎packages/platform-objects/src/apps/translations/de.objects.generated.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,18 @@ export const deObjects: NonNullable<TranslationData['objects']> = {
8888
label: "KI-Zugriff",
8989
help: "Ob dieser Benutzer einen KI-Platz innehat. Ein Platz verleiht die Berechtigung `ai_seat`, die die KI-Assistenten in der App öffnet (Erstellen und Fragen). Wie viele Benutzer einen innehaben können, begrenzt die Zahl der Plätze in Ihrer Lizenz."
9090
},
91+
principal_kind: {
92+
label: "Prinzipaltyp",
93+
help: "Ob dieser Benutzer eine Person oder ein KI-Dienstkonto ist. Ein KI-Dienstkonto meldet sich nie an und handelt nur über seine eigenen API-Schlüssel. Wird beim Anlegen des Benutzers festgelegt und ändert sich nie.",
94+
options: {
95+
human: "Person",
96+
agent: "KI-Dienstkonto"
97+
}
98+
},
99+
accountable_user_id: {
100+
label: "Verantwortliche Person",
101+
help: "Bei einem KI-Dienstkonto die dafür verantwortliche Person. Bei einer Person leer. Die eigenen Berechtigungen der verantwortlichen Person gehen nie auf das Konto über."
102+
},
91103
image: {
92104
label: "Profilbild"
93105
},

‎packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,4 +174,5 @@ export const deGeneratedSourceHashes: Readonly<Record<string, string>> = {
174174
"objects.sys_team.pluralLabel": "3fe8519872f65108",
175175
"objects.sys_team_member.fields.team_id.label": "42b87165ac826b2b",
176176
"objects.sys_user.fields.name.label": "5274417ff1ccaf01",
177+
"objects.sys_user.fields.principal_kind.options.human": "ed18d3469e10aef2",
177178
};

‎packages/platform-objects/src/apps/translations/en.objects.generated.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,18 @@ export const enObjects: NonNullable<TranslationData['objects']> = {
8888
label: "AI Access",
8989
help: "Whether this user holds an AI seat. A seat grants the `ai_seat` capability, which opens the AI assistants in the app (build and ask). How many users can hold one is limited by the seats your license includes."
9090
},
91+
principal_kind: {
92+
label: "Principal Kind",
93+
help: "Whether this user is a person or an AI service account. An AI service account never signs in and acts only through its own API keys. Set when the user is created; it never changes.",
94+
options: {
95+
human: "Person",
96+
agent: "AI Service Account"
97+
}
98+
},
99+
accountable_user_id: {
100+
label: "Accountable Owner",
101+
help: "For an AI service account, the person accountable for it. Empty for a person. The owner's own permissions never pass to the account."
102+
},
91103
image: {
92104
label: "Profile Image"
93105
},

‎packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,18 @@ export const esESObjects: NonNullable<TranslationData['objects']> = {
8888
label: "Acceso a IA",
8989
help: "Indica si este usuario dispone de una plaza de IA. La plaza otorga la capacidad `ai_seat`, que da acceso a los asistentes de IA de la aplicación (build y ask). El número de usuarios que pueden tenerla está limitado por las plazas que incluye su licencia."
9090
},
91+
principal_kind: {
92+
label: "Tipo de principal",
93+
help: "Indica si este usuario es una persona o una cuenta de servicio de IA. Una cuenta de servicio de IA nunca inicia sesión y actúa solo mediante sus propias claves de API. Se fija al crear el usuario y no cambia nunca.",
94+
options: {
95+
human: "Persona",
96+
agent: "Cuenta de servicio de IA"
97+
}
98+
},
99+
accountable_user_id: {
100+
label: "Responsable",
101+
help: "En una cuenta de servicio de IA, la persona responsable de ella. Vacío en una persona. Los permisos del responsable nunca pasan a la cuenta."
102+
},
91103
image: {
92104
label: "Imagen de perfil"
93105
},

‎packages/platform-objects/src/apps/translations/fr.objects.generated.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,18 @@ export const frObjects: NonNullable<TranslationData['objects']> = {
8888
label: "Accès IA",
8989
help: "Indique si cet utilisateur dispose d’un siège IA. Un siège accorde la capacité `ai_seat`, qui ouvre les assistants IA dans l’application (créer et demander). Le nombre d’utilisateurs pouvant en détenir un est limité par les sièges inclus dans votre licence."
9090
},
91+
principal_kind: {
92+
label: "Type de principal",
93+
help: "Indique si cet utilisateur est une personne ou un compte de service IA. Un compte de service IA ne se connecte jamais et n’agit qu’au moyen de ses propres clés d’API. Défini à la création de l’utilisateur ; ne change jamais.",
94+
options: {
95+
human: "Personne",
96+
agent: "Compte de service IA"
97+
}
98+
},
99+
accountable_user_id: {
100+
label: "Responsable",
101+
help: "Pour un compte de service IA, la personne qui en est responsable. Vide pour une personne. Les autorisations propres du responsable ne passent jamais au compte."
102+
},
91103
image: {
92104
label: "Photo de profil"
93105
},

‎packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,18 @@ export const jaJPObjects: NonNullable<TranslationData['objects']> = {
8888
label: "AI アクセス",
8989
help: "このユーザーが AI シートを保有しているかどうか。シートは `ai_seat` ケイパビリティを付与し、アプリ内の AI アシスタント(build と ask)を利用できるようにします。保有できるユーザー数は、ライセンスに含まれるシート数までです。"
9090
},
91+
principal_kind: {
92+
label: "プリンシパルの種類",
93+
help: "このユーザーが人か AI サービスアカウントか。AI サービスアカウントはサインインせず、自身の API キーだけで操作します。ユーザー作成時に設定され、変更されません。",
94+
options: {
95+
human: "人",
96+
agent: "AI サービスアカウント"
97+
}
98+
},
99+
accountable_user_id: {
100+
label: "責任者",
101+
help: "AI サービスアカウントについて、その責任を負う人。人のユーザーでは空です。責任者自身の権限はアカウントに引き継がれません。"
102+
},
91103
image: {
92104
label: "プロフィール画像"
93105
},

‎packages/platform-objects/src/apps/translations/ko.objects.generated.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,18 @@ export const koObjects: NonNullable<TranslationData['objects']> = {
8888
label: "AI 액세스",
8989
help: "이 사용자가 AI 시트를 보유하는지 여부입니다. 시트는 `ai_seat` 시스템 권한을 부여하며, 이를 통해 앱의 AI 어시스턴트(빌드 및 질문)를 사용할 수 있습니다. 보유할 수 있는 사용자 수는 라이선스에 포함된 시트 수로 제한됩니다."
9090
},
91+
principal_kind: {
92+
label: "주체 유형",
93+
help: "이 사용자가 사람인지 AI 서비스 계정인지 여부입니다. AI 서비스 계정은 로그인하지 않으며 자체 API 키로만 작업합니다. 사용자를 만들 때 정해지며 바뀌지 않습니다.",
94+
options: {
95+
human: "사람",
96+
agent: "AI 서비스 계정"
97+
}
98+
},
99+
accountable_user_id: {
100+
label: "책임자",
101+
help: "AI 서비스 계정의 경우 그 계정을 책임지는 사람입니다. 사람에게는 비어 있습니다. 책임자 자신의 권한은 계정에 넘어가지 않습니다."
102+
},
91103
image: {
92104
label: "프로필 이미지"
93105
},

‎packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,18 @@ export const ptBRObjects: NonNullable<TranslationData['objects']> = {
8888
label: "Acesso à IA",
8989
help: "Indica se este usuário ocupa uma licença de IA. A licença concede a capacidade `ai_seat`, que abre os assistentes de IA no app (criar e perguntar). Quantos usuários podem ter uma é limitado pelas licenças incluídas no seu plano."
9090
},
91+
principal_kind: {
92+
label: "Tipo de principal",
93+
help: "Indica se este usuário é uma pessoa ou uma conta de serviço de IA. Uma conta de serviço de IA nunca entra no sistema e age apenas por meio das próprias chaves de API. Definido na criação do usuário; nunca muda.",
94+
options: {
95+
human: "Pessoa",
96+
agent: "Conta de serviço de IA"
97+
}
98+
},
99+
accountable_user_id: {
100+
label: "Responsável",
101+
help: "Para uma conta de serviço de IA, a pessoa responsável por ela. Vazio para uma pessoa. As permissões do próprio responsável nunca passam para a conta."
102+
},
91103
image: {
92104
label: "Foto do perfil"
93105
},

0 commit comments

Comments
 (0)