@h-ai/ui 0.1.0-alpha.73 → 0.1.0-alpha.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.en.md +34 -3
  2. package/README.ja.md +35 -4
  3. package/README.md +36 -5
  4. package/auto-import.d.ts +2 -0
  5. package/auto-import.js +2 -0
  6. package/dist/components/scenes/app/FeedbackDetail.svelte +11 -1
  7. package/dist/components/scenes/app/FeedbackDetail.svelte.d.ts +6 -0
  8. package/dist/components/scenes/app/FeedbackForm.svelte +1 -1
  9. package/dist/components/scenes/iam/AuthPanel.svelte +7 -7
  10. package/dist/components/scenes/iam/AuthShell.svelte +6 -1
  11. package/dist/components/scenes/iam/AuthShell.svelte.d.ts +2 -0
  12. package/dist/components/scenes/iam/ChangePasswordForm.svelte +1 -1
  13. package/dist/components/scenes/iam/ForgotPasswordForm.svelte +1 -1
  14. package/dist/components/scenes/iam/LoginForm.svelte +4 -2
  15. package/dist/components/scenes/iam/RegisterForm.svelte +1 -1
  16. package/dist/components/scenes/iam/SensitiveOperationsForm.svelte +70 -0
  17. package/dist/components/scenes/iam/SensitiveOperationsForm.svelte.d.ts +21 -0
  18. package/dist/components/scenes/iam/SessionRecoveryDialog.svelte +64 -0
  19. package/dist/components/scenes/iam/SessionRecoveryDialog.svelte.d.ts +22 -0
  20. package/dist/components/scenes/iam/index.d.ts +6 -0
  21. package/dist/components/scenes/iam/index.js +4 -0
  22. package/dist/components/scenes/iam/sensitive-actions.svelte.d.ts +68 -0
  23. package/dist/components/scenes/iam/sensitive-actions.svelte.js +100 -0
  24. package/dist/components/scenes/iam/session-recovery.svelte.d.ts +44 -0
  25. package/dist/components/scenes/iam/session-recovery.svelte.js +57 -0
  26. package/dist/components/scenes/types.d.ts +7 -0
  27. package/dist/messages/en-US.json +13 -3
  28. package/dist/messages/ja-JP.json +13 -3
  29. package/dist/messages/zh-CN.json +13 -3
  30. package/package.json +2 -2
package/README.en.md CHANGED
@@ -293,7 +293,7 @@ Client validation appears on the first blur and updates as invalid input is corr
293
293
  | ------------ | ----------- | ----------------------------------------------- |
294
294
  | `PageHeader` | Page header | `title`, `description`; supports `actions` slot |
295
295
 
296
- #### Scenes (41)
296
+ #### Scenes (43)
297
297
 
298
298
  ##### Guide (2)
299
299
 
@@ -309,7 +309,7 @@ Client validation appears on the first blur and updates as invalid input is corr
309
309
  | `FeedbackModal` | Feedback modal | `open`, `onsubmit` |
310
310
  | `FeedbackForm` | Standalone feedback form | `attachments`, `evidenceSummary`, `onsubmit`, `onfileschange` |
311
311
  | `FeedbackList` | Server pagination, filters and processing actions | `data`, `query`, `permissions`, `onquerychange`, `onstatus` |
312
- | `FeedbackDetail` | Diagnostic evidence, history and exports | `report`, `evidence`, `attachments`, `history`, `onexport` |
312
+ | `FeedbackDetail` | Diagnostic evidence, history and exports | `report`, `evidence`, `attachments`, `history`, `webhook`, `onretry`, `onexport` |
313
313
  | `FeedbackScreenshot` | Image preview, highlighting and masking | `attachment`, `onannotate` |
314
314
  | `SettingsModal` | Settings modal | `open`, `onclose` |
315
315
  | `SettingsLayout` | Settings layout (section navigation + content) | `title`, `description`, `sections`, `active`, `onselect` |
@@ -318,6 +318,8 @@ Client validation appears on the first blur and updates as invalid input is corr
318
318
  | `ThemeSelector` | Full theme selector | No props required |
319
319
  | `ThemeToggle` | Light/dark toggle | No props required |
320
320
 
321
+ Pass the type: webhook task from report jobs into FeedbackDetail.webhook to show status, attempts and safe error codes; onretry calls the authenticated retry API. The Business evidence tab paginates kind: business, and archives download from the scene tab.
322
+
321
323
  Descriptions are optional. Call `prepare()` from `@h-ai/feedback/client` before opening the modal. Connect `onfileschange` to attachment preparation and `onannotate` to image editing that burns annotations into the pixels. Failed submissions retain input and support local export. The list shows the description or server summary and requests pages through `onquerychange`; UI permissions do not replace server authorization. See the [feedback module](../feedback/README.en.md) for integration and offline tools.
322
324
 
323
325
  ##### IAM authentication (11)
@@ -335,6 +337,8 @@ Descriptions are optional. Call `prepare()` from `@h-ai/feedback/client` before
335
337
  | `ReauthenticationDialog` | Sensitive action confirmation | `open`, `loading`, `error`, `onsubmit`, `onclose` |
336
338
  | `PermGuard` | Permission guard | `permissions`, `mode`, `fallback` |
337
339
  | `UserProfile` | User profile | `user`, `editable`, `fields`, `avatarAccept`, `avatarHint`, `onsubmit` |
340
+ | `SessionRecoveryDialog` | In-place session recovery | `recovery`, `actions` |
341
+ | `SensitiveOperationsForm` | Permission operation editor | `operations`, `onsubmit`, `ondone` |
338
342
 
339
343
  ##### Storage (4)
340
344
 
@@ -826,7 +830,34 @@ AuthPanel disables native form controls during SSR and enables input after clien
826
830
 
827
831
  When an authentication link points to the current complete URL, AuthPanel switches scenes without navigating again, so input entered after returning to login is preserved. Links with a different path, query, or hash use application routing. Modified clicks such as Ctrl/Cmd retain browser behavior.
828
832
 
829
- `ReauthenticationDialog` renders password confirmation through `open/loading/error/onsubmit/onclose`. The service calls `actions.reauthenticate(password, operation)` and passes the short-lived single-use proof only to the intended request; cancellation, closing and submission clear input, and proofs never grant permissions. `Input` supports `datetime-local`: convert its browser-local value to an explicit timestamp in the service layer.
833
+ `createSensitiveActions` can refresh database rules before an action through standard `actions.publicConfig()`. `SensitiveOperationsForm` shares line-based input, deduplication, validation and errors. Pass `operations`, async `onsubmit(operations)` returning HaiResult, and optional `ondone` for successful saves. Clearing database additions does not remove file rules.
834
+
835
+ Use `createSessionRecovery()` with `SessionRecoveryDialog` for expired sessions. Configure it with the public config and original `{ id, username }`, pass `recovery.recover` as Kit/API client's `recoverSession`, and give the dialog the same controller and standard actions. Call `cancel()` on teardown. The UI stores no passwords or business requests. `expectedUserId` restricts server session issuance to the original principal; captcha, lockout, access and password-renewal policies remain active. Cancellation preserves input and stops continuation; ambiguous network writes are never replayed. Reloaded/closed documents cannot recover lost in-memory drafts.
836
+
837
+ `createSensitiveActions(actions)` accepts Kit/API client authentication actions and shares confirmation, cancellation, retry, duplicate-submit and late-response handling. Create one per application root layout, update it with `configure(publicPolicy)`, and call `cancel()` on teardown. `authorize(operation)` returns undefined when confirmation is unnecessary, null when cancelled/busy, or the proof for that action. Do not send the business request on cancellation; pass a proof only to its intended request, never to global headers or persistent storage. Bind `ReauthenticationDialog` to the controller’s `open/loading/error/submit/cancel`; confirmation grants no permissions. `Input` supports `datetime-local`: convert its browser-local value to an explicit timestamp in the service layer.
838
+
839
+ ```svelte
840
+ <!-- actions comes from Kit/API client; policy is the public IAM reauthentication policy. -->
841
+ <script lang='ts'>
842
+ import type { SensitiveActionsOptions } from '@h-ai/ui'
843
+ import { createSensitiveActions, ReauthenticationDialog } from '@h-ai/ui'
844
+
845
+ const { actions, policy }: { actions: SensitiveActionsOptions, policy: { enabled: boolean, operations: string[] } } = $props()
846
+ const confirmation = createSensitiveActions(actions)
847
+ $effect(() => {
848
+ confirmation.configure(policy)
849
+ return () => confirmation.cancel()
850
+ })
851
+ // Await confirmation.authorize(operation) in the business action; stop on null.
852
+ </script>
853
+ <ReauthenticationDialog
854
+ open={confirmation.open}
855
+ loading={confirmation.loading}
856
+ error={confirmation.error}
857
+ onsubmit={password => confirmation.submit(password)}
858
+ onclose={() => confirmation.cancel()}
859
+ />
860
+ ```
830
861
 
831
862
  [完整 IAM 配置 / IAM configuration](../iam/README.en.md)
832
863
 
package/README.ja.md CHANGED
@@ -302,14 +302,14 @@ components/
302
302
  | `GuideHost` | 初回案内・ガイド・ヘルプダイアログ | `guide`, `locale`, `scope`, `autoStart` |
303
303
  | `HelpCenter` | 独立して使える検索付きヘルプ | `articles`, `tours`, `locale`, `selectedId`, `onstart` |
304
304
 
305
- ##### App:アプリ全体(11)
305
+ ##### App:アプリ全体(13)
306
306
 
307
307
  | コンポーネント | 説明 | 主なプロパティ |
308
308
  | ------------------ | ------------------------------------------- | -------------------------------------------------------- |
309
309
  | `FeedbackModal` | フィードバックモーダル | `open`, `onsubmit` |
310
310
  | `FeedbackForm` | 独立したフィードバックフォーム | `attachments`, `evidenceSummary`, `onsubmit`, `onfileschange` |
311
311
  | `FeedbackList` | サーバー側ページング・絞り込み・処理操作 | `data`, `query`, `permissions`, `onquerychange`, `onstatus` |
312
- | `FeedbackDetail` | 診断情報・処理履歴・エクスポート | `report`, `evidence`, `attachments`, `history`, `onexport` |
312
+ | `FeedbackDetail` | 診断情報・処理履歴・エクスポート | `report`, `evidence`, `attachments`, `history`, `webhook`, `onretry`, `onexport` |
313
313
  | `FeedbackScreenshot` | 画像のプレビュー・強調・マスキング | `attachment`, `onannotate` |
314
314
  | `SettingsModal` | 設定モーダル | `open`, `onclose` |
315
315
  | `SettingsLayout` | 設定レイアウト(区分ナビゲーション + 本文) | `title`, `description`, `sections`, `active`, `onselect` |
@@ -318,9 +318,11 @@ components/
318
318
  | `ThemeSelector` | テーマ選択パネル | プロパティ不要 |
319
319
  | `ThemeToggle` | ライト・ダーク切り替え | プロパティ不要 |
320
320
 
321
+ 詳細 jobs の type: webhook を FeedbackDetail.webhook に渡すと状態・試行回数・安全なエラーコードを表示し、onretry から認可付き retry API を呼びます。「業務情報」タブは kind: business をページ取得し、圧縮添付は操作現場からダウンロードします。
322
+
321
323
  説明は任意です。モーダルを開く前に `@h-ai/feedback/client` の `prepare()` で現場を固定します。`onfileschange` で添付を準備し、`onannotate` で注釈を画像のピクセルに反映します。送信失敗時は入力を保持し、ローカルに出力できます。一覧は説明またはサーバーの要約を表示し、`onquerychange` でページを取得します。UI の権限表示とは別にサーバーの認可が必要です。接続方法とオフラインツールは [feedback モジュール](../feedback/README.ja.md) を参照してください。
322
324
 
323
- ##### IAM:認証(11)
325
+ ##### IAM:認証(13)
324
326
 
325
327
  | コンポーネント | 説明 | 主なプロパティ |
326
328
  | -------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------ |
@@ -335,6 +337,8 @@ components/
335
337
  | `ReauthenticationDialog` | 機密操作の確認 | `open`, `loading`, `error`, `onsubmit`, `onclose` |
336
338
  | `PermGuard` | 権限ガード | `permissions`, `mode`, `fallback` |
337
339
  | `UserProfile` | ユーザープロフィール | `user`, `editable`, `fields`, `avatarAccept`, `avatarHint`, `onsubmit` |
340
+ | `SessionRecoveryDialog` | 画面内のセッション復帰 | `recovery`, `actions` |
341
+ | `SensitiveOperationsForm` | 権限の重要操作編集 | `operations`, `onsubmit`, `ondone` |
338
342
 
339
343
  ##### Storage:ストレージ(4)
340
344
 
@@ -826,7 +830,34 @@ AuthPanel は SSR 中のフォーム操作を無効にし、クライアント
826
830
 
827
831
  認証リンクが現在の完全な URL を指す場合、AuthPanel は再ナビゲーションせずに画面だけを切り替え、ログインに戻った直後の入力を保持します。パス、クエリー、hash が異なる場合はアプリのルーターに任せます。Ctrl/Cmd などの修飾キーを使ったクリックはブラウザーの動作を維持します。
828
832
 
829
- `ReauthenticationDialog` は `open/loading/error/onsubmit/onclose` でパスワード確認を表示します。サービスが `actions.reauthenticate(password, operation)` を呼び、短期・一回限りの証明を対象リクエストだけに渡します。取消・終了・送信で入力を消去し、証明自体は権限を付与しません。`Input` の `datetime-local` はブラウザーのローカル時刻のため、サービスで明確なタイムスタンプへ変換して送信します。
833
+ `createSensitiveActions` は標準 actions の `publicConfig()` で操作前に DB 規則を更新できます。`SensitiveOperationsForm` は行入力・重複除去・検証・エラー表示を共通化します。`operations` と HaiResult を返す非同期 `onsubmit(operations)` を渡し、成功時のみ `ondone` を呼びます。DB の追加を空にしてもファイルの規則は解除しません。
834
+
835
+ 期限切れの画面内復帰は `createSessionRecovery()` と `SessionRecoveryDialog` を使います。公開設定と元の `{ id, username }` を configure し、`recovery.recover` を Kit/API client の `recoverSession` に渡します。ダイアログに同じ controller と標準 actions を渡し、破棄時に `cancel()` します。UI にパスワードや業務要求を保存しません。`expectedUserId` は発行前に元の本人を検証し、通常の CAPTCHA・ロック・アクセス・改密方針を適用します。取消は入力を保持し、結果不明の通信障害では書込を再送しません。再読込や終了で失われたメモリの入力は復元できません。
836
+
837
+ `createSensitiveActions(actions)` はKit/API clientの認証アクションを受け取り、ログイン済み利用者の確認・取消・再試行・重複送信・遅延応答を共通処理します。アプリのルートレイアウトごとに生成し、`configure(公開設定)` で更新、破棄時は `cancel()` を呼びます。`authorize(operation)` は確認不要ならundefined、取消/処理中ならnull、成功なら当該操作の証明を返します。取消時は業務リクエストを送らず、証明は対象リクエストにのみ渡します。共有ヘッダーや永続ストレージには保存しません。`ReauthenticationDialog` に `open/loading/error/submit/cancel` を接続します。確認は権限を増やしません。`Input` の `datetime-local` はブラウザーのローカル時刻のため、サービスで明確なタイムスタンプへ変換して送信します。
838
+
839
+ ```svelte
840
+ <!-- actionsはKit/API clientの認証アクション、policyはIAMの公開再認証設定です。 -->
841
+ <script lang='ts'>
842
+ import type { SensitiveActionsOptions } from '@h-ai/ui'
843
+ import { createSensitiveActions, ReauthenticationDialog } from '@h-ai/ui'
844
+
845
+ const { actions, policy }: { actions: SensitiveActionsOptions, policy: { enabled: boolean, operations: string[] } } = $props()
846
+ const confirmation = createSensitiveActions(actions)
847
+ $effect(() => {
848
+ confirmation.configure(policy)
849
+ return () => confirmation.cancel()
850
+ })
851
+ // 業務操作でconfirmation.authorize(operation)を待ち、nullなら中止します。
852
+ </script>
853
+ <ReauthenticationDialog
854
+ open={confirmation.open}
855
+ loading={confirmation.loading}
856
+ error={confirmation.error}
857
+ onsubmit={password => confirmation.submit(password)}
858
+ onclose={() => confirmation.cancel()}
859
+ />
860
+ ```
830
861
 
831
862
  [完整 IAM 配置 / IAM configuration](../iam/README.ja.md)
832
863
 
package/README.md CHANGED
@@ -293,7 +293,7 @@ components/
293
293
  | ------------ | -------- | ------------------------------------------- |
294
294
  | `PageHeader` | 页面头部 | `title`, `description`,支持 `actions` 插槽 |
295
295
 
296
- #### 场景组件 Scenes(41 个)
296
+ #### 场景组件 Scenes(43 个)
297
297
 
298
298
  ##### Guide 引导与帮助(2 个)
299
299
 
@@ -302,14 +302,14 @@ components/
302
302
  | `GuideHost` | 首次邀请、页面导览与帮助弹窗宿主 | `guide`, `locale`, `scope`, `autoStart` |
303
303
  | `HelpCenter` | 可独立使用的帮助中心 | `articles`, `tours`, `locale`, `selectedId`, `onstart` |
304
304
 
305
- ##### App 应用级(11 个)
305
+ ##### App 应用级(13 个)
306
306
 
307
307
  | 组件 | 描述 | 主要属性 |
308
308
  | ---------------- | ---------------- | ------------------ |
309
309
  | `FeedbackModal` | 反馈模态框 | `open`, `onsubmit` |
310
310
  | `FeedbackForm` | 独立反馈表单 | `attachments`, `evidenceSummary`, `onsubmit`, `onfileschange` |
311
311
  | `FeedbackList` | 服务端分页、筛选与处理操作 | `data`, `query`, `permissions`, `onquerychange`, `onstatus` |
312
- | `FeedbackDetail` | 诊断材料、处理历史与导出 | `report`, `evidence`, `attachments`, `history`, `onexport` |
312
+ | `FeedbackDetail` | 诊断材料、处理历史与导出 | `report`, `evidence`, `attachments`, `history`, `webhook`, `onretry`, `onexport` |
313
313
  | `FeedbackScreenshot` | 图片预览、圈选与遮挡 | `attachment`, `onannotate` |
314
314
  | `SettingsModal` | 设置模态框 | `open`, `onclose` |
315
315
  | `SettingsLayout` | 设置页布局(分区导航 + 内容区) | `title`, `description`, `sections`, `active`, `onselect` |
@@ -318,9 +318,11 @@ components/
318
318
  | `ThemeSelector` | 完整主题选择面板 | 无需 Props |
319
319
  | `ThemeToggle` | 明/暗主题切换 | 无需 Props |
320
320
 
321
+ 将详情 jobs 中 type: webhook 的任务传给 FeedbackDetail.webhook,显示状态、尝试次数及安全错误码;onretry 负责调用受权 retry API。业务异步证据在“业务信息”页签分页查询 kind: business,压缩附件在“操作现场”下载。
322
+
321
323
  反馈说明可为空;宿主先用 `@h-ai/feedback/client` 的 `prepare()` 固定现场,再打开弹窗。表单通过 `onfileschange` 准备主动附件、通过 `onannotate` 将标注烧录到图片;受理失败保留输入并可本地导出。列表展示说明或服务端事实摘要,以 `onquerychange` 取得分页数据;界面权限不代替服务端授权。完整接入与离线工具见 [feedback 模块](../feedback/README.md)。
322
324
 
323
- ##### IAM 身份认证(11 个)
325
+ ##### IAM 身份认证(13 个)
324
326
 
325
327
  | 组件 | 描述 | 主要属性 |
326
328
  | -------------------- | ---------- | ----------------------------------------------------- |
@@ -335,6 +337,8 @@ components/
335
337
  | `ReauthenticationDialog` | 敏感操作再认证 | `open`, `loading`, `error`, `onsubmit`, `onclose` |
336
338
  | `PermGuard` | 权限守卫 | `permissions`, `mode`, `fallback` |
337
339
  | `UserProfile` | 用户资料 | `user`, `editable`, `fields`, `avatarAccept`, `avatarHint`, `onsubmit` |
340
+ | `SessionRecoveryDialog` | 原地会话恢复 | `recovery`, `actions` |
341
+ | `SensitiveOperationsForm` | 权限敏感操作编辑 | `operations`, `onsubmit`, `ondone` |
338
342
 
339
343
  ##### Storage 存储(4 个)
340
344
 
@@ -842,7 +846,34 @@ AuthPanel 在 SSR 阶段禁用原生表单控件,客户端挂载并绑定事
842
846
 
843
847
  认证链接指向当前完整 URL 时,AuthPanel 只切换场景并阻止重复导航,返回登录后可立即输入。路径、查询串或 hash 不同时交给应用路由处理;Ctrl/Cmd 等修改键点击保留浏览器行为。
844
848
 
845
- `ReauthenticationDialog` 只展示密码确认框,通过 `open/loading/error/onsubmit/onclose` 接入服务层。服务调用 `actions.reauthenticate(password, operation)`,拿到短期单次凭据后仅传给本次敏感请求;取消、关闭和提交会清除输入,凭据不提升原有权限。`Input` 支持 `datetime-local`,其值为浏览器本地时间,服务层转换为明确时间戳后提交。
849
+ `createSensitiveActions` 可利用标准 actions 的 `publicConfig()` 在操作前更新数据库规则。`SensitiveOperationsForm` 复用逐行输入、去重、校验与错误状态;传入 `operations`、异步 `onsubmit(operations)`(返回 HaiResult),`ondone` 只在保存成功后调用。数据库规则与文件规则取并集,表单清空不能取消文件规则。
850
+
851
+ 会话过期后的重新登录使用 `createSessionRecovery()` + `SessionRecoveryDialog`。根布局通过 `configure(publicConfig, { id, username })` 绑定原用户,把 `recovery.recover` 传给 Kit/API client 的 `recoverSession`;弹窗传入同一份 controller 和标准 actions,布局卸载时 `cancel()`。UI 不保存密码或业务请求,不切换页面。登录携带 `expectedUserId`,服务端在发会话前限制原主体;验证码、锁定、登录限制和改密流程仍按正常登录执行。取消保留当前输入并结束本次续接;真实网络失败不重放写入。整页刷新/关闭后的内存输入无法恢复。
852
+
853
+ `createSensitiveActions(actions)` 复用 Kit/API client 的认证动作,统一管理已登录用户的二次确认、取消、错误重试、重复提交与迟到响应。每个应用根布局创建一份,用 `configure(公开策略)` 更新清单;布局卸载时 `cancel()`。`authorize(operation)` 返回 undefined 表示不需确认、null 表示取消/忙、字符串为本次操作凭据;取消时不要发业务请求。有凭据时只传给本次请求,不放全局 header 或持久存储。`ReauthenticationDialog` 绑定控制器的 `open/loading/error/submit/cancel`,不会增加权限。`Input` 支持 `datetime-local`,其值为浏览器本地时间,服务层转换为明确时间戳后提交。
854
+
855
+ ```svelte
856
+ <!-- actions 为 Kit/API client 的标准认证动作;policy 为 IAM 公开再认证策略。 -->
857
+ <script lang='ts'>
858
+ import type { SensitiveActionsOptions } from '@h-ai/ui'
859
+ import { createSensitiveActions, ReauthenticationDialog } from '@h-ai/ui'
860
+
861
+ const { actions, policy }: { actions: SensitiveActionsOptions, policy: { enabled: boolean, operations: string[] } } = $props()
862
+ const confirmation = createSensitiveActions(actions)
863
+ $effect(() => {
864
+ confirmation.configure(policy)
865
+ return () => confirmation.cancel()
866
+ })
867
+ // 业务动作 await confirmation.authorize(operation);null 时中止该动作。
868
+ </script>
869
+ <ReauthenticationDialog
870
+ open={confirmation.open}
871
+ loading={confirmation.loading}
872
+ error={confirmation.error}
873
+ onsubmit={password => confirmation.submit(password)}
874
+ onclose={() => confirmation.cancel()}
875
+ />
876
+ ```
846
877
 
847
878
  [完整 IAM 配置 / IAM configuration](../iam/README.md)
848
879
 
package/auto-import.d.ts CHANGED
@@ -104,6 +104,8 @@ declare global {
104
104
  const ReauthenticationDialog: typeof import('@h-ai/ui')['ReauthenticationDialog']
105
105
  const RegisterForm: typeof import('@h-ai/ui')['RegisterForm']
106
106
  const ResetPasswordForm: typeof import('@h-ai/ui')['ResetPasswordForm']
107
+ const SensitiveOperationsForm: typeof import('@h-ai/ui')['SensitiveOperationsForm']
108
+ const SessionRecoveryDialog: typeof import('@h-ai/ui')['SessionRecoveryDialog']
107
109
  const UserProfile: typeof import('@h-ai/ui')['UserProfile']
108
110
 
109
111
  // scenes - storage
package/auto-import.js CHANGED
@@ -95,6 +95,8 @@ const UI_COMPONENTS = new Set([
95
95
  'ReauthenticationDialog',
96
96
  'RegisterForm',
97
97
  'ResetPasswordForm',
98
+ 'SensitiveOperationsForm',
99
+ 'SessionRecoveryDialog',
98
100
  'UserProfile',
99
101
  // scenes - storage
100
102
  'AvatarUpload',
@@ -30,6 +30,7 @@
30
30
  evidence = { items: [], total: 0, page: 1, pageSize: 20 },
31
31
  attachments = [],
32
32
  history = [],
33
+ webhook,
33
34
  permissions = {},
34
35
  loading = false,
35
36
  error = '',
@@ -48,6 +49,8 @@
48
49
  evidence?: FeedbackPage<FeedbackEvidenceView>
49
50
  attachments?: FeedbackAttachmentView[]
50
51
  history?: FeedbackHistoryView[]
52
+ /** 持久 Webhook 任务的公开状态,由反馈详情 jobs 中的 webhook 项提供。 */
53
+ webhook?: { status: 'pending' | 'running' | 'succeeded' | 'failed', attempts: number, lastError?: string }
51
54
  permissions?: FeedbackPermissions
52
55
  loading?: boolean
53
56
  error?: string
@@ -79,6 +82,7 @@
79
82
  { key: 'scene', label: uiM('feedback_scene') },
80
83
  { key: 'replay', label: uiM('feedback_replay') },
81
84
  { key: 'logs', label: uiM('feedback_logs') },
85
+ { key: 'business', label: uiM('feedback_business') },
82
86
  { key: 'environment', label: uiM('feedback_environment') },
83
87
  { key: 'history', label: uiM('feedback_history') },
84
88
  ])
@@ -122,6 +126,8 @@
122
126
  void query({ page: 1, kind: 'interaction' })
123
127
  else if (tab === 'logs')
124
128
  void query({ page: 1, kind: undefined })
129
+ else if (tab === 'business')
130
+ void query({ page: 1, kind: 'business', requestId: undefined, errorId: undefined })
125
131
  }
126
132
  </script>
127
133
 
@@ -147,17 +153,21 @@
147
153
  <dl class='grid grid-cols-1 gap-3 text-sm sm:grid-cols-2 xl:grid-cols-3'>
148
154
  <div><dt class='text-base-content/55'>{uiM('feedback_collection')}</dt><dd>{collectionLabel(report.collectionStatus)}</dd></div>
149
155
  <div><dt class='text-base-content/55'>{uiM('feedback_notification')}</dt><dd>{notificationLabel(report.notificationStatus)}</dd></div>
156
+ {#if webhook}
157
+ <div><dt class='text-base-content/55'>{uiM('feedback_webhook')}</dt><dd>{notificationLabel(webhook.status === 'succeeded' ? 'sent' : webhook.status === 'running' ? 'sending' : webhook.status)} · {uiM('feedback_attempts')}: {webhook.attempts}</dd>{#if webhook.lastError}<dd class='break-all text-error'>{webhook.lastError}</dd>{/if}</div>
158
+ {/if}
150
159
  <div><dt class='text-base-content/55'>{uiM('feedback_submitter')}</dt><dd class='break-all'>{report.userId || '—'}</dd></div>
151
160
  <div><dt class='text-base-content/55'>{uiM('feedback_revision')}</dt><dd>{report.evidenceRevision}</dd></div>
152
161
  {#if report.buildId}<div><dt class='text-base-content/55'>{uiM('feedback_build_id')}</dt><dd class='break-all'>{report.buildId}</dd></div>{/if}
153
162
  {#if report.commit}<div><dt class='text-base-content/55'>{uiM('feedback_commit')}</dt><dd class='break-all'>{report.commit}</dd></div>{/if}
154
163
  </dl>
164
+ {#if webhook?.status === 'failed' && permissions.retry && onretry}<Button size='sm' disabled={busy} onclick={() => run(() => onretry(report!))}>{uiM('feedback_retry')}</Button>{/if}
155
165
  </div>
156
166
  {:else if tab === 'replay'}
157
167
  <div class='py-4'>
158
168
  {#if onreplay}<FeedbackReplay load={onreplay} />{:else}<p class='text-sm'>{uiM('feedback_replay_empty')}</p>{/if}
159
169
  </div>
160
- {:else if tab === 'scene' || tab === 'logs' || tab === 'environment'}
170
+ {:else if tab === 'scene' || tab === 'logs' || tab === 'environment' || tab === 'business'}
161
171
  <div class='space-y-4 py-4'>
162
172
  {#if tab === 'scene'}
163
173
  <div class='grid grid-cols-1 gap-3 xl:grid-cols-2'>
@@ -5,6 +5,12 @@ type $$ComponentProps = {
5
5
  evidence?: FeedbackPage<FeedbackEvidenceView>;
6
6
  attachments?: FeedbackAttachmentView[];
7
7
  history?: FeedbackHistoryView[];
8
+ /** 持久 Webhook 任务的公开状态,由反馈详情 jobs 中的 webhook 项提供。 */
9
+ webhook?: {
10
+ status: 'pending' | 'running' | 'succeeded' | 'failed';
11
+ attempts: number;
12
+ lastError?: string;
13
+ };
8
14
  permissions?: FeedbackPermissions;
9
15
  loading?: boolean;
10
16
  error?: string;
@@ -268,7 +268,7 @@
268
268
  {#if oncapture}<Button size='sm' variant='outline' disabled={loading || annotating || staging || exporting} onclick={() => oncapture()}>{uiM('feedback_capture_add')}</Button>{/if}
269
269
  <label class='btn btn-sm btn-ghost focus-within:outline focus-within:outline-primary'>
270
270
  {uiM('feedback_add_files')}
271
- <BareInput id={`${instanceId}-files`} type='file' aria-label={uiM('feedback_add_files')} accept='.png,.jpg,.jpeg,.webp,.webm,.mp4,.txt,.log,.json,.pdf,image/png,image/jpeg,image/webp,video/webm,video/mp4,text/plain,application/json,application/pdf' multiple disabled={loading || staging || exporting} class='sr-only' onchange={selectFiles} />
271
+ <BareInput id={`${instanceId}-files`} type='file' aria-label={uiM('feedback_add_files')} accept='.png,.jpg,.jpeg,.webp,.webm,.mp4,.txt,.log,.json,.pdf,.zip,.gz,.tgz,image/png,image/jpeg,image/webp,video/webm,video/mp4,text/plain,application/json,application/pdf,application/zip,application/gzip' multiple disabled={loading || staging || exporting} class='sr-only' onchange={selectFiles} />
272
272
  </label>
273
273
  {#if onfileschange}<FeedbackRecorder maxBytes={recordingBytes} disabled={loading || annotating || staging || exporting || attachmentLimitReached} onactive={recordingChanged} onrecord={recorded} />{/if}
274
274
  </div>
@@ -46,7 +46,7 @@
46
46
  import RegisterForm from './RegisterForm.svelte'
47
47
  import ResetPasswordForm from './ResetPasswordForm.svelte'
48
48
 
49
- const { config, actions, columns = 1, labelPosition = 'top', labelWidth = '8rem', initialMode = 'login', resetToken = '', loginUrl, registerUrl, forgotPasswordUrl, onauthenticated, error = '', onretry, loginHeader, loginFields, loginFooter, registerHeader, registerFields, registerFooter, ...restProps }: AuthPanelProps = $props()
49
+ const { config, actions, embedded = false, initialIdentifier = '', columns = 1, labelPosition = 'top', labelWidth = '8rem', initialMode = 'login', resetToken = '', loginUrl, registerUrl, forgotPasswordUrl, onauthenticated, error = '', onretry, loginHeader, loginFields, loginFooter, registerHeader, registerFields, registerFooter, ...restProps }: AuthPanelProps = $props()
50
50
  const dataAttributes = $derived(getDataAttributes(restProps))
51
51
  let mode = $state<AuthPanelMode>(untrack(() => initialMode))
52
52
  let loading = $state(false)
@@ -164,7 +164,7 @@
164
164
  {:else}<BareButton type='button' class='link link-primary text-sm' disabled={loading} onclick={() => switchMode(next)}>{label}</BareButton>{/if}
165
165
  {/snippet}
166
166
 
167
- <AuthShell {...dataAttributes} {...config?.ui} title={config?.ui.title || title} brandTitle={config?.ui.brandTitle || uiM('auth_brand')}>
167
+ <AuthShell {embedded} {...dataAttributes} {...config?.ui} title={config?.ui.title || title} brandTitle={config?.ui.brandTitle || uiM('auth_brand')}>
168
168
  <fieldset class='m-0 min-w-0 border-0 p-0' disabled={!interactive}>
169
169
  <!-- 固定内容包装节点,避免 fieldset 插入通知时丢失容器查询子树的布局。 -->
170
170
  <div class='min-w-0'>
@@ -178,9 +178,9 @@
178
178
  <div class='mt-4 text-center'>{@render link('login', uiM('login_submit'), loginUrl)}</div>
179
179
  {:else}
180
180
  {#if notice}<Alert variant='success' class='mb-4'>{uiM(notice)}</Alert>{/if}
181
- {#if verifying}<p role='status' class='mb-4 flex items-center gap-2 text-sm'><Spinner size='sm' />{uiM('auth_captcha_verifying')}</p>{/if}
181
+ <span role='status' class='sr-only'>{verifying ? uiM('auth_captcha_verifying') : ''}</span>
182
182
  {#if mode === 'login'}
183
- <LoginForm {columns} {labelPosition} {labelWidth} {methods} {loading} {errors} header={loginHeader} extraFields={loginFields} showForgotPassword={config.passwordReset.enabled} {forgotPasswordUrl}
183
+ <LoginForm {initialIdentifier} submitText={verifying ? uiM('auth_captcha_verifying') : undefined} {columns} {labelPosition} {labelWidth} {methods} {loading} {errors} header={loginHeader} extraFields={loginFields} showForgotPassword={config.passwordReset.enabled} {forgotPasswordUrl}
184
184
  onforgotpassword={forgotPasswordUrl ? undefined : () => switchMode('forgot')}
185
185
  otpLength={config.otp.length} resendInterval={config.otp.resendInterval} onsendotp={identifier => withCaptcha('sendOtp', captcha => actions.sendOtp(identifier, { captcha }))}
186
186
  agreements={config.agreements.showOnLogin ? config.agreements : undefined}
@@ -194,7 +194,7 @@
194
194
  {/snippet}
195
195
  </LoginForm>
196
196
  {:else if mode === 'register'}
197
- <RegisterForm {columns} {labelPosition} {labelWidth} {loading} {errors} header={registerHeader} extraFields={registerFields} fields={config.passwordReset.mode === 'phone' ? ['username', 'phone', 'password'] : ['username', 'email', 'password']} passwordPolicy={config.password} minPasswordLength={config.password.minLength}
197
+ <RegisterForm submitText={verifying ? uiM('auth_captcha_verifying') : undefined} {columns} {labelPosition} {labelWidth} {loading} {errors} header={registerHeader} extraFields={registerFields} fields={config.passwordReset.mode === 'phone' ? ['username', 'phone', 'password'] : ['username', 'email', 'password']} passwordPolicy={config.password} minPasswordLength={config.password.minLength}
198
198
  agreements={config.agreements.showOnRegister ? config.agreements : undefined} onsubmit={data => run(() => withCaptcha('register', captcha => actions.register({ username: data.username || '', password: data.password, email: data.email, phone: data.phone, displayName: data.nickname, captcha })), true)}>
199
199
  {#snippet footer()}
200
200
  {#if registerFooter}{@render registerFooter()}{/if}
@@ -202,7 +202,7 @@
202
202
  {/snippet}
203
203
  </RegisterForm>
204
204
  {:else if mode === 'forgot'}
205
- <ForgotPasswordForm {columns} {labelPosition} {labelWidth} {loading} {errors} mode={config.passwordReset.mode ?? 'email'} onsubmit={data => run(() => withCaptcha('passwordReset', captcha => actions.requestPasswordReset(data.email || data.phone || '', { captcha })), false, 'auth_reset_sent')}>
205
+ <ForgotPasswordForm submitText={verifying ? uiM('auth_captcha_verifying') : undefined} {columns} {labelPosition} {labelWidth} {loading} {errors} mode={config.passwordReset.mode ?? 'email'} onsubmit={data => run(() => withCaptcha('passwordReset', captcha => actions.requestPasswordReset(data.email || data.phone || '', { captcha })), false, 'auth_reset_sent')}>
206
206
  {#snippet footer()}<div class='flex justify-between gap-3'>{@render link('login', uiM('login_submit'), loginUrl)}{@render link('reset', uiM('auth_have_token'))}</div>{/snippet}
207
207
  </ForgotPasswordForm>
208
208
  {:else if mode === 'renew'}
@@ -211,7 +211,7 @@
211
211
  <Input id='renew-identifier' autocomplete='username' bind:value={renewalIdentifier} disabled={loading} required />
212
212
  </FormField>
213
213
  </div>
214
- <ChangePasswordForm {columns} {labelPosition} {labelWidth} {loading} {errors} disabled={!renewalIdentifier.trim()} passwordPolicy={config.password} minPasswordLength={config.password.minLength}
214
+ <ChangePasswordForm submitText={verifying ? uiM('auth_captcha_verifying') : undefined} {columns} {labelPosition} {labelWidth} {loading} {errors} disabled={!renewalIdentifier.trim()} passwordPolicy={config.password} minPasswordLength={config.password.minLength}
215
215
  onsubmit={data => renewPassword(data.oldPassword || '', data.newPassword)} />
216
216
  <div class='mt-4 text-center'>{@render link('login', uiM('login_submit'), loginUrl)}</div>
217
217
  {:else}
@@ -25,6 +25,7 @@
25
25
  const {
26
26
  variant = 'card',
27
27
  title = '',
28
+ embedded = false,
28
29
  subtitle = '',
29
30
  brandTitle = '',
30
31
  brandText = '',
@@ -42,6 +43,8 @@
42
43
  }: {
43
44
  /** 布局形态:'card'(居中卡片,默认)或 'split'(左右分栏) */
44
45
  variant?: 'card' | 'split'
46
+ /** 嵌入已有弹窗/布局,只渲染表单内容。 */
47
+ embedded?: boolean
45
48
  /** 表单区标题 */
46
49
  title?: string
47
50
  /** 表单区副标题 */
@@ -96,7 +99,9 @@
96
99
  </div>
97
100
  {/snippet}
98
101
 
99
- {#if isSplit}
102
+ {#if embedded}
103
+ <div {...dataAttributes} class={className}>{#if children}{@render children()}{/if}</div>
104
+ {:else if isSplit}
100
105
  <div class={cn('grid min-h-screen lg:grid-cols-2', className)}>
101
106
  <!-- 品牌区 -->
102
107
  <div class='relative hidden overflow-hidden bg-primary p-10 text-primary-content lg:flex'>
@@ -3,6 +3,8 @@ import type { DataAttributes } from '../../../types.js';
3
3
  type $$ComponentProps = {
4
4
  /** 布局形态:'card'(居中卡片,默认)或 'split'(左右分栏) */
5
5
  variant?: 'card' | 'split';
6
+ /** 嵌入已有弹窗/布局,只渲染表单内容。 */
7
+ embedded?: boolean;
6
8
  /** 表单区标题 */
7
9
  title?: string;
8
10
  /** 表单区副标题 */
@@ -150,7 +150,7 @@
150
150
  <Button
151
151
  type='submit'
152
152
  variant='primary'
153
- class='w-full sm:w-auto sm:min-w-40'
153
+ class='disabled:text-base-content/70 w-full sm:w-auto sm:min-w-40'
154
154
  disabled={loading || disabled || !canSubmit || Boolean(policyError)}
155
155
  {loading}
156
156
  >
@@ -156,7 +156,7 @@
156
156
  variant='primary'
157
157
  {loading}
158
158
  disabled={loading || disabled}
159
- class='w-full'
159
+ class='disabled:text-base-content/70 w-full'
160
160
  >
161
161
  {submitText || uiM('forgot_password_submit')}
162
162
  </Button>
@@ -16,6 +16,7 @@
16
16
  import type { HaiError } from '@h-ai/core'
17
17
  import type { DataAttributes } from '../../../types.js'
18
18
  import type { AuthLoginMethod, LoginFormData, LoginFormProps } from '../types.js'
19
+ import { untrack } from 'svelte'
19
20
  import { uiM } from '../../../messages.js'
20
21
  import { cn, getDataAttributes } from '../../../utils.js'
21
22
  import Alert from '../../compounds/Alert.svelte'
@@ -30,6 +31,7 @@
30
31
 
31
32
  const {
32
33
  methods = ['password'],
34
+ initialIdentifier = '',
33
35
  otpLength = 6,
34
36
  resendInterval = 60,
35
37
  onsendotp,
@@ -57,7 +59,7 @@
57
59
 
58
60
  const dataAttributes = $derived(getDataAttributes(restProps))
59
61
 
60
- let username = $state('')
62
+ let username = $state(untrack(() => initialIdentifier))
61
63
  let password = $state('')
62
64
  let selectedMethod = $state<AuthLoginMethod>('password')
63
65
  const method = $derived(methods.includes(selectedMethod) ? selectedMethod : methods[0])
@@ -245,7 +247,7 @@
245
247
  variant='primary'
246
248
  {loading}
247
249
  disabled={loading || disabled || !method}
248
- class='w-full'
250
+ class='disabled:text-base-content/70 w-full'
249
251
  >
250
252
  {submitText || uiM('login_submit')}
251
253
  </Button>
@@ -261,7 +261,7 @@
261
261
  <Button
262
262
  type='submit'
263
263
  variant='primary'
264
- class='w-full'
264
+ class='disabled:text-base-content/70 w-full'
265
265
  disabled={loading || disabled || !passwordsMatch || Boolean(policyError)}
266
266
  loading={loading}
267
267
  >
@@ -0,0 +1,70 @@
1
+ <!--
2
+ @component 编辑权限关联的敏感操作 ID;只处理表单,持久化和授权由宿主负责。
3
+ @example
4
+ ```ts
5
+ import { mount, unmount } from 'svelte'
6
+ import { ok } from '@h-ai/core'
7
+ import { SensitiveOperationsForm } from '@h-ai/ui'
8
+ const component = mount(SensitiveOperationsForm, { target: document.body, props: { operations: ['orders.approve'], onsubmit: async () => ok(undefined) } })
9
+ await unmount(component)
10
+ ```
11
+ -->
12
+ <script lang='ts'>
13
+ import type { HaiResult } from '@h-ai/core'
14
+ import type { DataAttributes } from '../../../types.js'
15
+ import { onDestroy, untrack } from 'svelte'
16
+ import { uiM } from '../../../messages.js'
17
+ import { getDataAttributes } from '../../../utils.js'
18
+ import Button from '../../primitives/Button.svelte'
19
+ import Textarea from '../../primitives/Textarea.svelte'
20
+
21
+ const { operations, onsubmit, ondone, ...restProps }: {
22
+ operations: readonly string[]
23
+ onsubmit: (operations: string[]) => Promise<HaiResult<unknown>>
24
+ ondone?: () => void
25
+ } & DataAttributes = $props()
26
+ const dataAttributes = $derived(getDataAttributes(restProps))
27
+ let value = $state(untrack(() => operations.join('\n')))
28
+ let loading = $state(false)
29
+ let error = $state('')
30
+ let disposed = false
31
+ onDestroy(() => {
32
+ disposed = true
33
+ })
34
+
35
+ async function save(event: SubmitEvent): Promise<void> {
36
+ event.preventDefault()
37
+ if (loading)
38
+ return
39
+ const items = [...new Set(value.split(/\r?\n/).map(item => item.trim()).filter(Boolean))]
40
+ if (items.length > 1000 || items.some(item => item.length > 128)) {
41
+ error = uiM('sensitive_operations_invalid')
42
+ return
43
+ }
44
+ loading = true
45
+ error = ''
46
+ try {
47
+ const result = await onsubmit(items)
48
+ if (!result.success)
49
+ error = result.error.message
50
+ else if (!disposed)
51
+ ondone?.()
52
+ }
53
+ catch {
54
+ error = uiM('auth_network_error')
55
+ }
56
+ finally {
57
+ loading = false
58
+ }
59
+ }
60
+ </script>
61
+
62
+ <form data-testid='sensitive-operations-form' {...dataAttributes} class='space-y-4' onsubmit={save}>
63
+ <label class='block space-y-2 text-sm font-medium'>
64
+ <span>{uiM('sensitive_operations_label')}</span>
65
+ <Textarea bind:value rows={6} disabled={loading} aria-label={uiM('sensitive_operations_label')} />
66
+ </label>
67
+ <p class='text-sm text-base-content/60'>{uiM('sensitive_operations_hint')}</p>
68
+ {#if error}<p role='alert' class='text-sm text-error'>{error}</p>{/if}
69
+ <div class='flex justify-end'><Button type='submit' variant='primary' {loading}>{uiM('crud_save')}</Button></div>
70
+ </form>
@@ -0,0 +1,21 @@
1
+ import type { HaiResult } from '@h-ai/core';
2
+ import type { DataAttributes } from '../../../types.js';
3
+ type $$ComponentProps = {
4
+ operations: readonly string[];
5
+ onsubmit: (operations: string[]) => Promise<HaiResult<unknown>>;
6
+ ondone?: () => void;
7
+ } & DataAttributes;
8
+ /**
9
+ * 编辑权限关联的敏感操作 ID;只处理表单,持久化和授权由宿主负责。
10
+ * @example
11
+ * ```ts
12
+ * import { mount, unmount } from 'svelte'
13
+ * import { ok } from '@h-ai/core'
14
+ * import { SensitiveOperationsForm } from '@h-ai/ui'
15
+ * const component = mount(SensitiveOperationsForm, { target: document.body, props: { operations: ['orders.approve'], onsubmit: async () => ok(undefined) } })
16
+ * await unmount(component)
17
+ * ```
18
+ */
19
+ declare const SensitiveOperationsForm: import("svelte").Component<$$ComponentProps, {}, "">;
20
+ type SensitiveOperationsForm = ReturnType<typeof SensitiveOperationsForm>;
21
+ export default SensitiveOperationsForm;
@@ -0,0 +1,64 @@
1
+ <!--
2
+ @component SessionRecoveryDialog 原地恢复已失效会话,复用正常认证、验证码、锁定与改密流程。
3
+ @example
4
+ ```ts
5
+ import { mount, unmount } from 'svelte'
6
+ import { createSessionRecovery, SessionRecoveryDialog } from '@h-ai/ui'
7
+ import { kit } from '@h-ai/kit'
8
+ const recovery = createSessionRecovery()
9
+ const component = mount(SessionRecoveryDialog, { target: document.body, props: { recovery, actions: kit.client.createAuthActions() } })
10
+ await unmount(component)
11
+ ```
12
+ -->
13
+ <script lang='ts'>
14
+ import type { DataAttributes } from '../../../types.js'
15
+ import type { AuthPanelActions } from '../types.js'
16
+ import type { SessionRecovery } from './session-recovery.svelte.js'
17
+ import { err, HaiCommonError } from '@h-ai/core'
18
+ import { uiM } from '../../../messages.js'
19
+ import { getDataAttributes } from '../../../utils.js'
20
+ import Modal from '../../compounds/Modal.svelte'
21
+ import Button from '../../primitives/Button.svelte'
22
+ import AuthPanel from './AuthPanel.svelte'
23
+
24
+ const { recovery, actions, ...restProps }: { recovery: SessionRecovery, actions: AuthPanelActions } & DataAttributes = $props()
25
+ const dataAttributes = $derived(getDataAttributes(restProps))
26
+ let authenticating = $state(false)
27
+ let authenticatedId = ''
28
+ let authenticatedVersion = 0
29
+ const recoveryActions = $derived({
30
+ ...actions,
31
+ login: async (input: Parameters<AuthPanelActions['login']>[0]) => {
32
+ const expectedUserId = recovery.user?.id
33
+ const version = recovery.version
34
+ if (!expectedUserId || !recovery.open)
35
+ return err(HaiCommonError.UNAUTHORIZED, uiM('session_recovery_account_error'))
36
+ authenticating = true
37
+ try {
38
+ const result = await actions.login({ ...input, expectedUserId })
39
+ if (result.success) {
40
+ const data = result.data
41
+ if (!data || typeof data !== 'object' || !('user' in data) || !data.user || typeof data.user !== 'object' || !('id' in data.user) || data.user.id !== expectedUserId)
42
+ return err(HaiCommonError.UNAUTHORIZED, uiM('session_recovery_account_error'))
43
+ authenticatedId = expectedUserId
44
+ authenticatedVersion = version
45
+ }
46
+ return result
47
+ }
48
+ finally { authenticating = false }
49
+ },
50
+ })
51
+ </script>
52
+
53
+ <Modal {...dataAttributes} open={recovery.open} title={uiM('session_recovery_title')} onclose={() => recovery.cancel()} closeOnBackdrop={!authenticating} closeOnEscape={!authenticating} showClose={!authenticating} size='md'>
54
+ {#if recovery.open}
55
+ <div data-testid='session-recovery-dialog'>
56
+ <p class='mb-4 text-sm text-base-content/60'>{uiM('session_recovery_hint')}</p>
57
+ {#if recovery.user?.username}<p class='mb-4 text-sm font-medium'>{recovery.user.username}</p>{/if}
58
+ {#if recovery.config}
59
+ <AuthPanel embedded initialIdentifier={recovery.user?.username} config={{ ...recovery.config, register: { enabled: false } }} actions={recoveryActions} onauthenticated={() => recovery.complete(authenticatedId, authenticatedVersion)} />
60
+ {/if}
61
+ <div class='mt-4 flex justify-end'><Button variant='ghost' disabled={authenticating} onclick={() => recovery.cancel()}>{uiM('session_recovery_later')}</Button></div>
62
+ </div>
63
+ {/if}
64
+ </Modal>
@@ -0,0 +1,22 @@
1
+ import type { DataAttributes } from '../../../types.js';
2
+ import type { AuthPanelActions } from '../types.js';
3
+ import type { SessionRecovery } from './session-recovery.svelte.js';
4
+ type $$ComponentProps = {
5
+ recovery: SessionRecovery;
6
+ actions: AuthPanelActions;
7
+ } & DataAttributes;
8
+ /**
9
+ * SessionRecoveryDialog 原地恢复已失效会话,复用正常认证、验证码、锁定与改密流程。
10
+ * @example
11
+ * ```ts
12
+ * import { mount, unmount } from 'svelte'
13
+ * import { createSessionRecovery, SessionRecoveryDialog } from '@h-ai/ui'
14
+ * import { kit } from '@h-ai/kit'
15
+ * const recovery = createSessionRecovery()
16
+ * const component = mount(SessionRecoveryDialog, { target: document.body, props: { recovery, actions: kit.client.createAuthActions() } })
17
+ * await unmount(component)
18
+ * ```
19
+ */
20
+ declare const SessionRecoveryDialog: import("svelte").Component<$$ComponentProps, {}, "">;
21
+ type SessionRecoveryDialog = ReturnType<typeof SessionRecoveryDialog>;
22
+ export default SessionRecoveryDialog;
@@ -16,4 +16,10 @@ export type { PermissionContext } from './permission-context.svelte.js';
16
16
  export { default as ReauthenticationDialog } from './ReauthenticationDialog.svelte';
17
17
  export { default as RegisterForm } from './RegisterForm.svelte';
18
18
  export { default as ResetPasswordForm } from './ResetPasswordForm.svelte';
19
+ export { createSensitiveActions } from './sensitive-actions.svelte.js';
20
+ export type { SensitiveActions, SensitiveActionsOptions } from './sensitive-actions.svelte.js';
21
+ export { default as SensitiveOperationsForm } from './SensitiveOperationsForm.svelte';
22
+ export { createSessionRecovery } from './session-recovery.svelte.js';
23
+ export type { SessionRecovery } from './session-recovery.svelte.js';
24
+ export { default as SessionRecoveryDialog } from './SessionRecoveryDialog.svelte';
19
25
  export { default as UserProfile } from './UserProfile.svelte';
@@ -17,5 +17,9 @@ export { matchPermission, setPermissionContext, usePermission, } from './permiss
17
17
  export { default as ReauthenticationDialog } from './ReauthenticationDialog.svelte';
18
18
  export { default as RegisterForm } from './RegisterForm.svelte';
19
19
  export { default as ResetPasswordForm } from './ResetPasswordForm.svelte';
20
+ export { createSensitiveActions } from './sensitive-actions.svelte.js';
21
+ export { default as SensitiveOperationsForm } from './SensitiveOperationsForm.svelte';
22
+ export { createSessionRecovery } from './session-recovery.svelte.js';
23
+ export { default as SessionRecoveryDialog } from './SessionRecoveryDialog.svelte';
20
24
  // 用户信息
21
25
  export { default as UserProfile } from './UserProfile.svelte';
@@ -0,0 +1,68 @@
1
+ /** 敏感操作密码确认的页面级状态;网络传输及业务动作仍由宿主提供。 */
2
+ import type { HaiResult } from '@h-ai/core';
3
+ /**
4
+ * 二次认证动作;直接接受 Kit/API client 的 createAuthActions() 返回值。
5
+ * @example
6
+ * ```ts
7
+ * import type { SensitiveActionsOptions } from '@h-ai/ui'
8
+ * import { kit } from '@h-ai/kit'
9
+ * const options: SensitiveActionsOptions = kit.client.createAuthActions()
10
+ * ```
11
+ */
12
+ export interface SensitiveActionsOptions {
13
+ /** 验证当前账号密码,取得仅供指定操作使用的短期单次凭据。 */
14
+ reauthenticate: (password: string, operation: string) => Promise<HaiResult<{
15
+ ticket: string;
16
+ }>>;
17
+ /** 标准动作可提供实时公开策略,权限表变更无需等待重新加载页面。 */
18
+ publicConfig?: () => Promise<HaiResult<{
19
+ reauthentication?: {
20
+ enabled: boolean;
21
+ operations: string[];
22
+ };
23
+ } | null>>;
24
+ }
25
+ /**
26
+ * 绑定 ReauthenticationDialog 的状态与动作;每个应用根布局创建一份。
27
+ * @example
28
+ * ```ts
29
+ * import { createSensitiveActions } from '@h-ai/ui'
30
+ * import { kit } from '@h-ai/kit'
31
+ * const confirmation = createSensitiveActions(kit.client.createAuthActions())
32
+ * confirmation.configure({ enabled: true, operations: ['orders.approve'] })
33
+ * confirmation.cancel()
34
+ * ```
35
+ */
36
+ export interface SensitiveActions {
37
+ readonly open: boolean;
38
+ readonly loading: boolean;
39
+ readonly error: string;
40
+ /** 设置服务端公开策略;撤销当前操作时取消待确认动作。 */
41
+ configure: (policy: {
42
+ enabled: boolean;
43
+ operations: readonly string[];
44
+ }) => void;
45
+ /** undefined 表示无需确认,null 表示取消/忙,字符串为本次操作证明。 */
46
+ authorize: (operation: string) => Promise<string | null | undefined>;
47
+ /** 提交当前密码;错误在弹窗内显示,重复点击不会重复请求。 */
48
+ submit: (password: string) => Promise<void>;
49
+ /** 关闭弹窗或布局卸载时调用;迟到响应不能放行其他动作。 */
50
+ cancel: () => void;
51
+ }
52
+ /**
53
+ * 创建可跨业务复用的敏感动作确认状态,与 ReauthenticationDialog 配套。
54
+ * 密码不写入状态或存储;证明仅返回给 authorize 的对应调用者,不设置全局请求头。
55
+ * @param options - Kit/API client 的标准认证动作,或同签名自定义动作。
56
+ * @returns 页面级确认控制器;业务授权和凭据消费始终由服务端执行。
57
+ * @example
58
+ * ```ts
59
+ * import { createSensitiveActions } from '@h-ai/ui'
60
+ * import { kit } from '@h-ai/kit'
61
+ * const confirmation = createSensitiveActions(kit.client.createAuthActions())
62
+ * confirmation.configure({ enabled: false, operations: [] })
63
+ * const ticket = await confirmation.authorize('orders.approve')
64
+ * // null 时中止;有 ticket 时仅传给这一笔请求。
65
+ * void ticket
66
+ * ```
67
+ */
68
+ export declare function createSensitiveActions(options: SensitiveActionsOptions): SensitiveActions;
@@ -0,0 +1,100 @@
1
+ import { untrack } from 'svelte';
2
+ import { uiM } from '../../../messages.js';
3
+ /**
4
+ * 创建可跨业务复用的敏感动作确认状态,与 ReauthenticationDialog 配套。
5
+ * 密码不写入状态或存储;证明仅返回给 authorize 的对应调用者,不设置全局请求头。
6
+ * @param options - Kit/API client 的标准认证动作,或同签名自定义动作。
7
+ * @returns 页面级确认控制器;业务授权和凭据消费始终由服务端执行。
8
+ * @example
9
+ * ```ts
10
+ * import { createSensitiveActions } from '@h-ai/ui'
11
+ * import { kit } from '@h-ai/kit'
12
+ * const confirmation = createSensitiveActions(kit.client.createAuthActions())
13
+ * confirmation.configure({ enabled: false, operations: [] })
14
+ * const ticket = await confirmation.authorize('orders.approve')
15
+ * // null 时中止;有 ticket 时仅传给这一笔请求。
16
+ * void ticket
17
+ * ```
18
+ */
19
+ export function createSensitiveActions(options) {
20
+ class Confirmation {
21
+ open = $state(false);
22
+ loading = $state(false);
23
+ error = $state('');
24
+ policy = { enabled: false, operations: [] };
25
+ operation = '';
26
+ generation = 0;
27
+ resolve;
28
+ configure(policy) {
29
+ this.policy = { enabled: policy.enabled, operations: [...policy.operations] };
30
+ // configure 通常从宿主 $effect 调用;不要把弹窗状态变成该 effect 的依赖。
31
+ untrack(() => {
32
+ if (this.open && (!policy.enabled || !policy.operations.includes(this.operation)))
33
+ this.cancel();
34
+ });
35
+ }
36
+ async authorize(operation) {
37
+ if (this.open)
38
+ return null;
39
+ if (this.policy.enabled && options.publicConfig) {
40
+ const current = await options.publicConfig();
41
+ if (!current.success || !current.data)
42
+ return null;
43
+ if (current.data.reauthentication)
44
+ this.configure(current.data.reauthentication);
45
+ }
46
+ if (!this.policy.enabled || !this.policy.operations.includes(operation))
47
+ return undefined;
48
+ if (this.open)
49
+ return null;
50
+ this.operation = operation;
51
+ this.generation++;
52
+ this.error = '';
53
+ this.open = true;
54
+ return new Promise((resolve) => {
55
+ this.resolve = resolve;
56
+ });
57
+ }
58
+ async submit(password) {
59
+ if (!this.open || this.loading)
60
+ return;
61
+ this.loading = true;
62
+ this.error = '';
63
+ const operation = this.operation;
64
+ const generation = this.generation;
65
+ const pending = this.resolve;
66
+ try {
67
+ const proof = await options.reauthenticate(password, operation);
68
+ if (generation !== this.generation)
69
+ return;
70
+ if (!proof.success) {
71
+ this.error = proof.error.message;
72
+ return;
73
+ }
74
+ this.resolve = undefined;
75
+ this.operation = '';
76
+ this.open = false;
77
+ pending?.(proof.data.ticket);
78
+ }
79
+ catch {
80
+ if (generation === this.generation)
81
+ this.error = uiM('auth_network_error');
82
+ }
83
+ finally {
84
+ if (generation === this.generation)
85
+ this.loading = false;
86
+ }
87
+ }
88
+ cancel() {
89
+ this.generation++;
90
+ const resolve = this.resolve;
91
+ this.resolve = undefined;
92
+ this.operation = '';
93
+ this.open = false;
94
+ this.loading = false;
95
+ this.error = '';
96
+ resolve?.(null);
97
+ }
98
+ }
99
+ return new Confirmation();
100
+ }
@@ -0,0 +1,44 @@
1
+ /** 会话失效时保留页面,以正常登录流程恢复原主体;不保存密码、请求体或凭据。 */
2
+ import type { AuthPanelConfig } from '../types.js';
3
+ /**
4
+ * 页面级会话恢复控制器;同一时刻多个请求共享一次确认。
5
+ * @example
6
+ * ```ts
7
+ * import { createSessionRecovery, type SessionRecovery } from '@h-ai/ui'
8
+ * const recovery: SessionRecovery = createSessionRecovery()
9
+ * recovery.configure(null)
10
+ * const restored = await recovery.recover()
11
+ * ```
12
+ */
13
+ export interface SessionRecovery {
14
+ readonly open: boolean;
15
+ readonly config: AuthPanelConfig | null;
16
+ readonly user: {
17
+ id: string;
18
+ username?: string;
19
+ } | undefined;
20
+ readonly version: number;
21
+ /** 在应用根布局同步公开配置及当前用户;退出/切换用户时取消原待恢复请求。 */
22
+ configure: (config: AuthPanelConfig | null, user?: {
23
+ id: string;
24
+ username?: string;
25
+ }) => void;
26
+ /** 传给Kit/API client的recoverSession;没有已登录主体时不弹窗。 */
27
+ recover: () => Promise<boolean>;
28
+ /** 仅在限定原userId的正常登录成功后调用。 */
29
+ complete: (userId: string, version: number) => void;
30
+ /** 取消只中止原请求的恢复,不自动清空页面草稿。 */
31
+ cancel: () => void;
32
+ }
33
+ /**
34
+ * 创建与SessionRecoveryDialog配套的页面级恢复控制器,不依赖具体业务路由。
35
+ * @returns 只保留公开配置、原主体及单个等待Promise的控制器。
36
+ * @example
37
+ * ```ts
38
+ * import { createSessionRecovery } from '@h-ai/ui'
39
+ * const recovery = createSessionRecovery()
40
+ * // 布局以 configure(publicConfig, currentUser) 装配;销毁时 cancel()。
41
+ * recovery.cancel()
42
+ * ```
43
+ */
44
+ export declare function createSessionRecovery(): SessionRecovery;
@@ -0,0 +1,57 @@
1
+ import { untrack } from 'svelte';
2
+ /**
3
+ * 创建与SessionRecoveryDialog配套的页面级恢复控制器,不依赖具体业务路由。
4
+ * @returns 只保留公开配置、原主体及单个等待Promise的控制器。
5
+ * @example
6
+ * ```ts
7
+ * import { createSessionRecovery } from '@h-ai/ui'
8
+ * const recovery = createSessionRecovery()
9
+ * // 布局以 configure(publicConfig, currentUser) 装配;销毁时 cancel()。
10
+ * recovery.cancel()
11
+ * ```
12
+ */
13
+ export function createSessionRecovery() {
14
+ class Recovery {
15
+ open = $state(false);
16
+ config = $state(null);
17
+ user = $state();
18
+ pending;
19
+ resolve;
20
+ generation = 0;
21
+ get version() { return this.generation; }
22
+ configure(config, user) {
23
+ untrack(() => {
24
+ if (this.user?.id !== user?.id)
25
+ this.cancel();
26
+ });
27
+ this.config = config;
28
+ this.user = user;
29
+ }
30
+ recover = async () => {
31
+ if (!this.user || !this.config)
32
+ return false;
33
+ if (this.pending)
34
+ return this.pending;
35
+ this.generation++;
36
+ this.open = true;
37
+ this.pending = new Promise((resolve) => {
38
+ this.resolve = resolve;
39
+ });
40
+ return this.pending;
41
+ };
42
+ complete(userId, version) {
43
+ if (this.open && userId === this.user?.id && version === this.generation)
44
+ this.finish(true);
45
+ }
46
+ cancel() { this.finish(false); }
47
+ finish(restored) {
48
+ this.generation++;
49
+ const resolve = this.resolve;
50
+ this.resolve = undefined;
51
+ this.pending = undefined;
52
+ this.open = false;
53
+ resolve?.(restored);
54
+ }
55
+ }
56
+ return new Recovery();
57
+ }
@@ -107,6 +107,8 @@ export interface LoginFormData {
107
107
  * ```
108
108
  */
109
109
  export interface LoginFormProps extends FormLayoutOptions, DataAttributes {
110
+ /** 初始登录标识;原地恢复时预填原用户名,仍走正常鉴别。 */
111
+ initialIdentifier?: string;
110
112
  /** 实际可用的方式;空数组表示无可用登录方式。 */
111
113
  methods?: AuthLoginMethod[];
112
114
  /** 验证码长度 */
@@ -523,6 +525,7 @@ export interface AuthPanelActions {
523
525
  method?: AuthLoginMethod;
524
526
  code?: string;
525
527
  captcha?: string;
528
+ expectedUserId?: string;
526
529
  }) => Promise<HaiResult<unknown>>;
527
530
  /** 注册并登录;禁用新账户的待启用状态由面板单独提示。 */
528
531
  register: (input: {
@@ -580,6 +583,10 @@ export type AuthPanelMode = 'login' | 'register' | 'forgot' | 'reset' | 'renew';
580
583
  * ```
581
584
  */
582
585
  export interface AuthPanelProps extends FormLayoutOptions, DataAttributes {
586
+ /** 嵌入弹窗等已有布局,省略整页背景和重复标题。 */
587
+ embedded?: boolean;
588
+ /** 登录标识初始值;不能替代服务端主体约束。 */
589
+ initialIdentifier?: string;
583
590
  /** 未取得配置时显示加载状态,只消费 IAM 的公开配置。 */
584
591
  config: AuthPanelConfig | null;
585
592
  /** 由 Kit 或 API client 提供标准动作,组件不处理底层传输。 */
@@ -423,6 +423,9 @@
423
423
  "feedback_processing": "Processing status",
424
424
  "feedback_collection": "Collection status",
425
425
  "feedback_notification": "Notification status",
426
+ "feedback_webhook": "Webhook",
427
+ "feedback_business": "Business evidence",
428
+ "feedback_attempts": "Attempts",
426
429
  "feedback_notification_pending": "Notification pending",
427
430
  "feedback_notification_sending": "Sending notification",
428
431
  "feedback_notification_sent": "Accepted by notification channel",
@@ -483,8 +486,15 @@
483
486
  "json_viewer_copied": "Copied",
484
487
  "auth_captcha_error": "Security check is incomplete or unavailable. Try again.",
485
488
  "auth_captcha_verifying": "Verifying security challenge",
486
- "reauthentication_title": "Confirm sensitive action",
487
- "reauthentication_hint": "Enter your current password to continue this action.",
489
+ "reauthentication_title": "Verify your identity again",
490
+ "reauthentication_hint": "You are signed in. Enter this account's password again to continue this sensitive action. Canceling will not submit it.",
488
491
  "reauthentication_password": "Current password",
489
- "reauthentication_confirm": "Verify and continue"
492
+ "reauthentication_confirm": "Verify and continue",
493
+ "session_recovery_title": "Session expired — sign in again",
494
+ "session_recovery_hint": "Your page and input are preserved. Sign in to the same account using the normal controls to continue the rejected operation.",
495
+ "session_recovery_later": "Sign in later",
496
+ "session_recovery_account_error": "Sign in to the original account. The pending action has not continued.",
497
+ "sensitive_operations_label": "Operation IDs requiring reauthentication",
498
+ "sensitive_operations_hint": "One operation ID per line, matching the server guard. Database and file rules are combined. Clearing removes only this permission’s rules. The master switch must be enabled.",
499
+ "sensitive_operations_invalid": "Use at most 1000 operation IDs, each no longer than 128 characters."
490
500
  }
@@ -423,6 +423,9 @@
423
423
  "feedback_processing": "処理状況",
424
424
  "feedback_collection": "収集状況",
425
425
  "feedback_notification": "通知状況",
426
+ "feedback_webhook": "Webhook コールバック",
427
+ "feedback_business": "業務情報",
428
+ "feedback_attempts": "試行回数",
426
429
  "feedback_notification_pending": "通知待ち",
427
430
  "feedback_notification_sending": "送信中",
428
431
  "feedback_notification_sent": "通知チャネルで受理済み",
@@ -483,8 +486,15 @@
483
486
  "json_viewer_copied": "コピーしました",
484
487
  "auth_captcha_error": "セキュリティ確認が未完了または利用できません。再試行してください",
485
488
  "auth_captcha_verifying": "セキュリティ確認中",
486
- "reauthentication_title": "重要な操作の確認",
487
- "reauthentication_hint": "この操作を続けるには現在のパスワードを入力してください。",
489
+ "reauthentication_title": "本人確認を再実行",
490
+ "reauthentication_hint": "現在のアカウントでログイン済みです。この重要な操作を続けるには、同じアカウントのパスワードを再入力してください。キャンセルすると操作は送信されません。",
488
491
  "reauthentication_password": "現在のパスワード",
489
- "reauthentication_confirm": "認証して続行"
492
+ "reauthentication_confirm": "認証して続行",
493
+ "session_recovery_title": "セッションの期限切れ・再ログイン",
494
+ "session_recovery_hint": "ページと入力内容を保持しています。通常の認証で元のアカウントにログインすると、拒否された操作を続けます。",
495
+ "session_recovery_later": "後でログイン",
496
+ "session_recovery_account_error": "元のアカウントでログインしてください。操作はまだ続行していません。",
497
+ "sensitive_operations_label": "再認証が必要な操作 ID",
498
+ "sensitive_operations_hint": "サーバーのガードと一致する操作 ID を1行ずつ入力します。DB とファイルの規則は和集合です。空欄はこの権限の規則だけを削除します。主スイッチが有効な場合に適用されます。",
499
+ "sensitive_operations_invalid": "操作 ID は最大1000件、各128文字以内です。"
490
500
  }
@@ -423,6 +423,9 @@
423
423
  "feedback_processing": "处理状态",
424
424
  "feedback_collection": "采集状态",
425
425
  "feedback_notification": "通知状态",
426
+ "feedback_webhook": "Webhook 回调",
427
+ "feedback_business": "业务信息",
428
+ "feedback_attempts": "尝试次数",
426
429
  "feedback_notification_pending": "等待通知",
427
430
  "feedback_notification_sending": "正在发送",
428
431
  "feedback_notification_sent": "通知通道已受理",
@@ -483,8 +486,15 @@
483
486
  "json_viewer_copied": "已复制",
484
487
  "auth_captcha_error": "安全验证未完成或暂不可用,请重试",
485
488
  "auth_captcha_verifying": "正在进行安全验证",
486
- "reauthentication_title": "确认敏感操作",
487
- "reauthentication_hint": "请输入当前密码以继续本次操作。",
489
+ "reauthentication_title": "二次身份验证",
490
+ "reauthentication_hint": "当前账号已登录。请再次输入当前账号的密码,验证后继续本次敏感操作;取消不会提交操作。",
488
491
  "reauthentication_password": "当前密码",
489
- "reauthentication_confirm": "验证并继续"
492
+ "reauthentication_confirm": "验证并继续",
493
+ "session_recovery_title": "会话已过期,请重新登录",
494
+ "session_recovery_hint": "当前页面和输入已保留。请按正常登录流程验证原账号,成功后继续刚才未提交的操作。",
495
+ "session_recovery_later": "稍后登录",
496
+ "session_recovery_account_error": "请使用原账号完成登录,当前操作尚未继续。",
497
+ "sensitive_operations_label": "需要重新认证的操作 ID",
498
+ "sensitive_operations_hint": "每行一个操作 ID,与服务端守卫一致。数据库与文件配置取并集;清空只移除本权限的规则。主开关关闭时不要求二次认证。",
499
+ "sensitive_operations_invalid": "最多 1000 项,每个操作 ID 不超过 128 字符。"
490
500
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@h-ai/ui",
3
3
  "type": "module",
4
- "version": "0.1.0-alpha.73",
4
+ "version": "0.1.0-alpha.74",
5
5
  "description": "Hai Framework UI component library for Svelte 5 Runes.",
6
6
  "license": "Apache-2.0",
7
7
  "svelte": "./dist/index.js",
@@ -119,7 +119,7 @@
119
119
  "svelte": "^5.57.2"
120
120
  },
121
121
  "dependencies": {
122
- "@h-ai/core": "0.1.0-alpha.73",
122
+ "@h-ai/core": "0.1.0-alpha.74",
123
123
  "@internationalized/date": "^3.12.4",
124
124
  "@rrweb/replay": "^2.1.7",
125
125
  "@shikijs/langs": "^4.5.0",