@kinetis/vector-ui 0.10.2 → 0.10.3

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 (55) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/app/components/Vx/Action/Dialog.vue +9 -2
  3. package/app/components/Vx/Inbox.vue +10 -3
  4. package/app/components/Vx/Input/Relation.vue +6 -1
  5. package/app/components/Vx/Input/RichText.vue +1 -1
  6. package/app/components/Vx/Input/Upload.vue +5 -3
  7. package/app/components/Vx/Resource/Form.vue +12 -2
  8. package/app/components/Vx/Resource/Table.vue +3 -2
  9. package/app/components/Vx/Widget/Table.vue +10 -4
  10. package/app/composables/useVectorApi.ts +70 -14
  11. package/app/composables/useVectorAuthStore.ts +32 -7
  12. package/app/composables/useVectorForm.ts +6 -2
  13. package/app/composables/useVectorJobs.ts +6 -3
  14. package/app/composables/useVectorResource.ts +6 -2
  15. package/app/composables/useVectorSchema.ts +9 -1
  16. package/app/i18n/ar/actions.ts +1 -0
  17. package/app/i18n/ar/shell.ts +3 -0
  18. package/app/i18n/de/actions.ts +1 -0
  19. package/app/i18n/de/shell.ts +3 -0
  20. package/app/i18n/en/actions.ts +1 -0
  21. package/app/i18n/en/shell.ts +3 -0
  22. package/app/i18n/es/actions.ts +1 -0
  23. package/app/i18n/es/shell.ts +3 -0
  24. package/app/i18n/fr/actions.ts +1 -0
  25. package/app/i18n/fr/shell.ts +3 -0
  26. package/app/i18n/he/actions.ts +1 -0
  27. package/app/i18n/he/shell.ts +3 -0
  28. package/app/i18n/it/actions.ts +1 -0
  29. package/app/i18n/it/shell.ts +3 -0
  30. package/app/i18n/ja/actions.ts +1 -0
  31. package/app/i18n/ja/shell.ts +3 -0
  32. package/app/i18n/ko/actions.ts +1 -0
  33. package/app/i18n/ko/shell.ts +3 -0
  34. package/app/i18n/nl/actions.ts +1 -0
  35. package/app/i18n/nl/shell.ts +3 -0
  36. package/app/i18n/pl/actions.ts +1 -0
  37. package/app/i18n/pl/shell.ts +3 -0
  38. package/app/i18n/pt/actions.ts +1 -0
  39. package/app/i18n/pt/shell.ts +3 -0
  40. package/app/i18n/pt-BR/actions.ts +1 -0
  41. package/app/i18n/pt-BR/shell.ts +3 -0
  42. package/app/i18n/ru/actions.ts +1 -0
  43. package/app/i18n/ru/shell.ts +3 -0
  44. package/app/i18n/tr/actions.ts +1 -0
  45. package/app/i18n/tr/shell.ts +3 -0
  46. package/app/i18n/uk/actions.ts +1 -0
  47. package/app/i18n/uk/shell.ts +3 -0
  48. package/app/i18n/zh-Hans/actions.ts +1 -0
  49. package/app/i18n/zh-Hans/shell.ts +3 -0
  50. package/app/pages/jobs/index.vue +3 -2
  51. package/app/pages/login.vue +9 -3
  52. package/app/pages/settings.vue +4 -3
  53. package/app/utils/internal/paths.ts +12 -0
  54. package/app/utils/internal/violations.ts +26 -0
  55. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,76 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.10.3] - 2026-10-22
11
+
12
+ ### Changed
13
+
14
+ - The file and image inputs, and a rich-text field's image upload, send
15
+ the id of the record they edit in the upload's multipart `record`
16
+ part, which kinetis/vector now requires to upload while editing
17
+ without create permission. `useVectorResource().upload()` takes it as
18
+ an optional argument.
19
+
20
+ ### Fixed
21
+
22
+ - A 401 while impersonating in bearer mode ends the impersonation in the
23
+ signed-in user's own session, renewed with their refresh token, and
24
+ says so, instead of discarding that session and sending them to sign
25
+ in; when it cannot be renewed, the login page says the impersonation
26
+ ran out. The impersonation's expiry no longer forgets the signer's
27
+ refresh token, and a request refused for the impersonation token is
28
+ never repeated as the signer.
29
+ - The jobs list and the settings page say why when they fail to load,
30
+ as the record page does, instead of showing no jobs or "no settings".
31
+ - Several requests refused (401) together, whose shared renewal of the
32
+ session fails, sign the user out once: one trip to the login page
33
+ instead of one per request.
34
+ - The admin refuses a descriptor whose `version` is not the contract it
35
+ reads (4), naming both versions, instead of rendering it as if it were.
36
+ - Following a job no longer adds a listener to the page's abort signal on
37
+ every poll without removing it; a long job's page held one per poll.
38
+ - A request refused (401) for an access token another request has
39
+ already renewed is repeated with the new token instead of renewing the
40
+ session a second time, which spent the new refresh token and could end
41
+ a session that was still good.
42
+ - A relation input whose search fails says why under the input and keeps
43
+ the choices it listed, instead of failing silently with an unhandled
44
+ promise rejection.
45
+ - Opening a notification whose mark-as-read fails says why, instead of
46
+ failing silently with an unhandled promise rejection.
47
+ - A problem+json error without a `detail` shows its `title` instead of
48
+ the request's generic failure message.
49
+ - An entry of a 422 document's `errors` that is not a violation (no
50
+ `path` list of names and indexes, or no `message` text) is ignored by
51
+ the forms, the settings, bulk edit, action dialogs, inline list edits
52
+ and uploads, instead of being read as one: a `null` entry made a form
53
+ or the list's changeset fail without showing anything.
54
+ - A record form shows a server error on a field it does not show — hidden
55
+ by `visibleWhen`, or preset by the relation the form was opened from —
56
+ above the form, under the field's label; it was shown nowhere, and the
57
+ save failed without a reason.
58
+
59
+ ### Security
60
+
61
+ - An action answering `ActionResponse::openUrl()` opens the URL only
62
+ when it is http(s), mailto or relative — the rule a URL cell and a
63
+ rich-text link follow. A `javascript:` or `data:` URL, which an action
64
+ echoing a record's value could return, is no longer opened.
65
+ - A notification's link is followed only when it is a path of the
66
+ admin, the rule the sign-in page's `redirect` follows; `//host`,
67
+ `/\host` and a URL with a scheme are not.
68
+ - The sign-in page's `redirect`, and a notification's link, are refused
69
+ when they hold a backslash, whitespace or a control character anywhere:
70
+ a browser strips tab, CR and LF from a URL, so `/<tab>/host` was
71
+ followed as `//host`, another origin.
72
+ - A dashboard table widget's row opens its `_link` only when it is a path
73
+ of the admin, by the same rule, and a row whose link is not is not
74
+ offered as a link; a failed navigation is reported instead of
75
+ rejecting unhandled.
76
+ - An action answering `ActionResponse::redirect()` is followed only when
77
+ its URL is a path of the admin, checked before the dialog reports the
78
+ action done; any other URL, or none, is reported and not followed.
79
+
10
80
  ## [0.10.2] - 2026-10-21
11
81
 
12
82
  ### Fixed
@@ -1,6 +1,7 @@
1
1
  <script setup lang="ts">
2
2
  import type { SubmitEventPromise } from 'vuetify'
3
3
  import type { VectorAction, VectorResource, VectorSelection } from '#vector/app/types/vector'
4
+ import { isAdminPath } from '#vector/app/utils/internal/paths'
4
5
 
5
6
  // Runs one action: the confirmation, the dialog's fields, the request,
6
7
  // and what the response asks the client to do.
@@ -55,12 +56,18 @@ async function run(event: SubmitEventPromise) {
55
56
  return
56
57
  case 'redirect':
57
58
  if (response.message) notifications.success(response.message)
59
+ // only a path of this admin, as a notification's link, checked before the dialog is done
60
+ if (!response.url || !isAdminPath(response.url)) {
61
+ notifications.error(t('actions.redirectRefused'))
62
+ break
63
+ }
58
64
  emit('done', response.affected)
59
- await navigateTo(`${appConfig.vector.basePath}${response.url ?? ''}`)
65
+ await navigateTo(`${appConfig.vector.basePath}${response.url}`)
60
66
  return
61
67
  case 'url':
62
68
  if (response.message) notifications.success(response.message)
63
- if (response.url && import.meta.client) window.open(response.url, '_blank', 'noopener')
69
+ // only where a link could go, as a URL cell: an action may echo a record's value
70
+ if (response.url && allowedHref(response.url) && import.meta.client) window.open(response.url, '_blank', 'noopener')
64
71
  break
65
72
  case 'download':
66
73
  notifications.success(t('actions.downloadStarted'))
@@ -1,4 +1,6 @@
1
1
  <script setup lang="ts">
2
+ import { isAdminPath } from '#vector/app/utils/internal/paths'
3
+
2
4
  // The bell: unread count polled every 30 seconds, the latest messages in a menu.
3
5
  const appConfig = useAppConfig()
4
6
  const inbox = useVectorNotificationsInbox()
@@ -10,10 +12,15 @@ const { pause } = useIntervalFn(() => inbox.refresh().catch(() => undefined), 30
10
12
  onUnmounted(pause)
11
13
  watch(open, o => { if (o) inbox.refresh().catch(() => undefined) })
12
14
 
15
+ // A link is a path of this admin: `//host`, `/\host`, `/\t/host` and anything with a scheme are not followed, as the login redirect.
13
16
  async function go(id: number, link: string | null) {
14
- await inbox.markRead(id)
15
- open.value = false
16
- if (link) navigateTo(`${appConfig.vector.basePath}${link}`)
17
+ try {
18
+ await inbox.markRead(id)
19
+ open.value = false
20
+ if (link && isAdminPath(link)) await navigateTo(`${appConfig.vector.basePath}${link}`)
21
+ } catch (error) {
22
+ useVectorNotifications().error(vectorErrorMessage(error))
23
+ }
17
24
  }
18
25
  </script>
19
26
 
@@ -29,6 +29,8 @@ function loadThumbs(options: VectorRelationValue[]) {
29
29
 
30
30
  const search = ref('')
31
31
  const loading = ref(false)
32
+ /** Why the last search found nothing to show: the choices already listed stay. */
33
+ const loadError = ref<string | null>(null)
32
34
  let requestId = 0
33
35
 
34
36
  const dependsOn = computed(() => props.field.relation?.dependsOn ?? null)
@@ -57,7 +59,10 @@ async function fetchOptions(query: string, ids: (number | string)[] = []) {
57
59
  const merged = [...selected, ...result.data.filter(r => !selected.some(s => s.id === r.id))]
58
60
  items.value = merged
59
61
  loadThumbs(result.data)
62
+ loadError.value = null
60
63
  }
64
+ } catch (error) {
65
+ if (id === requestId) loadError.value = vectorErrorMessage(error)
61
66
  } finally {
62
67
  if (id === requestId) loading.value = false
63
68
  }
@@ -105,7 +110,7 @@ onMounted(async () => {
105
110
  :closable-chips="multiple"
106
111
  :loading="loading"
107
112
  :rules="rules"
108
- :error-messages="errorMessages"
113
+ :error-messages="loadError ? [...errorMessages, loadError] : errorMessages"
109
114
  :clearable="field.nullable === true || multiple"
110
115
  :disabled="disabled || waiting"
111
116
  no-filter
@@ -91,7 +91,7 @@ async function insertImage(event: Event) {
91
91
  uploading.value = true
92
92
  uploadError.value = null
93
93
  try {
94
- const { key } = await client.upload(rich.value.imageField, file)
94
+ const { key } = await client.upload(rich.value.imageField, file, props.record?.id as string | number | undefined)
95
95
  uploaded.set(key, await dataUrl(file))
96
96
  run(e => e.chain().focus().setImage({ src: key, alt: file.name }).run())
97
97
  } catch (error) {
@@ -1,5 +1,6 @@
1
1
  <script setup lang="ts">
2
2
  import type { VectorField, VectorUploaded } from '#vector/app/types/vector'
3
+ import { violationsOf } from '#vector/app/utils/internal/violations'
3
4
 
4
5
  // A file or image field: pick a file, it uploads at once, and the field
5
6
  // takes the key the server issued. The server detects the format from the
@@ -39,12 +40,13 @@ async function choose(files: File | File[] | null) {
39
40
 
40
41
  uploading.value = true
41
42
  try {
42
- picked.value = await client.upload(props.field.name, file)
43
+ picked.value = await client.upload(props.field.name, file, props.record?.id as string | number | undefined)
43
44
  model.value = picked.value.key
44
45
  preview.value = image.value ? await dataUrl(file) : null
45
46
  } catch (error) {
46
- const failure = error as { data?: { errors?: { message: string }[] } } | null
47
- uploadError.value = failure?.data?.errors?.[0]?.message ? t('fields.upload.rejected', { message: failure.data.errors[0].message }) : vectorErrorMessage(error)
47
+ const failure = error as { data?: { errors?: unknown } } | null
48
+ const rejected = violationsOf(failure?.data?.errors)[0]
49
+ uploadError.value = rejected?.message ? t('fields.upload.rejected', { message: rejected.message }) : vectorErrorMessage(error)
48
50
  } finally {
49
51
  uploading.value = false
50
52
  }
@@ -1,6 +1,7 @@
1
1
  <script setup lang="ts">
2
2
  import type { SubmitEventPromise } from 'vuetify'
3
3
  import type { VectorField, VectorFieldState, VectorLayoutNode, VectorRecord, VectorResource } from '#vector/app/types/vector'
4
+ import { violationsOf } from '#vector/app/utils/internal/violations'
4
5
 
5
6
  // A create or edit form generated from the descriptor: one input per
6
7
  // editable field, client rules mirroring the server's, and the server's
@@ -222,7 +223,7 @@ async function save({ valid, errors }: { valid: boolean, errors: { id: string |
222
223
  const violations = failure?.data?.errors
223
224
 
224
225
  if ((failure?.status ?? failure?.statusCode) === 422 && Array.isArray(violations)) {
225
- for (const violation of violations as { path: (string | number)[], message: string }[]) {
226
+ for (const violation of violationsOf(violations)) {
226
227
  // a repeater row's own violation stays with its row: `lines.2.quantity`
227
228
  const repeated = violation.path.length >= 3 && fields.value.some(f => f.name === violation.path[0] && f.repeater)
228
229
  const key = repeated ? violation.path.slice(0, 3).join('.') : String(violation.path[0] ?? '')
@@ -311,13 +312,22 @@ const errorNames = computed(() => [...new Set([
311
312
  ...Object.entries(serverErrors).filter(([, messages]) => messages.length > 0).map(([key]) => key.split('.')[0]!),
312
313
  ...clientErrors.value,
313
314
  ])])
315
+
316
+ /** The server's errors on a field the form does not show (visibleWhen, or preset): above the form, under the field's label. */
317
+ const hiddenErrors = computed(() => Object.entries(serverErrors)
318
+ .map(([key, messages]) => [key.split('.')[0]!, messages] as const)
319
+ .filter(([name]) => !shownNames.value.has(name))
320
+ .flatMap(([name, messages]) => messages.map(message => `${fieldsByName.value.get(name)?.label ?? name}: ${message}`)))
314
321
  </script>
315
322
 
316
323
  <template>
317
324
  <v-form ref="formRef" validate-on="blur lazy" @submit.prevent="submit">
318
325
  <v-card>
319
326
  <v-card-text>
320
- <v-alert v-if="formError" type="error" variant="tonal" class="mb-4" :text="formError" />
327
+ <v-alert v-if="formError || hiddenErrors.length" type="error" variant="tonal" class="mb-4">
328
+ <div v-if="formError">{{ formError }}</div>
329
+ <div v-for="message in hiddenErrors" :key="message">{{ message }}</div>
330
+ </v-alert>
321
331
  <VxLayout :nodes="layout" :shown="name => shownNames.has(name)" :errors="errorNames" :default-span="defaultSpan">
322
332
  <template #field="{ field: name }">
323
333
  <component
@@ -1,6 +1,7 @@
1
1
  <script setup lang="ts">
2
2
  import { fieldProps, type VectorAction, type VectorExportFormat, type VectorField, type VectorFilterGroup, type VectorFilterQuery, type VectorFilters, type VectorListState, type VectorPage, type VectorRecord, type VectorResource, type VectorSelection, type VectorSort, type VectorSavedView } from '#vector/app/types/vector'
3
3
  import type { VectorPageStep } from '#vector/app/composables/useVectorCursorPager'
4
+ import { violationsOf } from '#vector/app/utils/internal/violations'
4
5
 
5
6
  // The list view: a server-driven table whose every option — page, size,
6
7
  // sort, filters, search, grouping, columns — becomes one list request,
@@ -404,11 +405,11 @@ async function saveChanges() {
404
405
  discardChanges()
405
406
  await load()
406
407
  } catch (error) {
407
- const failure = error as { status?: number, statusCode?: number, data?: { errors?: { path: (string | number)[], message: string }[] } } | null
408
+ const failure = error as { status?: number, statusCode?: number, data?: { errors?: unknown } } | null
408
409
  const status = failure?.status ?? failure?.statusCode
409
410
 
410
411
  if (status === 422 && Array.isArray(failure?.data?.errors)) {
411
- for (const violation of failure.data.errors) {
412
+ for (const violation of violationsOf(failure.data.errors)) {
412
413
  const [, index, field] = violation.path
413
414
  const change = typeof index === 'number' ? list[index] : undefined
414
415
  if (change && typeof field === 'string' && field in change.values) cellErrors[cellKey(change.id, field)] = violation.message
@@ -1,16 +1,22 @@
1
1
  <script setup lang="ts">
2
2
  import type { VectorWidgetData } from '#vector/app/types/vector'
3
+ import { isAdminPath } from '#vector/app/utils/internal/paths'
3
4
 
4
5
  const props = defineProps<{ data: VectorWidgetData }>()
5
6
  const appConfig = useAppConfig()
6
7
  const { t } = useVectorT()
7
8
  const rows = computed(() => props.data.rows ?? [])
8
9
 
9
- // a row with a link opens it, by mouse or by keyboard
10
- const linked = (row: Record<string, unknown>) => typeof row._link === 'string'
10
+ // a row with a link opens it, by mouse or by keyboard: only a path of this admin, as a notification's link
11
+ const linked = (row: Record<string, unknown>): row is { _link: string } => typeof row._link === 'string' && isAdminPath(row._link)
11
12
 
12
- function open(row: Record<string, unknown>) {
13
- if (typeof row._link === 'string') navigateTo(`${appConfig.vector.basePath}${row._link}`)
13
+ async function open(row: Record<string, unknown>) {
14
+ if (!linked(row)) return
15
+ try {
16
+ await navigateTo(`${appConfig.vector.basePath}${row._link}`)
17
+ } catch (error) {
18
+ useVectorNotifications().error(vectorErrorMessage(error))
19
+ }
14
20
  }
15
21
  </script>
16
22
 
@@ -1,14 +1,22 @@
1
1
  import type { $Fetch } from 'nitropack'
2
2
 
3
+ // The sign-out a 401 started, and the token whose session it ends: every
4
+ // request refused with that token (several waiting on one failed renewal)
5
+ // joins it rather than signing out again. One per module is one per session,
6
+ // the UI running in the browser only.
7
+ let ending: { token: string | null | undefined, done: Promise<void> } | null = null
8
+
3
9
  /**
4
10
  * The one HTTP client every Vector request goes through. Bearer mode
5
11
  * attaches the in-memory token — renewed first when it has under two
6
- * minutes left — and on a 401 renews it once and repeats the request,
7
- * sending the user to the login page only when that fails too (a 401
8
- * means the request did nothing, so repeating even a POST is safe);
9
- * cookie mode (hosted) rides the application's session cookie,
10
- * sends the CSRF token on every unsafe method, and hands a 401 to the
11
- * application's own login URL.
12
+ * minutes left — and on a 401 renews it once and repeats the request
13
+ * (a 401 for a token another request already renewed only repeats it),
14
+ * sending the user to the login page — once, however many requests
15
+ * that renewal failed — only when that fails too (a 401 means the
16
+ * request did nothing, so repeating even a POST is safe); cookie mode
17
+ * (hosted) rides the application's session cookie, sends the CSRF token
18
+ * on every unsafe method, and hands a 401 to the application's own login
19
+ * URL.
12
20
  */
13
21
  export function useVectorApi(): $Fetch {
14
22
  const config = useRuntimeConfig()
@@ -29,13 +37,20 @@ export function useVectorApi(): $Fetch {
29
37
  }
30
38
  } else {
31
39
  const token = await auth.fresh()
40
+ if (token !== null) ending = null // a new session: its own 401 signs out again
41
+ // which token, and whose, this request carried, for its 401
42
+ Object.assign(options, { vectorToken: token, vectorUser: auth.user === null ? null : String(auth.user.id) })
32
43
  if (token) options.headers.set('Authorization', `Bearer ${token}`)
33
44
  }
34
45
  },
35
46
  async onResponseError({ response, options }) {
36
- const once = options as typeof options & { vectorRenewed?: boolean }
47
+ const once = options as typeof options & { vectorRenewed?: boolean, vectorToken?: string | null, vectorUser?: string | null }
48
+ // the session changed since this request left: renewed for the same user (another request's 401 did it)
49
+ // repeats it without renewing again; another user's session (an impersonation ended) is not this request's
50
+ const moved = auth.token !== once.vectorToken
51
+ const renewedSince = moved && auth.token !== null && auth.user !== null && String(auth.user.id) === once.vectorUser
37
52
 
38
- if (response.status === 401 && !runtime.hosted && !once.vectorRenewed && auth.canRefresh && await auth.refresh()) {
53
+ if (response.status === 401 && !runtime.hosted && !once.vectorRenewed && (renewedSince || (!moved && auth.canRefresh && await auth.refresh()))) {
39
54
  // repeated once, with the renewed token (onRequest sets it)
40
55
  once.vectorRenewed = true
41
56
  options.retry = 1
@@ -51,23 +66,64 @@ export function useVectorApi(): $Fetch {
51
66
  return
52
67
  }
53
68
 
54
- auth.clear()
55
- // back to this page after signing in again, as the route middleware would send a visitor
56
- const current = router.currentRoute.value.fullPath
57
- await navigateTo({ path: `${appConfig.vector.basePath || ''}/login`, query: current.startsWith(`${appConfig.vector.basePath || ''}/login`) ? {} : { redirect: current } })
69
+ // the session this token belonged to is already ending: join that
70
+ if (ending !== null && ending.token === once.vectorToken) {
71
+ await ending.done
72
+
73
+ return
74
+ }
75
+
76
+ // refused for a session since replaced by another user's: that one is not this 401's to end
77
+ if (moved && auth.token !== null) return
78
+
79
+ ending = { token: once.vectorToken, done: end() }
80
+ await ending.done
58
81
  }
59
82
  },
60
83
  }) as $Fetch
84
+
85
+ /**
86
+ * Ends the session a 401 refused. An impersonation (never renewed)
87
+ * falls back to the signer's own session, renewed with their refresh
88
+ * token, without repeating the request as them; otherwise, or when
89
+ * that fails, the login page, saying why for an impersonation.
90
+ */
91
+ async function end(): Promise<void> {
92
+ const impersonating = auth.impersonating
93
+ const base = appConfig.vector.basePath || ''
94
+
95
+ try {
96
+ if (impersonating && await auth.resume()) {
97
+ // as stopping the impersonation does: the signer's own preferences and descriptor, and the dashboard
98
+ useState('vector.impersonator').value = null
99
+ useVectorPreferences().clear()
100
+ useVectorNotifications().notify(vt('shell.impersonation.ended'))
101
+ await useVectorSchema().load(true).catch(() => undefined)
102
+ await navigateTo(base || '/')
103
+
104
+ return
105
+ }
106
+
107
+ auth.clear()
108
+ // back to this page after signing in again, as the route middleware would send a visitor
109
+ const current = router.currentRoute.value.fullPath
110
+ const redirect = current.startsWith(`${base}/login`) ? {} : { redirect: current }
111
+ await navigateTo({ path: `${base}/login`, query: impersonating ? { ...redirect, reason: 'impersonation' } : redirect })
112
+ } catch {
113
+ // the navigation failed: the session is already ended
114
+ }
115
+ }
61
116
  }
62
117
 
63
- /** The message a failed request should show, from either Kinetis error shape. */
118
+ /** The message a failed request should show, from either Kinetis error shape: `error`, or problem+json's `detail`, then its `title`. */
64
119
  export function vectorErrorMessage(error: unknown): string {
65
- const failure = error as { data?: { error?: string, detail?: string }, message?: string } | null
120
+ const failure = error as { data?: { error?: string, detail?: string, title?: string }, message?: string } | null
66
121
  const data = failure?.data
67
122
 
68
123
  if (data && typeof data === 'object') {
69
124
  if (typeof data.error === 'string') return data.error
70
125
  if (typeof data.detail === 'string') return data.detail
126
+ if (typeof data.title === 'string') return data.title
71
127
  }
72
128
 
73
129
  return typeof failure?.message === 'string' ? failure.message : String(error)
@@ -46,7 +46,9 @@ const MAX_DELAY = 2 ** 31 - 1
46
46
  * 401; a failed renewal signs the user out. Logout revokes the refresh
47
47
  * token (`POST /auth/logout`). An impersonation token is never renewed:
48
48
  * the refresh token is the signed-in user's own, used only while the
49
- * session is theirs. Hosted mode rides the application's session instead.
49
+ * session is theirs or to end an impersonation that ran out, back in
50
+ * their own session (`resume`). Hosted mode rides the application's
51
+ * session instead.
50
52
  */
51
53
  export const useVectorAuthStore = defineStore('vectorAuth', {
52
54
  state: () => ({
@@ -55,7 +57,7 @@ export const useVectorAuthStore = defineStore('vectorAuth', {
55
57
  user: null as VectorUser | null,
56
58
  refreshToken: null as string | null,
57
59
  refreshExpiresAt: 0,
58
- /** Whose refresh token it is: the user who signed in. */
60
+ /** The user who signed in: whose refresh token it is, when there is one. */
59
61
  refreshSubject: null as string | null,
60
62
  restored: false,
61
63
  hosted: false,
@@ -67,11 +69,17 @@ export const useVectorAuthStore = defineStore('vectorAuth', {
67
69
  && state.refreshExpiresAt > Date.now()
68
70
  && state.user !== null
69
71
  && String(state.user.id) === state.refreshSubject,
72
+ /** Whether the session is another user's than the one who signed in: an impersonation. */
73
+ impersonating: state => state.user !== null && state.refreshSubject !== null && String(state.user.id) !== state.refreshSubject,
74
+ /** Whether an impersonation can end in the signer's own session: their refresh token is live. */
75
+ canResume(state): boolean {
76
+ return this.impersonating && state.refreshToken !== null && state.refreshExpiresAt > Date.now()
77
+ },
70
78
  // A getter is cached until the state changes, and the clock is not
71
79
  // state: the session's own timer (expireAt) renews or clears the
72
80
  // token when it runs out, which is the change that updates this.
73
81
  isAuthenticated(state): boolean {
74
- return state.hosted || (state.token !== null && state.expiresAt > Date.now()) || this.canRefresh
82
+ return state.hosted || (state.token !== null && state.expiresAt > Date.now()) || this.canRefresh || this.canResume
75
83
  },
76
84
  },
77
85
 
@@ -104,7 +112,7 @@ export const useVectorAuthStore = defineStore('vectorAuth', {
104
112
  this.user = saved.user
105
113
  this.refreshToken = refreshable ? saved.refreshToken! : null
106
114
  this.refreshExpiresAt = refreshable ? saved.refreshExpiresAt! : 0
107
- this.refreshSubject = refreshable ? saved.refreshSubject ?? null : null
115
+ this.refreshSubject = saved.refreshSubject ?? null
108
116
  this.expireAt(saved.expiresAt)
109
117
  }
110
118
  }
@@ -131,6 +139,22 @@ export const useVectorAuthStore = defineStore('vectorAuth', {
131
139
  refresh(): Promise<boolean> {
132
140
  if (!this.canRefresh) return Promise.resolve(false)
133
141
 
142
+ return this.renew()
143
+ },
144
+
145
+ /**
146
+ * Ends an impersonation the API no longer accepts: the signer's own
147
+ * session is renewed with their refresh token. False when it cannot
148
+ * be, and the session ended when the renewal is refused.
149
+ */
150
+ resume(): Promise<boolean> {
151
+ if (!this.canResume) return Promise.resolve(false)
152
+
153
+ return this.renew()
154
+ },
155
+
156
+ /** POST /auth/refresh with the refresh token, once at a time however many callers ask: `refresh` and `resume` decide when. */
157
+ renew(): Promise<boolean> {
134
158
  refreshing ??= (async () => {
135
159
  try {
136
160
  const config = useRuntimeConfig()
@@ -196,7 +220,8 @@ export const useVectorAuthStore = defineStore('vectorAuth', {
196
220
  if (this.expiresAt !== expiresAt) return // a newer token has its own timer
197
221
  if (Date.now() < due) this.expireAt(expiresAt) // past setTimeout's range: wait again
198
222
  else if (this.canRefresh) void this.refresh()
199
- else this.clear()
223
+ // an impersonation that ran out is left to lapse: the next request's 401 resumes the signer's own session
224
+ else if (!this.canResume) this.clear()
200
225
  }, Math.min(MAX_DELAY, Math.max(0, due - Date.now())))
201
226
  },
202
227
 
@@ -229,13 +254,13 @@ export const useVectorAuthStore = defineStore('vectorAuth', {
229
254
  if (response.refreshToken) {
230
255
  this.refreshToken = response.refreshToken
231
256
  this.refreshExpiresAt = Date.now() + (response.refreshExpiresIn ?? 0) * 1000
232
- this.refreshSubject = String(response.user.id)
233
257
  } else {
234
258
  this.refreshToken = null
235
259
  this.refreshExpiresAt = 0
236
- this.refreshSubject = null
237
260
  }
238
261
 
262
+ this.refreshSubject = String(response.user.id)
263
+
239
264
  this.expireAt(this.expiresAt)
240
265
  this.save()
241
266
  },
@@ -1,4 +1,5 @@
1
1
  import type { VectorField } from '#vector/app/types/vector'
2
+ import { violationsOf } from '#vector/app/utils/internal/violations'
2
3
 
3
4
  /** The value a fresh input holds: the field's default, or the type's empty value. */
4
5
  export function initialValue(field: VectorField): unknown {
@@ -10,7 +11,10 @@ export function initialValue(field: VectorField): unknown {
10
11
 
11
12
  /**
12
13
  * Maps the framework's 422 document onto field names; returns the
13
- * message that names no field, if any.
14
+ * message that names no field, if any. A violation deeper in a value
15
+ * (`tags.2`) shows on its field: the loose field lists this serves
16
+ * (settings, bulk edit, action dialogs) hold no repeater, the one input
17
+ * that takes a deeper key (`Vx/Resource/Form.vue` maps those).
14
18
  */
15
19
  export function applyViolations(error: unknown, values: Record<string, unknown>, serverErrors: Record<string, string[]>): string | null {
16
20
  const failure = error as { status?: number, statusCode?: number, data?: { errors?: unknown } } | null
@@ -22,7 +26,7 @@ export function applyViolations(error: unknown, values: Record<string, unknown>,
22
26
 
23
27
  let general: string | null = null
24
28
 
25
- for (const violation of violations as { path: (string | number)[], message: string }[]) {
29
+ for (const violation of violationsOf(violations)) {
26
30
  const key = String(violation.path[0] ?? '')
27
31
 
28
32
  if (key && key in values) {
@@ -28,12 +28,15 @@ export function useVectorJobs() {
28
28
  return job
29
29
  }
30
30
 
31
+ // the wait ends on the timer or the abort, and takes its listener off the signal either way
31
32
  await new Promise<void>((resolve) => {
32
- const timer = setTimeout(resolve, delay)
33
- signal?.addEventListener('abort', () => {
33
+ const done = () => {
34
34
  clearTimeout(timer)
35
+ signal?.removeEventListener('abort', done)
35
36
  resolve()
36
- }, { once: true })
37
+ }
38
+ const timer = setTimeout(done, delay)
39
+ signal?.addEventListener('abort', done, { once: true })
37
40
  })
38
41
 
39
42
  if (signal?.aborted) {
@@ -127,10 +127,14 @@ export function useVectorResource(slug: MaybeRefOrGetter<string>) {
127
127
  return api<{ data: VectorRecord[] }>(`${base()}/changes`, { method: 'POST', body: { changes: list } })
128
128
  }
129
129
 
130
- /** Stores one file for a file or image field; the answer's key is the value to write. */
131
- function upload(field: string, file: File): Promise<VectorUploaded> {
130
+ /**
131
+ * Stores one file for a file or image field; the answer's key is the value to write.
132
+ * `record` is the id of the record being edited: an account that may update it but not create needs it.
133
+ */
134
+ function upload(field: string, file: File, record?: string | number | null): Promise<VectorUploaded> {
132
135
  const body = new FormData()
133
136
  body.append('file', file)
137
+ if (record !== undefined && record !== null && record !== '') body.append('record', String(record))
134
138
  return api<VectorUploaded>(`${base()}/fields/${encodeURIComponent(field)}/upload`, { method: 'POST', body })
135
139
  }
136
140
 
@@ -4,10 +4,14 @@ import type { VectorResource, VectorSchema } from '#vector/app/types/vector'
4
4
  // language switched twice, say) must not replace it. One app per page.
5
5
  let latestLoad = 0
6
6
 
7
+ /** The descriptor contract this UI reads: the `version` kinetis/vector publishes (VectorRegistry::VERSION). */
8
+ export const DESCRIPTOR_VERSION = 4
9
+
7
10
  /**
8
11
  * The descriptor, loaded once per session and shared by every page. The
9
12
  * server's ETag makes a reload cheap; the layer reloads it after login
10
- * because the permission overlay is per identity.
13
+ * because the permission overlay is per identity. A descriptor of another
14
+ * contract version is refused rather than read as this one.
11
15
  */
12
16
  export function useVectorSchema() {
13
17
  const schema = useState<VectorSchema | null>('vector.schema', () => null)
@@ -26,6 +30,10 @@ export function useVectorSchema() {
26
30
  try {
27
31
  const answer = await api<VectorSchema>('/vector/schema')
28
32
 
33
+ if (answer?.version !== DESCRIPTOR_VERSION) {
34
+ throw new Error(vt('shell.unsupportedDescriptor', { version: String(answer?.version), supported: DESCRIPTOR_VERSION }))
35
+ }
36
+
29
37
  if (request === latestLoad) {
30
38
  schema.value = answer
31
39
  adoptMinorUnits(answer.minorUnits ?? {})
@@ -7,6 +7,7 @@ export default {
7
7
  subjectCount: '{count} {label}',
8
8
  done: 'تم تنفيذ {label}.',
9
9
  declined: 'رُفض الإجراء.',
10
+ redirectRefused: 'طلب الإجراء فتح صفحة خارج لوحة الإدارة، ولم تُفتح.',
10
11
  downloadStarted: 'بدأ التنزيل.',
11
12
  queued: 'أُضيف {label} إلى قائمة الانتظار.',
12
13
  }
@@ -8,6 +8,7 @@ export default {
8
8
  toggleTheme: 'تبديل السمة',
9
9
  language: 'اللغة: {name}',
10
10
  languageFailed: 'تعذّر حفظ اللغة: {error}',
11
+ unsupportedDescriptor: 'تنشر الواجهة البرمجية الإصدار {version} من الواصف، وهذه الإدارة تقرأ الإصدار {supported}. ثبّت إصدارين متوافقين من kinetis/vector وvector-ui.',
11
12
  nav: {
12
13
  main: 'الرئيسية',
13
14
  dashboard: 'لوحة المعلومات',
@@ -26,6 +27,7 @@ export default {
26
27
  stop: 'إنهاء التصرف باسم مستخدم آخر',
27
28
  noAccess: 'ليس لدى {name} صلاحية الوصول إلى لوحة الإدارة، لذا لا يوجد ما يمكن رؤيته باسمه. تم إنهاء التصرف باسمه.',
28
29
  noToken: 'استجاب التطبيق دون رمز مميز أو إعادة تحميل، لذا لم يتغير شيء.',
30
+ ended: 'انتهت مدة انتحال الهوية، فعدت إلى حسابك الخاص.',
29
31
  },
30
32
  palette: {
31
33
  placeholder: 'البحث في السجلات والموارد…',
@@ -47,6 +49,7 @@ export default {
47
49
  invalidEmail: 'يُرجى إدخال عنوان بريد إلكتروني صالح',
48
50
  welcome: 'مرحبًا بعودتك، {name}.',
49
51
  signedOutIdle: 'تم تسجيل خروجك بعد {minutes} دقيقة من عدم النشاط. سجّل الدخول مجددًا للمتابعة من حيث توقفت.',
52
+ impersonationEnded: 'انتهت مدة انتحال الهوية وتعذّر تجديد جلستك الخاصة. سجّل الدخول مجددًا للمتابعة.',
50
53
  },
51
54
  home: {
52
55
  title: 'لوحة المعلومات',