@h-ai/ui 0.1.0-alpha.71 → 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.
@@ -245,90 +245,92 @@
245
245
  }
246
246
  </script>
247
247
 
248
- <form {...dataAttributes} class={`feedback-form min-w-0 space-y-4 ${className}`} onsubmit={submit} data-feedback-ui='true' data-feedback-ignore='true'>
249
- {#if budget}
250
- <p class='text-xs text-base-content/60'>{uiM('feedback_capacity_hint', { used: (attachments.filter(item => !removedAttachmentIds.includes(item.id)).reduce((sum, item) => sum + (item.size ?? 0), 0) / 1048576).toFixed(1), total: (budget.maxAttachmentsBytes / 1048576).toFixed(1), single: (budget.maxAttachmentBytes / 1048576).toFixed(1), count: budget.maxAttachmentCount })}</p>
251
- {/if}
252
- {#if error}<div class='alert alert-error break-words' role='alert'>{error}</div>{/if}
253
- {#if receipt}
254
- <div role='status' class='alert alert-success block space-y-2 break-words'>
255
- <p class='font-medium'>{uiM('feedback_accepted', { number: receipt.number })}</p>
256
- <p>{collectionLabel(receipt.collectionStatus)}</p>
257
- <p class='text-sm'>{uiM('feedback_accepted_hint')}</p>
258
- </div>
259
- {:else}
260
- <p class='text-sm text-base-content/65'>{labels.description ?? uiM('feedback_quick_hint')}</p>
261
- <FormLayout {columns} {labelPosition} {labelWidth}>
262
- <FormField for={`${instanceId}-description`} label={labels.contentLabel ?? uiM('feedback_optional_description')}>
263
- <Textarea id={`${instanceId}-description`} name='description' class='h-28' maxlength={10000} placeholder={labels.contentPlaceholder ?? uiM('feedback_content_placeholder')} bind:value={description} disabled={loading} />
264
- </FormField>
265
- </FormLayout>
266
- <div class='flex flex-wrap gap-2'>
267
- {#if oncapture}<Button size='sm' variant='outline' disabled={loading || annotating || staging || exporting} onclick={() => oncapture()}>{uiM('feedback_capture_add')}</Button>{/if}
268
- <label class='btn btn-sm btn-ghost focus-within:outline focus-within:outline-primary'>
269
- {uiM('feedback_add_files')}
270
- <BareInput id={`${instanceId}-files`} type='file' aria-label={uiM('feedback_add_files')} accept='.png,.jpg,.jpeg,.webp,.webm,.mp4,.txt,.log,.json,image/png,image/jpeg,image/webp,video/webm,video/mp4,text/plain,application/json' multiple disabled={loading || staging || exporting} class='sr-only' onchange={selectFiles} />
271
- </label>
272
- {#if onfileschange}<FeedbackRecorder maxBytes={recordingBytes} disabled={loading || annotating || staging || exporting || attachmentLimitReached} onactive={recordingChanged} onrecord={recorded} />{/if}
273
- </div>
274
- {#each files as file, index (`${file.name}:${file.lastModified}:${index}`)}
275
- <div class='flex items-center gap-2 min-w-0 text-sm'><span class='min-w-0 flex-1 break-all'>{file.name}</span><Button size='xs' variant='ghost' disabled={loading || staging} ariaLabel={`${uiM('feedback_remove')} ${file.name}`} onclick={() => removeFile(index)}>{uiM('feedback_remove')}</Button></div>
276
- {/each}
277
- {#if onfileschange && filesError}<Button size='sm' loading={staging} onclick={stageFiles}>{uiM('feedback_retry')}</Button>{/if}
278
- {#if visibleAttachments.length}
279
- <section class='space-y-3' aria-label={uiM('feedback_screenshots')}>
280
- {#each visibleAttachments as attachment (attachment.id)}
281
- <div class='rounded-lg border border-base-content/10 p-3 min-w-0 space-y-2'>
282
- <div class='flex items-center justify-between gap-3'>
283
- <span class='min-w-0 text-sm break-all'>{attachment.name}</span>
284
- <div class='flex shrink-0 gap-1'>
285
- {#if oncapture && attachment.mimeType?.startsWith('image/')}<Button size='xs' variant='ghost' disabled={loading || annotating || staging || exporting} onclick={() => oncapture(attachment.id)}>{uiM('feedback_capture_replace')}</Button>{/if}
286
- <Button size='xs' variant='ghost' disabled={loading || annotating || exporting} ariaLabel={`${uiM('feedback_remove')} ${attachment.name}`} onclick={() => removedAttachmentIds = [...removedAttachmentIds, attachment.id]}>{uiM('feedback_remove')}</Button>
287
- </div>
288
- </div>
289
- {#if attachment.mimeType?.startsWith('image/') && attachment.url}<FeedbackScreenshot {attachment} onannotate={!loading && !exporting && !staging && onannotate ? annotate : undefined} />{/if}
290
- {#if attachment.mimeType?.startsWith('video/') && attachment.url}<!-- svelte-ignore a11y_media_has_caption (用户上传的无声录屏) -->
291
- <video src={attachment.url} controls preload='metadata' class='max-w-full rounded' aria-label={attachment.name}></video>{/if}
292
- {#if attachment.missingReason}<p class='text-warning text-sm break-words'>{uiM('feedback_missing')}: {attachment.missingReason}</p>{/if}
293
- </div>
294
- {/each}
295
- </section>
248
+ <form {...dataAttributes} class={`feedback-form flex min-h-0 min-w-0 flex-1 flex-col gap-4 ${className}`} onsubmit={submit} data-feedback-ui='true' data-feedback-ignore='true'>
249
+ <div class='min-h-0 flex-1 space-y-4 overflow-y-auto'>
250
+ {#if budget}
251
+ <p class='text-xs text-base-content/60'>{uiM('feedback_capacity_hint', { used: (attachments.filter(item => !removedAttachmentIds.includes(item.id)).reduce((sum, item) => sum + (item.size ?? 0), 0) / 1048576).toFixed(1), total: (budget.maxAttachmentsBytes / 1048576).toFixed(1), single: (budget.maxAttachmentBytes / 1048576).toFixed(1), count: budget.maxAttachmentCount })}</p>
296
252
  {/if}
297
- <details class='rounded-lg border border-base-content/10 p-3'>
298
- <summary class='cursor-pointer text-sm font-medium'>{uiM('feedback_more')}</summary>
299
- <div class='pt-3 space-y-4'>
300
- <FormLayout {columns} {labelPosition} {labelWidth}>
301
- <FormField for={`${instanceId}-type`} label={labels.typeLabel ?? uiM('feedback_type_label')}><Select id={`${instanceId}-type`} options={typeOptions} bind:value={feedbackType} disabled={loading} /></FormField>
302
- <FormField for={`${instanceId}-contact`} label={labels.contactLabel ?? uiM('feedback_contact_label')}><Input id={`${instanceId}-contact`} placeholder={labels.contactPlaceholder ?? uiM('feedback_contact_placeholder')} bind:value={contact} maxlength={254} autocomplete='email' disabled={loading} /></FormField>
303
- </FormLayout>
253
+ {#if error}<div class='alert alert-error break-words' role='alert'>{error}</div>{/if}
254
+ {#if receipt}
255
+ <div role='status' class='alert alert-success block space-y-2 break-words'>
256
+ <p class='font-medium'>{uiM('feedback_accepted', { number: receipt.number })}</p>
257
+ <p>{collectionLabel(receipt.collectionStatus)}</p>
258
+ <p class='text-sm'>{uiM('feedback_accepted_hint')}</p>
304
259
  </div>
305
- </details>
306
- {#if evidenceSummary.length || evidence.length}
307
- <details class='rounded-lg border border-base-content/10 p-3'>
308
- <summary class='cursor-pointer text-sm font-medium'>{uiM('feedback_materials')}</summary>
309
- <dl class='space-y-2 pt-3 text-sm'>
310
- {#each materialGroups as group (group.label)}
311
- <div class='min-w-0'>
312
- <dt class='font-medium'>{group.label} · {group.items.length}</dt>
313
- <dd class='space-y-2 pt-2'>
314
- {#each group.items as item (item.id)}
315
- <details class='rounded bg-base-200 p-2' ontoggle={event => expandedMaterials = event.currentTarget.open ? [...expandedMaterials, item.id] : expandedMaterials.filter(id => id !== item.id)}>
316
- <summary class='cursor-pointer break-all text-xs'>{feedbackTime(item.timestamp)} · {item.kind} · {item.source} #{item.sequence}</summary>
317
- {#if expandedMaterials.includes(item.id)}<pre class='mt-2 max-h-64 max-w-full overflow-auto whitespace-pre-wrap break-all text-xs'>{evidenceText(item.data)}</pre>{/if}
318
- </details>
319
- {/each}
320
- </dd>
260
+ {:else}
261
+ <p class='text-sm text-base-content/65'>{labels.description ?? uiM('feedback_quick_hint')}</p>
262
+ <FormLayout {columns} {labelPosition} {labelWidth}>
263
+ <FormField for={`${instanceId}-description`} label={labels.contentLabel ?? uiM('feedback_optional_description')}>
264
+ <Textarea id={`${instanceId}-description`} name='description' class='h-28' maxlength={10000} placeholder={labels.contentPlaceholder ?? uiM('feedback_content_placeholder')} bind:value={description} disabled={loading} />
265
+ </FormField>
266
+ </FormLayout>
267
+ <div class='flex flex-wrap gap-2'>
268
+ {#if oncapture}<Button size='sm' variant='outline' disabled={loading || annotating || staging || exporting} onclick={() => oncapture()}>{uiM('feedback_capture_add')}</Button>{/if}
269
+ <label class='btn btn-sm btn-ghost focus-within:outline focus-within:outline-primary'>
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} />
272
+ </label>
273
+ {#if onfileschange}<FeedbackRecorder maxBytes={recordingBytes} disabled={loading || annotating || staging || exporting || attachmentLimitReached} onactive={recordingChanged} onrecord={recorded} />{/if}
274
+ </div>
275
+ {#each files as file, index (`${file.name}:${file.lastModified}:${index}`)}
276
+ <div class='flex items-center gap-2 min-w-0 text-sm'><span class='min-w-0 flex-1 break-all'>{file.name}</span><Button size='xs' variant='ghost' disabled={loading || staging} ariaLabel={`${uiM('feedback_remove')} ${file.name}`} onclick={() => removeFile(index)}>{uiM('feedback_remove')}</Button></div>
277
+ {/each}
278
+ {#if onfileschange && filesError}<Button size='sm' loading={staging} onclick={stageFiles}>{uiM('feedback_retry')}</Button>{/if}
279
+ {#if visibleAttachments.length}
280
+ <section class='space-y-3' aria-label={uiM('feedback_screenshots')}>
281
+ {#each visibleAttachments as attachment (attachment.id)}
282
+ <div class='rounded-lg border border-base-content/10 p-3 min-w-0 space-y-2'>
283
+ <div class='flex items-center justify-between gap-3'>
284
+ <span class='min-w-0 text-sm break-all'>{attachment.name}</span>
285
+ <div class='flex shrink-0 gap-1'>
286
+ {#if oncapture && attachment.mimeType?.startsWith('image/')}<Button size='xs' variant='ghost' disabled={loading || annotating || staging || exporting} onclick={() => oncapture(attachment.id)}>{uiM('feedback_capture_replace')}</Button>{/if}
287
+ <Button size='xs' variant='ghost' disabled={loading || annotating || exporting} ariaLabel={`${uiM('feedback_remove')} ${attachment.name}`} onclick={() => removedAttachmentIds = [...removedAttachmentIds, attachment.id]}>{uiM('feedback_remove')}</Button>
288
+ </div>
289
+ </div>
290
+ {#if attachment.mimeType?.startsWith('image/') && attachment.url}<FeedbackScreenshot {attachment} onannotate={!loading && !exporting && !staging && onannotate ? annotate : undefined} />{/if}
291
+ {#if attachment.mimeType?.startsWith('video/') && attachment.url}<!-- svelte-ignore a11y_media_has_caption (用户上传的无声录屏) -->
292
+ <video src={attachment.url} controls preload='metadata' class='max-w-full rounded' aria-label={attachment.name}></video>{/if}
293
+ {#if attachment.missingReason}<p class='text-warning text-sm break-words'>{uiM('feedback_missing')}: {attachment.missingReason}</p>{/if}
321
294
  </div>
322
295
  {/each}
323
- {#each evidenceSummary as item, index (`${item.label}:${index}`)}
324
- <div class='min-w-0'><dt class='font-medium'>{item.label}{item.count === undefined ? '' : ` · ${item.count}`}</dt><dd class='text-base-content/65 break-words'>{item.status === 'missing' ? uiM('feedback_missing') : item.status === 'not-applicable' ? uiM('feedback_not_applicable') : item.status === 'partial' ? uiM('feedback_partial') : uiM('feedback_complete')}{item.detail ? ` · ${item.detail}` : ''}</dd></div>
325
- {/each}
326
- </dl>
296
+ </section>
297
+ {/if}
298
+ <details class='rounded-lg border border-base-content/10 p-3'>
299
+ <summary class='cursor-pointer text-sm font-medium'>{uiM('feedback_more')}</summary>
300
+ <div class='pt-3 space-y-4'>
301
+ <FormLayout {columns} {labelPosition} {labelWidth}>
302
+ <FormField for={`${instanceId}-type`} label={labels.typeLabel ?? uiM('feedback_type_label')}><Select id={`${instanceId}-type`} options={typeOptions} bind:value={feedbackType} disabled={loading} /></FormField>
303
+ <FormField for={`${instanceId}-contact`} label={labels.contactLabel ?? uiM('feedback_contact_label')}><Input id={`${instanceId}-contact`} placeholder={labels.contactPlaceholder ?? uiM('feedback_contact_placeholder')} bind:value={contact} maxlength={254} autocomplete='email' disabled={loading} /></FormField>
304
+ </FormLayout>
305
+ </div>
327
306
  </details>
307
+ {#if evidenceSummary.length || evidence.length}
308
+ <details class='rounded-lg border border-base-content/10 p-3'>
309
+ <summary class='cursor-pointer text-sm font-medium'>{uiM('feedback_materials')}</summary>
310
+ <dl class='space-y-2 pt-3 text-sm'>
311
+ {#each materialGroups as group (group.label)}
312
+ <div class='min-w-0'>
313
+ <dt class='font-medium'>{group.label} · {group.items.length}</dt>
314
+ <dd class='space-y-2 pt-2'>
315
+ {#each group.items as item (item.id)}
316
+ <details class='rounded bg-base-200 p-2' ontoggle={event => expandedMaterials = event.currentTarget.open ? [...expandedMaterials, item.id] : expandedMaterials.filter(id => id !== item.id)}>
317
+ <summary class='cursor-pointer break-all text-xs'>{feedbackTime(item.timestamp)} · {item.kind} · {item.source} #{item.sequence}</summary>
318
+ {#if expandedMaterials.includes(item.id)}<pre class='mt-2 max-h-64 max-w-full overflow-auto whitespace-pre-wrap break-all text-xs'>{evidenceText(item.data)}</pre>{/if}
319
+ </details>
320
+ {/each}
321
+ </dd>
322
+ </div>
323
+ {/each}
324
+ {#each evidenceSummary as item, index (`${item.label}:${index}`)}
325
+ <div class='min-w-0'><dt class='font-medium'>{item.label}{item.count === undefined ? '' : ` · ${item.count}`}</dt><dd class='text-base-content/65 break-words'>{item.status === 'missing' ? uiM('feedback_missing') : item.status === 'not-applicable' ? uiM('feedback_not_applicable') : item.status === 'partial' ? uiM('feedback_partial') : uiM('feedback_complete')}{item.detail ? ` · ${item.detail}` : ''}</dd></div>
326
+ {/each}
327
+ </dl>
328
+ </details>
329
+ {/if}
328
330
  {/if}
329
- {/if}
330
- {#if exported}<p class='text-sm text-success' role='status'>{uiM('feedback_local_saved')}</p>{/if}
331
- <div class='sticky bottom-0 z-10 flex flex-wrap justify-end gap-2 border-t border-base-content/10 bg-base-100 pt-4 pb-2'>
331
+ {#if exported}<p class='text-sm text-success' role='status'>{uiM('feedback_local_saved')}</p>{/if}
332
+ </div>
333
+ <div class='shrink-0 flex flex-wrap justify-end gap-2 border-t border-base-content/10 bg-base-100 pt-4 pb-2'>
332
334
  {#if onexport}<Button variant='ghost' loading={exporting} disabled={annotating || staging} onclick={saveLocal}>{uiM('feedback_local_export')}</Button>{/if}
333
335
  {#if oncancel}<Button variant='ghost' onclick={oncancel}>{receipt ? uiM('feedback_close') : labels.cancel ?? uiM('feedback_cancel')}</Button>{/if}
334
336
  {#if !receipt}<Button type='submit' variant='primary' loading={loading || staging} disabled={annotating || exporting || recording || Boolean(onfileschange && filesError)}>{labels.submit ?? uiM('feedback_submit')}</Button>{/if}
@@ -112,7 +112,6 @@
112
112
  <p role='alert' class='alert alert-warning'>{uiM('feedback_permission_denied')}</p>
113
113
  {:else}
114
114
  <TableToolbar bind:searchValue={search} {filterFields} bind:filterValues sortableColumns={[{ key: 'createdAt', label: uiM('feedback_created_at') }]} sortBy='createdAt' bind:sortDirection searchPlaceholder={uiM('feedback_search')} onsearch={value => update({ page: 1, search: value || undefined })} onfilterchange={filter} onclearfilters={() => update({ page: 1, status: undefined, collectionStatus: undefined, appId: undefined, appVersion: undefined, from: undefined, to: undefined })} onsort={(_, direction) => update({ page: 1, sortDirection: direction })}>
115
- {#snippet leading()}<h2 class='font-semibold text-lg'>{uiM('feedback_list_title')}</h2>{/snippet}
116
115
  </TableToolbar>
117
116
  {#if error || actionError}<p role='alert' class='alert alert-error break-words'>{error || actionError}</p>{/if}
118
117
  <div class='min-h-0 min-w-0 flex-1 overflow-hidden'>
@@ -74,7 +74,7 @@
74
74
  </div>
75
75
  </aside>
76
76
  {/if}
77
- <Modal {...dataAttributes} bind:open title={formProps.labels?.title ?? uiM('feedback_title')} size='lg' data-feedback-ui='true' data-feedback-ignore='true'>
77
+ <Modal {...dataAttributes} bind:open title={formProps.labels?.title ?? uiM('feedback_title')} size='lg' bodyOverflow='hidden' bodyClass='flex flex-col' data-feedback-ui='true' data-feedback-ignore='true'>
78
78
  <FeedbackForm {...formProps} onrecordingchange={recordingChanged} oncapture={formProps.oncapture ? selectPage : undefined} oncancel={() => {
79
79
  open = false
80
80
  formProps.oncancel?.()
@@ -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
  }