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

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.
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 (40)
296
+ #### Scenes (41)
297
297
 
298
298
  ##### Guide (2)
299
299
 
@@ -320,7 +320,7 @@ Client validation appears on the first blur and updates as invalid input is corr
320
320
 
321
321
  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
322
 
323
- ##### IAM authentication (10)
323
+ ##### IAM authentication (11)
324
324
 
325
325
  | Component | Description | Key props |
326
326
  | -------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
@@ -332,6 +332,7 @@ Descriptions are optional. Call `prepare()` from `@h-ai/feedback/client` before
332
332
  | `ResetPasswordForm` | Reset password | `loading`, `errors`, `showCode`, `onsubmit` |
333
333
  | `ChangePasswordForm` | Change password | `loading`, `errors`, `requireOldPassword`, `onsubmit` |
334
334
  | `PasswordInput` | Password input | `value`, `showToggle`, `showStrength`, `minLength` |
335
+ | `ReauthenticationDialog` | Sensitive action confirmation | `open`, `loading`, `error`, `onsubmit`, `onclose` |
335
336
  | `PermGuard` | Permission guard | `permissions`, `mode`, `fallback` |
336
337
  | `UserProfile` | User profile | `user`, `editable`, `fields`, `avatarAccept`, `avatarHint`, `onsubmit` |
337
338
 
@@ -825,6 +826,8 @@ AuthPanel disables native form controls during SSR and enables input after clien
825
826
 
826
827
  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.
827
828
 
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.
830
+
828
831
  [完整 IAM 配置 / IAM configuration](../iam/README.en.md)
829
832
 
830
833
  ### Onboarding and help center
@@ -935,6 +938,12 @@ HTTP errors expose localized safe messages followed by `(traceId: …)`, with th
935
938
 
936
939
  Use `core.error.toPublic(error, traceId?)` at HTTP/UI boundaries and `core.error.formatMessage(error)` after translating messages; formatting is idempotent. Pass complete Error objects to logs instead of discarding their context. Database failures log driver codes, sanitized messages/stacks and table/column context; SQL text, bound values and connection credentials are excluded.
937
940
 
941
+ ## Optional interactive challenges
942
+
943
+ AuthPanel uses actions.createCaptcha to automatically create and asynchronously solve self-hosted ALTCHA when config.captcha.enabled, submitting one-use proofs for login/register/sendOtp/passwordReset/renewPassword. The solver is not loaded when disabled. createAuthActions supplies the action; custom actions must preserve captcha and missing actions fail closed. Proofs stay in request memory and are always verified/consumed on the server.
944
+
945
+ See policy, defaults and recovery boundaries in [IAM](../iam/README.en.md).
946
+
938
947
  ## Development and testing
939
948
 
940
949
  ```sh
package/README.ja.md CHANGED
@@ -293,7 +293,7 @@ components/
293
293
  | -------------- | -------------- | ---------------------------------------------- |
294
294
  | `PageHeader` | ページヘッダー | `title`, `description`、`actions` スロット対応 |
295
295
 
296
- #### Scenes:用途別コンポーネント(40)
296
+ #### Scenes:用途別コンポーネント(41)
297
297
 
298
298
  ##### Guide:案内・ヘルプ(2)
299
299
 
@@ -320,7 +320,7 @@ components/
320
320
 
321
321
  説明は任意です。モーダルを開く前に `@h-ai/feedback/client` の `prepare()` で現場を固定します。`onfileschange` で添付を準備し、`onannotate` で注釈を画像のピクセルに反映します。送信失敗時は入力を保持し、ローカルに出力できます。一覧は説明またはサーバーの要約を表示し、`onquerychange` でページを取得します。UI の権限表示とは別にサーバーの認可が必要です。接続方法とオフラインツールは [feedback モジュール](../feedback/README.ja.md) を参照してください。
322
322
 
323
- ##### IAM:認証(10)
323
+ ##### IAM:認証(11)
324
324
 
325
325
  | コンポーネント | 説明 | 主なプロパティ |
326
326
  | -------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------ |
@@ -332,6 +332,7 @@ components/
332
332
  | `ResetPasswordForm` | パスワードリセット | `loading`, `errors`, `showCode`, `onsubmit` |
333
333
  | `ChangePasswordForm` | パスワード変更 | `loading`, `errors`, `requireOldPassword`, `onsubmit` |
334
334
  | `PasswordInput` | パスワード入力 | `value`, `showToggle`, `showStrength`, `minLength` |
335
+ | `ReauthenticationDialog` | 機密操作の確認 | `open`, `loading`, `error`, `onsubmit`, `onclose` |
335
336
  | `PermGuard` | 権限ガード | `permissions`, `mode`, `fallback` |
336
337
  | `UserProfile` | ユーザープロフィール | `user`, `editable`, `fields`, `avatarAccept`, `avatarHint`, `onsubmit` |
337
338
 
@@ -825,6 +826,8 @@ AuthPanel は SSR 中のフォーム操作を無効にし、クライアント
825
826
 
826
827
  認証リンクが現在の完全な URL を指す場合、AuthPanel は再ナビゲーションせずに画面だけを切り替え、ログインに戻った直後の入力を保持します。パス、クエリー、hash が異なる場合はアプリのルーターに任せます。Ctrl/Cmd などの修飾キーを使ったクリックはブラウザーの動作を維持します。
827
828
 
829
+ `ReauthenticationDialog` は `open/loading/error/onsubmit/onclose` でパスワード確認を表示します。サービスが `actions.reauthenticate(password, operation)` を呼び、短期・一回限りの証明を対象リクエストだけに渡します。取消・終了・送信で入力を消去し、証明自体は権限を付与しません。`Input` の `datetime-local` はブラウザーのローカル時刻のため、サービスで明確なタイムスタンプへ変換して送信します。
830
+
828
831
  [完整 IAM 配置 / IAM configuration](../iam/README.ja.md)
829
832
 
830
833
  ### 初回ガイドとヘルプセンター
@@ -935,6 +938,12 @@ HTTP エラーはローカライズ済みの安全な表示に `(traceId: …)`
935
938
 
936
939
  HTTP/UI 境界には core.error.toPublic(error, traceId?)、再翻訳後の表示には core.error.formatMessage(error) を使い、ID を重複追加しません。ログには完全な Error を渡してください。DB ログにはドライバーコード、脱機密化したメッセージ・スタック、表・列を残し、SQL 本文、バインド値と接続認証情報を記録しません。
937
940
 
941
+ ## 任意の対話チャレンジ
942
+
943
+ AuthPanel は config.captcha.enabled の場合 actions.createCaptcha で自己ホスト ALTCHA を自動生成・非同期求解し、login/register/sendOtp/passwordReset/renewPassword 用の単用証明を送信します。無効時は求解器を読み込みません。createAuthActions は対応済みで、独自動作は captcha を保持し、不足時は通過しません。証明は現在のメモリ内だけに保持し、サーバーで必ず検証・消費します。
944
+
945
+ 方針・既定値・復旧範囲は次を参照: [IAM](../iam/README.ja.md)。
946
+
938
947
  ## 開発とテスト
939
948
 
940
949
  ```sh
package/README.md CHANGED
@@ -293,7 +293,7 @@ components/
293
293
  | ------------ | -------- | ------------------------------------------- |
294
294
  | `PageHeader` | 页面头部 | `title`, `description`,支持 `actions` 插槽 |
295
295
 
296
- #### 场景组件 Scenes(40 个)
296
+ #### 场景组件 Scenes(41 个)
297
297
 
298
298
  ##### Guide 引导与帮助(2 个)
299
299
 
@@ -320,7 +320,7 @@ components/
320
320
 
321
321
  反馈说明可为空;宿主先用 `@h-ai/feedback/client` 的 `prepare()` 固定现场,再打开弹窗。表单通过 `onfileschange` 准备主动附件、通过 `onannotate` 将标注烧录到图片;受理失败保留输入并可本地导出。列表展示说明或服务端事实摘要,以 `onquerychange` 取得分页数据;界面权限不代替服务端授权。完整接入与离线工具见 [feedback 模块](../feedback/README.md)。
322
322
 
323
- ##### IAM 身份认证(10 个)
323
+ ##### IAM 身份认证(11 个)
324
324
 
325
325
  | 组件 | 描述 | 主要属性 |
326
326
  | -------------------- | ---------- | ----------------------------------------------------- |
@@ -332,6 +332,7 @@ components/
332
332
  | `ResetPasswordForm` | 重置密码 | `loading`, `errors`, `showCode`, `onsubmit` |
333
333
  | `ChangePasswordForm` | 修改密码 | `loading`, `errors`, `requireOldPassword`, `onsubmit` |
334
334
  | `PasswordInput` | 密码输入框 | `value`, `showToggle`, `showStrength`, `minLength` |
335
+ | `ReauthenticationDialog` | 敏感操作再认证 | `open`, `loading`, `error`, `onsubmit`, `onclose` |
335
336
  | `PermGuard` | 权限守卫 | `permissions`, `mode`, `fallback` |
336
337
  | `UserProfile` | 用户资料 | `user`, `editable`, `fields`, `avatarAccept`, `avatarHint`, `onsubmit` |
337
338
 
@@ -841,6 +842,8 @@ AuthPanel 在 SSR 阶段禁用原生表单控件,客户端挂载并绑定事
841
842
 
842
843
  认证链接指向当前完整 URL 时,AuthPanel 只切换场景并阻止重复导航,返回登录后可立即输入。路径、查询串或 hash 不同时交给应用路由处理;Ctrl/Cmd 等修改键点击保留浏览器行为。
843
844
 
845
+ `ReauthenticationDialog` 只展示密码确认框,通过 `open/loading/error/onsubmit/onclose` 接入服务层。服务调用 `actions.reauthenticate(password, operation)`,拿到短期单次凭据后仅传给本次敏感请求;取消、关闭和提交会清除输入,凭据不提升原有权限。`Input` 支持 `datetime-local`,其值为浏览器本地时间,服务层转换为明确时间戳后提交。
846
+
844
847
  [完整 IAM 配置 / IAM configuration](../iam/README.md)
845
848
 
846
849
  ### 新手引导与帮助中心
@@ -938,6 +941,12 @@ HTTP 错误只向用户返回本地化的安全提示,末尾显示 `(traceId:
938
941
 
939
942
  `core.error.toPublic(error, traceId?)` 用于接口/UI 边界;`core.error.formatMessage(error)` 用于重新翻译后的提示,重复调用不会重复追加标识。日志传入完整 Error 对象,不能只记录通用标题或提前 String(error) 丢失上下文。数据库失败记录驱动错误码、消息、堆栈及表/列;SQL 原文、绑定值和连接凭据不进入日志。
940
943
 
944
+ ## 可选交互挑战
945
+
946
+ AuthPanel 在 config.captcha.enabled 时通过 actions.createCaptcha 自动生成并异步求解自托管 ALTCHA,按 login/register/sendOtp/passwordReset/renewPassword 用途提交单用证明;关闭时不加载求解器。createAuthActions 已提供动作,自定义动作须保留 captcha,缺少动作时不放行。证明仅存在当前请求内存,服务端始终校验与消费。
947
+
948
+ 策略、默认值和恢复边界见 [IAM](../iam/README.md)。
949
+
941
950
  ## 开发测试
942
951
 
943
952
  ```sh
package/auto-import.d.ts CHANGED
@@ -101,6 +101,7 @@ declare global {
101
101
  const LoginForm: typeof import('@h-ai/ui')['LoginForm']
102
102
  const PasswordInput: typeof import('@h-ai/ui')['PasswordInput']
103
103
  const PermGuard: typeof import('@h-ai/ui')['PermGuard']
104
+ const ReauthenticationDialog: typeof import('@h-ai/ui')['ReauthenticationDialog']
104
105
  const RegisterForm: typeof import('@h-ai/ui')['RegisterForm']
105
106
  const ResetPasswordForm: typeof import('@h-ai/ui')['ResetPasswordForm']
106
107
  const UserProfile: typeof import('@h-ai/ui')['UserProfile']
package/auto-import.js CHANGED
@@ -92,6 +92,7 @@ const UI_COMPONENTS = new Set([
92
92
  'LoginForm',
93
93
  'PasswordInput',
94
94
  'PermGuard',
95
+ 'ReauthenticationDialog',
95
96
  'RegisterForm',
96
97
  'ResetPasswordForm',
97
98
  'UserProfile',
@@ -26,16 +26,21 @@
26
26
  <script lang='ts'>
27
27
  import type { HaiError, HaiResult } from '@h-ai/core'
28
28
  import type { UIMessageKey } from '../../../messages.js'
29
- import type { AuthLoginMethod, AuthPanelMode, AuthPanelProps } from '../types.js'
29
+ import type { AuthLoginMethod, AuthPanelActions, AuthPanelMode, AuthPanelProps } from '../types.js'
30
+ import { err, HaiCommonError } from '@h-ai/core'
30
31
  import { onMount, untrack } from 'svelte'
31
32
  import { uiM } from '../../../messages.js'
32
33
  import { getDataAttributes } from '../../../utils.js'
33
34
  import Alert from '../../compounds/Alert.svelte'
35
+ import FormField from '../../compounds/FormField.svelte'
34
36
  import BareButton from '../../primitives/BareButton.svelte'
35
37
  import Button from '../../primitives/Button.svelte'
38
+ import Input from '../../primitives/Input.svelte'
36
39
  import Spinner from '../../primitives/Spinner.svelte'
40
+ import { solveAuthCaptcha } from './auth-captcha.js'
37
41
  import { authErrorMessage } from './auth-error-message.js'
38
42
  import AuthShell from './AuthShell.svelte'
43
+ import ChangePasswordForm from './ChangePasswordForm.svelte'
39
44
  import ForgotPasswordForm from './ForgotPasswordForm.svelte'
40
45
  import LoginForm from './LoginForm.svelte'
41
46
  import RegisterForm from './RegisterForm.svelte'
@@ -45,25 +50,60 @@
45
50
  const dataAttributes = $derived(getDataAttributes(restProps))
46
51
  let mode = $state<AuthPanelMode>(untrack(() => initialMode))
47
52
  let loading = $state(false)
53
+ let renewalIdentifier = $state('')
48
54
  let actionError = $state<Pick<HaiError, 'code' | 'message'>>()
49
55
  let networkFailed = $state(false)
50
56
  const errors = $derived<Record<string, string>>(actionError ? { general: authErrorMessage(actionError) } : networkFailed ? { general: uiM('auth_network_error') } : {})
51
57
  let notice = $state<UIMessageKey | ''>('')
52
58
  // SSR 表单先显示但不可编辑;客户端绑定事件后开放输入,避免接管时丢失早到的输入。
53
59
  let interactive = $state(false)
60
+ let verifying = $state(false)
61
+ let captchaController: AbortController | undefined
54
62
  onMount(() => {
55
63
  interactive = true
64
+ return () => captchaController?.abort()
56
65
  })
57
66
  const methods = $derived(config ? (['password', 'ldap', 'email', 'sms'] as AuthLoginMethod[]).filter(method => config.login[method]) : [])
58
- const title = $derived(mode === 'register' ? uiM('register_title') : mode === 'forgot' ? uiM('forgot_password_title') : mode === 'reset' ? uiM('reset_password_title') : uiM('login_title'))
59
- const available = $derived(config && (mode === 'login' || (mode === 'register' ? config.register.enabled : config.passwordReset.enabled)))
67
+ const title = $derived(mode === 'register' ? uiM('register_title') : mode === 'forgot' ? uiM('forgot_password_title') : mode === 'renew' ? uiM('auth_renew_title') : mode === 'reset' ? uiM('reset_password_title') : uiM('login_title'))
68
+ const available = $derived(config && (mode === 'login' || (mode === 'renew' ? Boolean(actions.renewPassword) : mode === 'register' ? config.register.enabled : config.passwordReset.enabled)))
60
69
 
61
70
  function switchMode(next: AuthPanelMode) {
71
+ captchaController?.abort()
62
72
  mode = next
63
73
  actionError = undefined
64
74
  networkFailed = false
65
75
  notice = ''
66
76
  }
77
+ async function withCaptcha<T>(operation: Parameters<NonNullable<AuthPanelActions['createCaptcha']>>[0]['operation'], request: (proof?: string) => Promise<HaiResult<T>>): Promise<HaiResult<T>> {
78
+ if (!config?.captcha?.enabled)
79
+ return request()
80
+ if (!actions.createCaptcha)
81
+ return err(HaiCommonError.SERVICE_UNAVAILABLE, uiM('auth_captcha_error'))
82
+ captchaController?.abort()
83
+ const controller = new AbortController()
84
+ captchaController = controller
85
+ verifying = true
86
+ try {
87
+ const challenge = await actions.createCaptcha({ operation })
88
+ if (!challenge.success)
89
+ return challenge
90
+ controller.signal.throwIfAborted()
91
+ const proof = await solveAuthCaptcha(challenge.data, controller)
92
+ controller.signal.throwIfAborted()
93
+ if (!proof)
94
+ return err(HaiCommonError.SERVICE_UNAVAILABLE, uiM('auth_captcha_error'))
95
+ return request(proof)
96
+ }
97
+ catch {
98
+ return err(HaiCommonError.SERVICE_UNAVAILABLE, uiM('auth_captcha_error'))
99
+ }
100
+ finally {
101
+ if (captchaController === controller) {
102
+ captchaController = undefined
103
+ verifying = false
104
+ }
105
+ }
106
+ }
67
107
  async function run(operation: () => Promise<HaiResult<unknown>>, authenticate = false, successNotice: UIMessageKey | '' = '') {
68
108
  if (loading)
69
109
  return
@@ -80,6 +120,8 @@
80
120
  notice = 'auth_registration_pending'
81
121
  }
82
122
  else {
123
+ if (authenticate && actions.renewPassword && ['hai:iam:007', 'hai:iam:025'].includes(result.error.code))
124
+ mode = 'renew'
83
125
  actionError = result.error
84
126
  }
85
127
  }
@@ -93,6 +135,15 @@
93
135
  catch { networkFailed = true }
94
136
  finally { loading = false }
95
137
  }
138
+
139
+ async function renewPassword(password: string, newPassword: string) {
140
+ const renew = actions.renewPassword
141
+ if (!renew || loading || !renewalIdentifier.trim())
142
+ return
143
+ await run(() => withCaptcha('renewPassword', captcha => renew({ identifier: renewalIdentifier.trim(), password, newPassword, captcha })), false, 'auth_reset_done')
144
+ if (!actionError && !networkFailed)
145
+ mode = 'login'
146
+ }
96
147
  </script>
97
148
 
98
149
  {#snippet link(next: AuthPanelMode, label: string, href?: string)}
@@ -127,12 +178,16 @@
127
178
  <div class='mt-4 text-center'>{@render link('login', uiM('login_submit'), loginUrl)}</div>
128
179
  {:else}
129
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}
130
182
  {#if mode === 'login'}
131
183
  <LoginForm {columns} {labelPosition} {labelWidth} {methods} {loading} {errors} header={loginHeader} extraFields={loginFields} showForgotPassword={config.passwordReset.enabled} {forgotPasswordUrl}
132
184
  onforgotpassword={forgotPasswordUrl ? undefined : () => switchMode('forgot')}
133
- otpLength={config.otp.length} resendInterval={config.otp.resendInterval} onsendotp={actions.sendOtp}
185
+ otpLength={config.otp.length} resendInterval={config.otp.resendInterval} onsendotp={identifier => withCaptcha('sendOtp', captcha => actions.sendOtp(identifier, { captcha }))}
134
186
  agreements={config.agreements.showOnLogin ? config.agreements : undefined}
135
- onsubmit={data => run(() => actions.login({ identifier: data.username, password: data.password, method: data.method, code: data.code }), true)}>
187
+ onsubmit={(data) => {
188
+ renewalIdentifier = data.username
189
+ return run(() => withCaptcha('login', captcha => actions.login({ identifier: data.username, password: data.password, method: data.method, code: data.code, captcha })), true)
190
+ }}>
136
191
  {#snippet footer()}
137
192
  {#if loginFooter}{@render loginFooter()}{/if}
138
193
  {#if config?.register.enabled}<div class='text-center text-sm'>{uiM('login_no_account')} {@render link('register', uiM('login_register_now'), registerUrl)}</div>{/if}
@@ -140,16 +195,25 @@
140
195
  </LoginForm>
141
196
  {:else if mode === 'register'}
142
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}
143
- agreements={config.agreements.showOnRegister ? config.agreements : undefined} onsubmit={data => run(() => actions.register({ username: data.username || '', password: data.password, email: data.email, phone: data.phone, displayName: data.nickname }), true)}>
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)}>
144
199
  {#snippet footer()}
145
200
  {#if registerFooter}{@render registerFooter()}{/if}
146
201
  <div class='text-center'>{@render link('login', uiM('register_login_now'), loginUrl)}</div>
147
202
  {/snippet}
148
203
  </RegisterForm>
149
204
  {:else if mode === 'forgot'}
150
- <ForgotPasswordForm {columns} {labelPosition} {labelWidth} {loading} {errors} mode={config.passwordReset.mode ?? 'email'} onsubmit={data => run(() => actions.requestPasswordReset(data.email || data.phone || ''), false, 'auth_reset_sent')}>
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')}>
151
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}
152
207
  </ForgotPasswordForm>
208
+ {:else if mode === 'renew'}
209
+ <div class='mb-5'>
210
+ <FormField for='renew-identifier' label={uiM('login_username')}>
211
+ <Input id='renew-identifier' autocomplete='username' bind:value={renewalIdentifier} disabled={loading} required />
212
+ </FormField>
213
+ </div>
214
+ <ChangePasswordForm {columns} {labelPosition} {labelWidth} {loading} {errors} disabled={!renewalIdentifier.trim()} passwordPolicy={config.password} minPasswordLength={config.password.minLength}
215
+ onsubmit={data => renewPassword(data.oldPassword || '', data.newPassword)} />
216
+ <div class='mt-4 text-center'>{@render link('login', uiM('login_submit'), loginUrl)}</div>
153
217
  {:else}
154
218
  <ResetPasswordForm {columns} {labelPosition} {labelWidth} {loading} {errors} showCode={!resetToken} passwordPolicy={config.password} minPasswordLength={config.password.minLength}
155
219
  onsubmit={data => run(() => actions.confirmPasswordReset(resetToken || data.code || '', data.newPassword), false, 'auth_reset_done')} />
@@ -0,0 +1,68 @@
1
+ <!--
2
+ @component ReauthenticationDialog
3
+ 敏感操作前重新输入密码;鉴别、操作绑定和凭据使用由宿主服务负责。
4
+ @example
5
+ ```ts
6
+ import { mount, unmount } from 'svelte'
7
+ import { ReauthenticationDialog } from '@h-ai/ui'
8
+ const component = mount(ReauthenticationDialog, { target: document.body, props: { open: true, onsubmit: async (password: string) => { void password }, onclose: () => {} } })
9
+ await unmount(component)
10
+ ```
11
+ -->
12
+ <script lang='ts'>
13
+ import type { DataAttributes } from '../../../types.js'
14
+ import type { ReauthenticationDialogProps } from '../types.js'
15
+ import { uiM } from '../../../messages.js'
16
+ import { getDataAttributes } from '../../../utils.js'
17
+ import Alert from '../../compounds/Alert.svelte'
18
+ import FormField from '../../compounds/FormField.svelte'
19
+ import Modal from '../../compounds/Modal.svelte'
20
+ import Button from '../../primitives/Button.svelte'
21
+ import PasswordInput from './PasswordInput.svelte'
22
+
23
+ const { open, loading = false, error = '', onsubmit, onclose, ...restProps }: ReauthenticationDialogProps & DataAttributes = $props()
24
+ const dataAttributes = $derived(getDataAttributes(restProps))
25
+ const fieldId = $props.id()
26
+ let password = $state('')
27
+ $effect(() => {
28
+ if (!open)
29
+ password = ''
30
+ })
31
+ async function submit(event: SubmitEvent) {
32
+ event.preventDefault()
33
+ try {
34
+ await onsubmit(password)
35
+ }
36
+ finally {
37
+ password = ''
38
+ }
39
+ }
40
+ function close() {
41
+ password = ''
42
+ onclose()
43
+ }
44
+ </script>
45
+
46
+ <div {...dataAttributes} class='reauthentication-layer'>
47
+ <Modal {open} title={uiM('reauthentication_title')} onclose={close} closeOnBackdrop={!loading} closeOnEscape={!loading} showClose={!loading} size='sm'>
48
+ <form class='space-y-4' onsubmit={submit} data-testid='reauthentication-form'>
49
+ <p class='text-sm text-base-content/60'>{uiM('reauthentication_hint')}</p>
50
+ <FormField label={uiM('reauthentication_password')} for={fieldId}>
51
+ <PasswordInput id={fieldId} bind:value={password} autocomplete='current-password' disabled={loading} required data-testid='reauthentication-password' />
52
+ </FormField>
53
+ {#if error}<Alert variant='error'>{error}</Alert>{/if}
54
+ <div class='flex justify-end gap-2'>
55
+ <Button variant='ghost' disabled={loading} onclick={close}>{uiM('confirm_cancel')}</Button>
56
+ <Button type='submit' variant='primary' {loading} disabled={!password}>{uiM('reauthentication_confirm')}</Button>
57
+ </div>
58
+ </form>
59
+ </Modal>
60
+ </div>
61
+
62
+ <style>
63
+ /* 再鉴别可由已打开的业务弹窗触发,必须显示在同层业务弹窗上方。 */
64
+ .reauthentication-layer {
65
+ position: relative;
66
+ z-index: calc(var(--hai-z-modal, 1100) + 1);
67
+ }
68
+ </style>
@@ -0,0 +1,17 @@
1
+ import type { DataAttributes } from '../../../types.js';
2
+ import type { ReauthenticationDialogProps } from '../types.js';
3
+ type $$ComponentProps = ReauthenticationDialogProps & DataAttributes;
4
+ /**
5
+ * ReauthenticationDialog
6
+ * 敏感操作前重新输入密码;鉴别、操作绑定和凭据使用由宿主服务负责。
7
+ * @example
8
+ * ```ts
9
+ * import { mount, unmount } from 'svelte'
10
+ * import { ReauthenticationDialog } from '@h-ai/ui'
11
+ * const component = mount(ReauthenticationDialog, { target: document.body, props: { open: true, onsubmit: async (password: string) => { void password }, onclose: () => {} } })
12
+ * await unmount(component)
13
+ * ```
14
+ */
15
+ declare const ReauthenticationDialog: import("svelte").Component<$$ComponentProps, {}, "">;
16
+ type ReauthenticationDialog = ReturnType<typeof ReauthenticationDialog>;
17
+ export default ReauthenticationDialog;
@@ -0,0 +1,21 @@
1
+ /** 求解逻辑独立于组件渲染;第三方计算能力仅在启用时加载。 */
2
+ import type { Challenge } from 'altcha/lib';
3
+ /**
4
+ * 生成当前请求使用的单次证明;不缓存,不持久化,也不执行网络请求。
5
+ * @param input - 已由认证动作取得的可公开挑战。
6
+ * @param input.id - 服务端签发的挑战编号。
7
+ * @param input.challenge - 原始公开挑战,包含算法参数与签名。
8
+ * @param controller - 当前交互生命周期的取消控制器。
9
+ * @returns 求解成功时返回证明;超过求解期限时返回 null。
10
+ * @throws 取消或底层计算失败时抛错,由组件转换为安全的交互错误。
11
+ * @example 模块内部上下文
12
+ * ```ts
13
+ * async function prove(challenge: Challenge) {
14
+ * return solveAuthCaptcha({ id: 'challenge-id', challenge }, new AbortController())
15
+ * }
16
+ * ```
17
+ */
18
+ export declare function solveAuthCaptcha(input: {
19
+ id: string;
20
+ challenge: Challenge;
21
+ }, controller: AbortController): Promise<string | null>;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * 生成当前请求使用的单次证明;不缓存,不持久化,也不执行网络请求。
3
+ * @param input - 已由认证动作取得的可公开挑战。
4
+ * @param input.id - 服务端签发的挑战编号。
5
+ * @param input.challenge - 原始公开挑战,包含算法参数与签名。
6
+ * @param controller - 当前交互生命周期的取消控制器。
7
+ * @returns 求解成功时返回证明;超过求解期限时返回 null。
8
+ * @throws 取消或底层计算失败时抛错,由组件转换为安全的交互错误。
9
+ * @example 模块内部上下文
10
+ * ```ts
11
+ * async function prove(challenge: Challenge) {
12
+ * return solveAuthCaptcha({ id: 'challenge-id', challenge }, new AbortController())
13
+ * }
14
+ * ```
15
+ */
16
+ export async function solveAuthCaptcha(input, controller) {
17
+ controller.signal.throwIfAborted();
18
+ const { solveChallenge, pbkdf2 } = await import('altcha/lib');
19
+ controller.signal.throwIfAborted();
20
+ const solution = await solveChallenge({ challenge: input.challenge, deriveKey: pbkdf2.deriveKey, controller, timeout: 20000 });
21
+ controller.signal.throwIfAborted();
22
+ return solution ? JSON.stringify({ id: input.id, solution }) : null;
23
+ }
@@ -21,6 +21,10 @@ const messages = {
21
21
  'hai:iam:022': 'auth_error_otp',
22
22
  'hai:iam:023': 'auth_error_busy',
23
23
  'hai:iam:024': 'auth_unavailable',
24
+ 'hai:iam:030': 'auth_captcha_error',
25
+ 'hai:iam:031': 'auth_captcha_error',
26
+ 'hai:iam:032': 'auth_captcha_error',
27
+ 'hai:iam:033': 'auth_captcha_error',
24
28
  'hai:iam:301': 'auth_error_service',
25
29
  'hai:iam:302': 'auth_error_credentials',
26
30
  'hai:iam:303': 'auth_error_service',
@@ -13,6 +13,7 @@ export { default as PasswordInput } from './PasswordInput.svelte';
13
13
  export { default as PermGuard } from './PermGuard.svelte';
14
14
  export { matchPermission, setPermissionContext, usePermission, } from './permission-context.svelte.js';
15
15
  export type { PermissionContext } from './permission-context.svelte.js';
16
+ export { default as ReauthenticationDialog } from './ReauthenticationDialog.svelte';
16
17
  export { default as RegisterForm } from './RegisterForm.svelte';
17
18
  export { default as ResetPasswordForm } from './ResetPasswordForm.svelte';
18
19
  export { default as UserProfile } from './UserProfile.svelte';
@@ -14,6 +14,7 @@ export { default as PasswordInput } from './PasswordInput.svelte';
14
14
  // 权限控制
15
15
  export { default as PermGuard } from './PermGuard.svelte';
16
16
  export { matchPermission, setPermissionContext, usePermission, } from './permission-context.svelte.js';
17
+ export { default as ReauthenticationDialog } from './ReauthenticationDialog.svelte';
17
18
  export { default as RegisterForm } from './RegisterForm.svelte';
18
19
  export { default as ResetPasswordForm } from './ResetPasswordForm.svelte';
19
20
  // 用户信息
@@ -54,6 +54,9 @@ export function passwordPolicyError(password, policy) {
54
54
  return uiM('password_policy_number');
55
55
  if (policy.requireSpecialChar && !/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(password))
56
56
  return uiM('password_policy_special');
57
+ const classes = [/[A-Z]/, /[a-z]/, /\d/, /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/].filter(pattern => pattern.test(password)).length;
58
+ if (classes < (policy.minCharacterClasses ?? 0))
59
+ return uiM('password_policy_classes', { count: policy.minCharacterClasses ?? 0 });
57
60
  return '';
58
61
  }
59
62
  /**
@@ -76,5 +79,7 @@ export function passwordPolicyHint(policy) {
76
79
  requirements.push(uiM('password_policy_number'));
77
80
  if (policy.requireSpecialChar)
78
81
  requirements.push(uiM('password_policy_special'));
82
+ if (policy.minCharacterClasses)
83
+ requirements.push(uiM('password_policy_classes', { count: policy.minCharacterClasses }));
79
84
  return requirements.join(' · ');
80
85
  }
@@ -5,6 +5,7 @@
5
5
  * @module types
6
6
  */
7
7
  import type { HaiResult } from '@h-ai/core';
8
+ import type { Challenge } from 'altcha/lib';
8
9
  import type { Snippet } from 'svelte';
9
10
  import type { DataAttributes, FormLayoutOptions, FormText, InputProps, Size } from '../../types.js';
10
11
  /**
@@ -238,6 +239,21 @@ export interface ChangePasswordFormData {
238
239
  newPassword: string;
239
240
  confirmPassword: string;
240
241
  }
242
+ /**
243
+ * 敏感操作再鉴别对话框属性;宿主只在服务端选定操作前请求密码。
244
+ * @example
245
+ * ```ts
246
+ * import type { ReauthenticationDialogProps } from '@h-ai/ui'
247
+ * const props: ReauthenticationDialogProps = { open: false, onsubmit: async (password) => { void password }, onclose: () => {} }
248
+ * ```
249
+ */
250
+ export interface ReauthenticationDialogProps {
251
+ open: boolean;
252
+ loading?: boolean;
253
+ error?: string;
254
+ onsubmit: (password: string) => void | Promise<void>;
255
+ onclose: () => void;
256
+ }
241
257
  /**
242
258
  * 修改密码表单属性
243
259
  *
@@ -408,6 +424,8 @@ export interface PasswordPolicy {
408
424
  requireLowercase: boolean;
409
425
  requireNumber: boolean;
410
426
  requireSpecialChar: boolean;
427
+ /** 至少满足的字符类别数;0 或未提供时仅应用各项独立要求。 */
428
+ minCharacterClasses?: number;
411
429
  }
412
430
  /**
413
431
  * 仅消费安全公开配置,不能将 iam.config 或连接密钥传入浏览器。
@@ -431,6 +449,9 @@ export interface PasswordPolicy {
431
449
  * ```
432
450
  */
433
451
  export interface AuthPanelConfig {
452
+ captcha?: {
453
+ enabled: boolean;
454
+ };
434
455
  /** 只有已启用且具备运行时依赖的方式才应为 true。 */
435
456
  login: {
436
457
  password: boolean;
@@ -488,12 +509,20 @@ export interface AuthPanelConfig {
488
509
  * ```
489
510
  */
490
511
  export interface AuthPanelActions {
512
+ /** 仅启用交互挑战时需要;动作返回可公开挑战,签名秘密保留在服务端。 */
513
+ createCaptcha?: (input: {
514
+ operation: 'login' | 'register' | 'sendOtp' | 'passwordReset' | 'renewPassword';
515
+ }) => Promise<HaiResult<{
516
+ id: string;
517
+ challenge: Challenge;
518
+ }>>;
491
519
  /** password/ldap 使用 password,email/sms 使用 code;成功后由工厂保存凭证。 */
492
520
  login: (input: {
493
521
  identifier: string;
494
522
  password: string;
495
523
  method?: AuthLoginMethod;
496
524
  code?: string;
525
+ captcha?: string;
497
526
  }) => Promise<HaiResult<unknown>>;
498
527
  /** 注册并登录;禁用新账户的待启用状态由面板单独提示。 */
499
528
  register: (input: {
@@ -502,10 +531,22 @@ export interface AuthPanelActions {
502
531
  email?: string;
503
532
  phone?: string;
504
533
  displayName?: string;
534
+ captcha?: string;
535
+ }) => Promise<HaiResult<unknown>>;
536
+ sendOtp: (identifier: string, options?: {
537
+ captcha?: string;
538
+ }) => Promise<HaiResult<unknown>>;
539
+ requestPasswordReset: (identifier: string, options?: {
540
+ captcha?: string;
505
541
  }) => Promise<HaiResult<unknown>>;
506
- sendOtp: (identifier: string) => Promise<HaiResult<unknown>>;
507
- requestPasswordReset: (identifier: string) => Promise<HaiResult<unknown>>;
508
542
  confirmPasswordReset: (token: string, newPassword: string) => Promise<HaiResult<unknown>>;
543
+ /** 首次或密码过期时,验证原密码并换新;完成后重新登录。 */
544
+ renewPassword?: (input: {
545
+ identifier: string;
546
+ password: string;
547
+ newPassword: string;
548
+ captcha?: string;
549
+ }) => Promise<HaiResult<unknown>>;
509
550
  }
510
551
  /**
511
552
  * AuthPanel 的初始页面;未传独立路由时由组件内部导航。
@@ -516,7 +557,7 @@ export interface AuthPanelActions {
516
557
  * const example: AuthPanelMode = 'login'
517
558
  * ```
518
559
  */
519
- export type AuthPanelMode = 'login' | 'register' | 'forgot' | 'reset';
560
+ export type AuthPanelMode = 'login' | 'register' | 'forgot' | 'reset' | 'renew';
520
561
  /**
521
562
  * 配置驱动认证场景;网络、通知和令牌存储由应用注入 actions。
522
563
  *
@@ -350,6 +350,7 @@
350
350
  "auth_unavailable": "This authentication feature is unavailable.",
351
351
  "auth_reset_sent": "If the account exists, a reset notification has been sent. Check your email or SMS.",
352
352
  "auth_reset_done": "Password reset. Sign in with your new password.",
353
+ "auth_renew_title": "Update your sign-in password",
353
354
  "auth_have_token": "I have a reset token",
354
355
  "auth_brand": "Account center",
355
356
  "password_policy_length": "Use {min}–{max} characters",
@@ -357,6 +358,7 @@
357
358
  "password_policy_lowercase": "Include lowercase letters",
358
359
  "password_policy_number": "Include numbers",
359
360
  "password_policy_special": "Include special characters",
361
+ "password_policy_classes": "Include at least {count} of uppercase, lowercase, numbers and special characters",
360
362
  "guide_welcome": "Welcome",
361
363
  "guide_start": "Start tour",
362
364
  "guide_later": "Remind me later",
@@ -478,5 +480,11 @@
478
480
  "feedback_notification_disabled": "Notifications disabled",
479
481
  "feedback_capacity_hint": "Attachments {used}/{total} MiB · {single} MiB each · up to {count}",
480
482
  "json_viewer_copy": "Copy",
481
- "json_viewer_copied": "Copied"
483
+ "json_viewer_copied": "Copied",
484
+ "auth_captcha_error": "Security check is incomplete or unavailable. Try again.",
485
+ "auth_captcha_verifying": "Verifying security challenge",
486
+ "reauthentication_title": "Confirm sensitive action",
487
+ "reauthentication_hint": "Enter your current password to continue this action.",
488
+ "reauthentication_password": "Current password",
489
+ "reauthentication_confirm": "Verify and continue"
482
490
  }
@@ -350,6 +350,7 @@
350
350
  "auth_unavailable": "この認証機能は利用できません。",
351
351
  "auth_reset_sent": "アカウントが存在する場合、リセット通知を送信しました。メールまたはSMSをご確認ください。",
352
352
  "auth_reset_done": "パスワードをリセットしました。新しいパスワードでログインしてください。",
353
+ "auth_renew_title": "ログインパスワードの更新",
353
354
  "auth_have_token": "リセットトークンを持っています",
354
355
  "auth_brand": "アカウントセンター",
355
356
  "password_policy_length": "{min}~{max}文字で入力",
@@ -357,6 +358,7 @@
357
358
  "password_policy_lowercase": "英小文字を含める",
358
359
  "password_policy_number": "数字を含める",
359
360
  "password_policy_special": "特殊文字を含める",
361
+ "password_policy_classes": "大文字、小文字、数字、特殊文字のうち {count} 種類以上を含める",
360
362
  "guide_welcome": "ようこそ",
361
363
  "guide_start": "ツアーを開始",
362
364
  "guide_later": "後で通知",
@@ -478,5 +480,11 @@
478
480
  "feedback_notification_disabled": "通知は無効です",
479
481
  "feedback_capacity_hint": "添付 {used}/{total} MiB · 各 {single} MiB まで · 最大 {count} 件",
480
482
  "json_viewer_copy": "コピー",
481
- "json_viewer_copied": "コピーしました"
483
+ "json_viewer_copied": "コピーしました",
484
+ "auth_captcha_error": "セキュリティ確認が未完了または利用できません。再試行してください",
485
+ "auth_captcha_verifying": "セキュリティ確認中",
486
+ "reauthentication_title": "重要な操作の確認",
487
+ "reauthentication_hint": "この操作を続けるには現在のパスワードを入力してください。",
488
+ "reauthentication_password": "現在のパスワード",
489
+ "reauthentication_confirm": "認証して続行"
482
490
  }
@@ -350,6 +350,7 @@
350
350
  "auth_unavailable": "此认证功能暂不可用",
351
351
  "auth_reset_sent": "如果账号存在,重置通知已发送,请查看邮箱或短信。",
352
352
  "auth_reset_done": "密码已重置,请使用新密码登录。",
353
+ "auth_renew_title": "更新登录密码",
353
354
  "auth_have_token": "已有重置令牌",
354
355
  "auth_brand": "账号中心",
355
356
  "password_policy_length": "密码长度为 {min}–{max} 个字符",
@@ -357,6 +358,7 @@
357
358
  "password_policy_lowercase": "包含小写字母",
358
359
  "password_policy_number": "包含数字",
359
360
  "password_policy_special": "包含特殊字符",
361
+ "password_policy_classes": "大写、小写、数字、特殊字符中至少满足 {count} 类",
360
362
  "guide_welcome": "欢迎使用",
361
363
  "guide_start": "开始引导",
362
364
  "guide_later": "稍后提醒",
@@ -478,5 +480,11 @@
478
480
  "feedback_notification_disabled": "未启用通知",
479
481
  "feedback_capacity_hint": "附件 {used}/{total} MiB · 单个最多 {single} MiB · 最多 {count} 项",
480
482
  "json_viewer_copy": "复制",
481
- "json_viewer_copied": "已复制"
483
+ "json_viewer_copied": "已复制",
484
+ "auth_captcha_error": "安全验证未完成或暂不可用,请重试",
485
+ "auth_captcha_verifying": "正在进行安全验证",
486
+ "reauthentication_title": "确认敏感操作",
487
+ "reauthentication_hint": "请输入当前密码以继续本次操作。",
488
+ "reauthentication_password": "当前密码",
489
+ "reauthentication_confirm": "验证并继续"
482
490
  }
package/dist/types.d.ts CHANGED
@@ -160,8 +160,8 @@ export interface InputProps extends DataAttributes {
160
160
  value?: string;
161
161
  /** 占位符 */
162
162
  placeholder?: string;
163
- /** 类型 */
164
- type?: 'text' | 'password' | 'email' | 'number' | 'tel' | 'url' | 'search';
163
+ /** 类型;datetime-local 使用浏览器本地时区,服务层应转换为明确的时间戳。 */
164
+ type?: 'text' | 'password' | 'email' | 'number' | 'tel' | 'url' | 'search' | 'datetime-local';
165
165
  /** 尺寸 */
166
166
  size?: Size;
167
167
  /** 是否禁用 */
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.72",
4
+ "version": "0.1.0-alpha.73",
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,10 +119,11 @@
119
119
  "svelte": "^5.57.2"
120
120
  },
121
121
  "dependencies": {
122
- "@h-ai/core": "0.1.0-alpha.72",
122
+ "@h-ai/core": "0.1.0-alpha.73",
123
123
  "@internationalized/date": "^3.12.4",
124
124
  "@rrweb/replay": "^2.1.7",
125
125
  "@shikijs/langs": "^4.5.0",
126
+ "altcha": "^3.5.0",
126
127
  "bits-ui": "^2.19.5",
127
128
  "driver.js": "1.9.0",
128
129
  "html2canvas": "^1.4.1",