@h-ai/ui 0.1.0-alpha.72 → 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 (37) hide show
  1. package/README.en.md +43 -3
  2. package/README.ja.md +44 -4
  3. package/README.md +44 -4
  4. package/auto-import.d.ts +3 -0
  5. package/auto-import.js +3 -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 +75 -11
  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/ReauthenticationDialog.svelte +68 -0
  16. package/dist/components/scenes/iam/ReauthenticationDialog.svelte.d.ts +17 -0
  17. package/dist/components/scenes/iam/RegisterForm.svelte +1 -1
  18. package/dist/components/scenes/iam/SensitiveOperationsForm.svelte +70 -0
  19. package/dist/components/scenes/iam/SensitiveOperationsForm.svelte.d.ts +21 -0
  20. package/dist/components/scenes/iam/SessionRecoveryDialog.svelte +64 -0
  21. package/dist/components/scenes/iam/SessionRecoveryDialog.svelte.d.ts +22 -0
  22. package/dist/components/scenes/iam/auth-captcha.d.ts +21 -0
  23. package/dist/components/scenes/iam/auth-captcha.js +23 -0
  24. package/dist/components/scenes/iam/auth-error-message.js +4 -0
  25. package/dist/components/scenes/iam/index.d.ts +7 -0
  26. package/dist/components/scenes/iam/index.js +5 -0
  27. package/dist/components/scenes/iam/password-utils.js +5 -0
  28. package/dist/components/scenes/iam/sensitive-actions.svelte.d.ts +68 -0
  29. package/dist/components/scenes/iam/sensitive-actions.svelte.js +100 -0
  30. package/dist/components/scenes/iam/session-recovery.svelte.d.ts +44 -0
  31. package/dist/components/scenes/iam/session-recovery.svelte.js +57 -0
  32. package/dist/components/scenes/types.d.ts +51 -3
  33. package/dist/messages/en-US.json +19 -1
  34. package/dist/messages/ja-JP.json +19 -1
  35. package/dist/messages/zh-CN.json +19 -1
  36. package/dist/types.d.ts +2 -2
  37. package/package.json +3 -2
@@ -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>
@@ -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;
@@ -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;
@@ -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,13 @@ 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';
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';
18
25
  export { default as UserProfile } from './UserProfile.svelte';
@@ -14,7 +14,12 @@ 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';
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';
19
24
  // 用户信息
20
25
  export { default as UserProfile } from './UserProfile.svelte';
@@ -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
  }
@@ -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;