@innertia-solutions/innertia-nuxt 0.1.69 → 0.1.71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/components/Files/StorageTestRunner.vue +128 -0
- package/composables/useApi.js +18 -1
- package/composables/useStorageTestRunner/index.ts +54 -0
- package/composables/useStorageTestRunner/internal/__tests__/engine.test.ts +52 -0
- package/composables/useStorageTestRunner/internal/__tests__/steps.test.ts +232 -0
- package/composables/useStorageTestRunner/internal/engine.ts +82 -0
- package/composables/useStorageTestRunner/internal/steps.ts +280 -0
- package/nuxt.config.ts +1 -1
- package/package.json +1 -1
- package/server/routes/api/[...path].ts +9 -2
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
<script setup>
|
|
2
|
+
import { IconCircleCheck, IconCircleX, IconLoader2, IconCircleDashed, IconPlayerSkipForward, IconUpload, IconDownload, IconTrash, IconFlask } from '@tabler/icons-vue'
|
|
3
|
+
|
|
4
|
+
const props = defineProps({
|
|
5
|
+
filesBase: { type: String, required: true },
|
|
6
|
+
directoriesBase: { type: String, required: true },
|
|
7
|
+
expectedDisk: { type: String, default: null },
|
|
8
|
+
grants: { type: Boolean, default: true },
|
|
9
|
+
/** `{ grantable_type, grantable_id, grantable_class }`; obligatorio salvo que el backend use por defecto el usuario autenticado. */
|
|
10
|
+
grantee: { type: Object, default: null },
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
const { results, running, summary, run, abort } = useStorageTestRunner(() => ({
|
|
14
|
+
filesBase: props.filesBase,
|
|
15
|
+
directoriesBase: props.directoriesBase,
|
|
16
|
+
expectedDisk: props.expectedDisk,
|
|
17
|
+
grants: props.grants,
|
|
18
|
+
grantee: props.grantee,
|
|
19
|
+
}))
|
|
20
|
+
|
|
21
|
+
const api = useApi()
|
|
22
|
+
const { upload } = useFile()
|
|
23
|
+
const toast = useToast()
|
|
24
|
+
|
|
25
|
+
const file = ref(null)
|
|
26
|
+
const ran = ref(false)
|
|
27
|
+
const open = reactive({})
|
|
28
|
+
const LARGE = 50 * 1024 * 1024
|
|
29
|
+
|
|
30
|
+
function onPick(e) { file.value = e.target.files?.[0] ?? null }
|
|
31
|
+
function fmtSize(b) { return b < 1024 ? `${b} B` : b < 1048576 ? `${(b / 1024).toFixed(1)} KB` : `${(b / 1048576).toFixed(1)} MB` }
|
|
32
|
+
|
|
33
|
+
async function execute() {
|
|
34
|
+
if (!file.value) return
|
|
35
|
+
ran.value = true
|
|
36
|
+
await run(file.value)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
onBeforeUnmount(abort)
|
|
40
|
+
|
|
41
|
+
// ── Acciones manuales: subir de ejemplo (queda guardado) / descargar / borrar ──
|
|
42
|
+
const sample = ref(null)
|
|
43
|
+
const sampleBusy = ref(false)
|
|
44
|
+
async function uploadSample() {
|
|
45
|
+
if (!file.value) return
|
|
46
|
+
sampleBusy.value = true
|
|
47
|
+
try {
|
|
48
|
+
const res = await upload(props.filesBase, file.value, { extraData: { visibility: 'auth' } })
|
|
49
|
+
sample.value = res?.data ?? res
|
|
50
|
+
toast.success(`Subido a "${sample.value.disk}".`)
|
|
51
|
+
} catch (e) {
|
|
52
|
+
toast.error(e?.data?.message ?? 'No se pudo subir.')
|
|
53
|
+
} finally { sampleBusy.value = false }
|
|
54
|
+
}
|
|
55
|
+
async function downloadSample() {
|
|
56
|
+
// Las URLs firmadas expiran (~15 min): pedir una fresca al hacer clic.
|
|
57
|
+
try {
|
|
58
|
+
const res = await api.get(`${props.filesBase}/${sample.value.id}`)
|
|
59
|
+
const fresh = res?.data ?? res
|
|
60
|
+
window.location.href = fresh.download_url
|
|
61
|
+
} catch (e) { toast.error(e?.data?.message ?? 'No se pudo descargar.') }
|
|
62
|
+
}
|
|
63
|
+
async function deleteSample() {
|
|
64
|
+
try {
|
|
65
|
+
await api.delete(`${props.filesBase}/${sample.value.id}`, { params: { force: 1 } })
|
|
66
|
+
sample.value = null
|
|
67
|
+
} catch (e) { toast.error(e?.data?.message ?? 'No se pudo borrar.') }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const ICONS = { ok: IconCircleCheck, failed: IconCircleX, running: IconLoader2, pending: IconCircleDashed, skipped: IconPlayerSkipForward }
|
|
71
|
+
const COLORS = {
|
|
72
|
+
ok: 'text-emerald-600 dark:text-emerald-400',
|
|
73
|
+
failed: 'text-red-600 dark:text-red-400',
|
|
74
|
+
running: 'text-primary animate-spin',
|
|
75
|
+
pending: 'text-muted-foreground',
|
|
76
|
+
skipped: 'text-muted-foreground',
|
|
77
|
+
}
|
|
78
|
+
</script>
|
|
79
|
+
|
|
80
|
+
<template>
|
|
81
|
+
<div class="space-y-4">
|
|
82
|
+
<div class="bg-card border border-card-line rounded-card p-5 space-y-3">
|
|
83
|
+
<div class="flex items-center gap-2">
|
|
84
|
+
<IconFlask class="size-4 text-primary" />
|
|
85
|
+
<p class="text-sm font-semibold text-foreground">Probar almacenamiento con tu archivo</p>
|
|
86
|
+
</div>
|
|
87
|
+
<p class="text-xs text-muted-foreground">
|
|
88
|
+
Se sube tu archivo y se recorre la API real: directorios, descarga con verificación de integridad,
|
|
89
|
+
renombrar, público/privado, link compartido, permisos, papelera y borrado. Al final se limpia todo.
|
|
90
|
+
</p>
|
|
91
|
+
<input type="file" :disabled="running" class="block w-full text-sm text-foreground file:mr-3 file:rounded-control file:border-0 file:bg-primary/10 file:text-primary file:px-3 file:py-1.5" @change="onPick">
|
|
92
|
+
<p v-if="file" class="text-xs text-muted-foreground">
|
|
93
|
+
{{ file.name }} · {{ fmtSize(file.size) }} · {{ file.type || 'tipo desconocido' }}
|
|
94
|
+
<span v-if="file.size > LARGE" class="text-amber-600 dark:text-amber-400"> — archivo grande, la prueba puede tardar.</span>
|
|
95
|
+
</p>
|
|
96
|
+
<div class="flex flex-wrap items-center gap-2">
|
|
97
|
+
<AppButton :text="ran ? 'Volver a ejecutar' : 'Ejecutar pruebas'" severity="primary" size="sm" :disabled="!file" :loading="running" @click="execute" />
|
|
98
|
+
<AppButton v-if="running" text="Cancelar" severity="secondary" size="sm" @click="abort" />
|
|
99
|
+
<span class="grow" />
|
|
100
|
+
<AppButton text="Subir de ejemplo" :icon="IconUpload" severity="secondary" size="sm" :disabled="!file || running" :loading="sampleBusy" @click="uploadSample" />
|
|
101
|
+
</div>
|
|
102
|
+
<div v-if="sample" class="flex items-center gap-3 text-xs rounded-control border border-card-line p-2">
|
|
103
|
+
<span class="text-foreground truncate">{{ sample.original_name }}</span>
|
|
104
|
+
<span class="text-muted-foreground">disco: {{ sample.disk }}</span>
|
|
105
|
+
<span class="grow" />
|
|
106
|
+
<button type="button" class="inline-flex items-center gap-1 text-primary hover:underline" @click="downloadSample"><IconDownload class="size-3.5" /> Descargar</button>
|
|
107
|
+
<button type="button" class="inline-flex items-center gap-1 text-red-600 hover:underline" @click="deleteSample"><IconTrash class="size-3.5" /> Borrar</button>
|
|
108
|
+
</div>
|
|
109
|
+
</div>
|
|
110
|
+
|
|
111
|
+
<div v-if="ran" class="bg-card border border-card-line rounded-card divide-y divide-card-line">
|
|
112
|
+
<div class="px-5 py-3 flex items-center justify-between">
|
|
113
|
+
<p class="text-sm font-semibold text-foreground">Resultados</p>
|
|
114
|
+
<p class="text-xs" :class="summary.failed ? 'text-red-600 dark:text-red-400' : 'text-muted-foreground'">
|
|
115
|
+
{{ summary.ok }}/{{ summary.total }} OK<span v-if="summary.failed"> · {{ summary.failed }} fallaron</span><span v-if="summary.skipped"> · {{ summary.skipped }} omitidos</span>
|
|
116
|
+
</p>
|
|
117
|
+
</div>
|
|
118
|
+
<div v-for="r in results" :key="r.id" class="px-5 py-2.5">
|
|
119
|
+
<button type="button" class="w-full flex items-center gap-3 text-left" :disabled="!r.detail" @click="open[r.id] = !open[r.id]">
|
|
120
|
+
<component :is="ICONS[r.status]" class="size-4 shrink-0" :class="COLORS[r.status]" />
|
|
121
|
+
<span class="text-sm text-foreground grow">{{ r.label }}</span>
|
|
122
|
+
<span v-if="r.ms != null" class="text-[11px] text-muted-foreground tabular-nums">{{ r.ms }} ms</span>
|
|
123
|
+
</button>
|
|
124
|
+
<p v-if="r.detail && (open[r.id] || r.status === 'failed')" class="ml-7 mt-1 text-xs break-all" :class="r.status === 'failed' ? 'text-red-600 dark:text-red-400' : 'text-muted-foreground'">{{ r.detail }}</p>
|
|
125
|
+
</div>
|
|
126
|
+
</div>
|
|
127
|
+
</div>
|
|
128
|
+
</template>
|
package/composables/useApi.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// useRequestInterceptors auto-imported from nuxt-core
|
|
2
|
+
import { deleteCookie } from 'h3'
|
|
2
3
|
// useAuthStore auto-imported from this package
|
|
3
4
|
|
|
4
5
|
export function useApi() {
|
|
@@ -9,6 +10,10 @@ export function useApi() {
|
|
|
9
10
|
? (config.apiInternalUrl || config.public.apiBaseUrl || '/api')
|
|
10
11
|
: (config.public.apiBaseUrl || '/api')
|
|
11
12
|
const loginPath = config.public.loginPath || '/login'
|
|
13
|
+
// Capturados en setup (contexto Nuxt síncrono): tras un await en makeRequest
|
|
14
|
+
// el contexto puede no estar disponible.
|
|
15
|
+
const requestEvent = import.meta.server ? useRequestEvent() : null
|
|
16
|
+
const router = import.meta.client ? useRouter() : null
|
|
12
17
|
|
|
13
18
|
const { run, add } = useRequestInterceptors()
|
|
14
19
|
|
|
@@ -66,7 +71,19 @@ export function useApi() {
|
|
|
66
71
|
if (response.status === 401) {
|
|
67
72
|
const authStore = useAuthStore()
|
|
68
73
|
authStore.logout()
|
|
69
|
-
|
|
74
|
+
// La sesión sellada quedó inválida (token revocado, usuario borrado, BD
|
|
75
|
+
// reseteada): hay que BORRARLA. Si no, cada request vuelve "autenticado",
|
|
76
|
+
// guest manda a home, auth/me da 401 y se redirige a login → loop infinito
|
|
77
|
+
// (ERR_TOO_MANY_REDIRECTS).
|
|
78
|
+
if (requestEvent) {
|
|
79
|
+
requestEvent.context.authToken = undefined
|
|
80
|
+
deleteCookie(requestEvent, 'innertia_session', { path: '/' })
|
|
81
|
+
} else if (import.meta.client) {
|
|
82
|
+
try { await $fetch('/_auth/logout', { method: 'POST' }) } catch { /* best-effort */ }
|
|
83
|
+
}
|
|
84
|
+
const current = requestEvent ? requestEvent.path?.split('?')[0] : router?.currentRoute.value.path
|
|
85
|
+
// Ya en una página de login (la del producto o /platform/login): no redirigir.
|
|
86
|
+
if (current !== loginPath && !current?.endsWith('/login')) await navigateTo(loginPath)
|
|
70
87
|
return null
|
|
71
88
|
}
|
|
72
89
|
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { ref, computed, toValue, type MaybeRefOrGetter } from 'vue'
|
|
2
|
+
import { runSteps, type StepResult } from './internal/engine'
|
|
3
|
+
import { buildStorageSteps, sha256Hex, type StorageTestOptions } from './internal/steps'
|
|
4
|
+
|
|
5
|
+
export type { StepResult, StepStatus } from './internal/engine'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Pruebas de almacenamiento de punta a punta contra la API real de Files,
|
|
9
|
+
* con un archivo elegido por el usuario. Ver <Files.StorageTestRunner>.
|
|
10
|
+
*/
|
|
11
|
+
export function useStorageTestRunner(options: MaybeRefOrGetter<StorageTestOptions>) {
|
|
12
|
+
const api = useApi()
|
|
13
|
+
const { upload } = useFile()
|
|
14
|
+
|
|
15
|
+
const initial = (): StepResult[] => buildStorageSteps().map(d => ({ id: d.id, label: d.label, status: 'pending' }))
|
|
16
|
+
const results = ref<StepResult[]>(initial())
|
|
17
|
+
const running = ref(false)
|
|
18
|
+
let controller: AbortController | null = null
|
|
19
|
+
|
|
20
|
+
const summary = computed(() => {
|
|
21
|
+
const count = (s: string) => results.value.filter(r => r.status === s).length
|
|
22
|
+
return { ok: count('ok'), failed: count('failed'), skipped: count('skipped'), total: results.value.length }
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
async function run(file: File) {
|
|
26
|
+
if (running.value) return
|
|
27
|
+
running.value = true
|
|
28
|
+
controller = new AbortController()
|
|
29
|
+
try {
|
|
30
|
+
await runSteps(
|
|
31
|
+
buildStorageSteps(),
|
|
32
|
+
{
|
|
33
|
+
api, upload, hash: sha256Hex,
|
|
34
|
+
fetchFn: (url: string, init?: RequestInit) => fetch(url, init),
|
|
35
|
+
...toValue(options),
|
|
36
|
+
file,
|
|
37
|
+
stamp: new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14),
|
|
38
|
+
state: {},
|
|
39
|
+
signal: controller.signal,
|
|
40
|
+
},
|
|
41
|
+
(r) => { results.value = r },
|
|
42
|
+
controller.signal,
|
|
43
|
+
)
|
|
44
|
+
} finally {
|
|
45
|
+
running.value = false
|
|
46
|
+
controller = null
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function abort() { controller?.abort() }
|
|
51
|
+
function reset() { if (!running.value) results.value = initial() }
|
|
52
|
+
|
|
53
|
+
return { results, running, summary, run, abort, reset }
|
|
54
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { runSteps, describeError, type StepDef } from '../engine'
|
|
3
|
+
|
|
4
|
+
const ok = (id: string, extra: Partial<StepDef<any>> = {}): StepDef<any> => ({ id, label: id, run: async () => `${id} listo`, ...extra })
|
|
5
|
+
const boom = (id: string, extra: Partial<StepDef<any>> = {}): StepDef<any> => ({
|
|
6
|
+
id, label: id, run: async () => { throw Object.assign(new Error('API error 500'), { status: 500, data: { message: 'falló' } }) }, ...extra,
|
|
7
|
+
})
|
|
8
|
+
|
|
9
|
+
describe('runSteps', () => {
|
|
10
|
+
it('corre en orden y marca ok con detalle y duración', async () => {
|
|
11
|
+
const order: string[] = []
|
|
12
|
+
const defs = ['a', 'b'].map(id => ok(id, { run: async () => { order.push(id); return `${id} listo` } }))
|
|
13
|
+
const res = await runSteps(defs, {}, () => {})
|
|
14
|
+
expect(order).toEqual(['a', 'b'])
|
|
15
|
+
expect(res.map(r => r.status)).toEqual(['ok', 'ok'])
|
|
16
|
+
expect(res[0].detail).toBe('a listo')
|
|
17
|
+
expect(typeof res[0].ms).toBe('number')
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
it('omite dependientes de un paso fallido y siempre corre los always', async () => {
|
|
21
|
+
const res = await runSteps([boom('a'), ok('b', { dependsOn: ['a'] }), ok('c'), ok('z', { always: true, dependsOn: ['a'] })], {}, () => {})
|
|
22
|
+
expect(res.map(r => r.status)).toEqual(['failed', 'skipped', 'ok', 'ok'])
|
|
23
|
+
expect(res[0].detail).toBe('HTTP 500: falló')
|
|
24
|
+
expect(res[1].detail).toBe('Depende de: a')
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('when=false deja el paso omitido como desactivado', async () => {
|
|
28
|
+
const res = await runSteps([ok('a', { when: () => false })], {}, () => {})
|
|
29
|
+
expect(res[0]).toMatchObject({ status: 'skipped', detail: 'Desactivado' })
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
it('abortado: omite lo que falta salvo always', async () => {
|
|
33
|
+
const ctrl = new AbortController()
|
|
34
|
+
const defs = [ok('a', { run: async () => { ctrl.abort() } }), ok('b'), ok('z', { always: true })]
|
|
35
|
+
const res = await runSteps(defs, {}, () => {}, ctrl.signal)
|
|
36
|
+
expect(res.map(r => r.status)).toEqual(['ok', 'skipped', 'ok'])
|
|
37
|
+
expect(res[1].detail).toBe('Cancelado')
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
it('emite snapshots en cada cambio de estado', async () => {
|
|
41
|
+
const snaps: string[][] = []
|
|
42
|
+
await runSteps([ok('a')], {}, r => snaps.push(r.map(x => x.status)))
|
|
43
|
+
expect(snaps).toEqual([['pending'], ['running'], ['ok']])
|
|
44
|
+
})
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
describe('describeError', () => {
|
|
48
|
+
it('usa status + message del backend o el message del error', () => {
|
|
49
|
+
expect(describeError({ status: 404, data: { message: 'no' } })).toBe('HTTP 404: no')
|
|
50
|
+
expect(describeError(new Error('red caída'))).toBe('red caída')
|
|
51
|
+
})
|
|
52
|
+
})
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { runSteps } from '../engine'
|
|
3
|
+
import { buildStorageSteps, sha256Hex, type StorageTestCtx } from '../steps'
|
|
4
|
+
|
|
5
|
+
type Opts = { disk?: string, corrupt?: boolean, leakPublic?: boolean, grantNoId?: boolean, trashListThrows?: boolean }
|
|
6
|
+
|
|
7
|
+
function httpError(status: number, message = 'error') {
|
|
8
|
+
return Object.assign(new Error(`API error ${status}`), { status, data: { message } })
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function fakeBackend(opts: Opts = {}) {
|
|
12
|
+
let n = 0
|
|
13
|
+
const nextId = () => `id${++n}`
|
|
14
|
+
const dirs = new Map<string, any>()
|
|
15
|
+
const files = new Map<string, any>()
|
|
16
|
+
const blobs = new Map<string, Blob>()
|
|
17
|
+
const grants = new Map<string, any[]>()
|
|
18
|
+
const patches: { id: string, body: any }[] = []
|
|
19
|
+
const fetchInits: any[] = []
|
|
20
|
+
const ops: string[] = []
|
|
21
|
+
|
|
22
|
+
const present = (f: any) => {
|
|
23
|
+
const pub = f.visibility === 'public'
|
|
24
|
+
return {
|
|
25
|
+
...f,
|
|
26
|
+
view_url: pub ? `/files/${f.id}/view` : `/files/${f.id}/view?signature=s`,
|
|
27
|
+
download_url: pub ? `/files/${f.id}/download` : `/files/${f.id}/download?signature=s`,
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const fileOr404 = (id: string) => { const f = files.get(id); if (!f) throw httpError(404, 'File not found.'); return f }
|
|
31
|
+
|
|
32
|
+
const api = {
|
|
33
|
+
async get(path: string, o: any = {}) {
|
|
34
|
+
let m
|
|
35
|
+
if ((m = path.match(/^files\/trash$/))) {
|
|
36
|
+
if (opts.trashListThrows) throw new Error('la lista de papelera no debe usarse')
|
|
37
|
+
const q = o.params?.search ?? ''
|
|
38
|
+
return { data: [...files.values()].filter(f => f.deleted_at && f.original_name.includes(q)).map(present) }
|
|
39
|
+
}
|
|
40
|
+
if ((m = path.match(/^files\/(\w+)\/share-link$/))) { fileOr404(m[1]); return { url: `/files/${m[1]}/view?signature=share`, expires_in_hours: 1 } }
|
|
41
|
+
if ((m = path.match(/^files\/(\w+)\/grants$/))) { fileOr404(m[1]); return { data: grants.get(m[1]) ?? [] } }
|
|
42
|
+
if ((m = path.match(/^files\/(\w+)$/))) return { data: present(fileOr404(m[1])) }
|
|
43
|
+
throw httpError(404)
|
|
44
|
+
},
|
|
45
|
+
async post(path: string, body: any = {}) {
|
|
46
|
+
let m
|
|
47
|
+
if (path === 'dirs') { const d = { id: nextId(), name: body.name }; dirs.set(d.id, d); return { data: d } }
|
|
48
|
+
if ((m = path.match(/^files\/(\w+)\/restore$/))) { const f = fileOr404(m[1]); f.deleted_at = null; return { data: present(f) } }
|
|
49
|
+
if ((m = path.match(/^files\/(\w+)\/grants$/))) {
|
|
50
|
+
fileOr404(m[1]); const g: any = { id: opts.grantNoId ? undefined : nextId(), action: body.action }
|
|
51
|
+
grants.set(m[1], [...(grants.get(m[1]) ?? []), g]); return { data: g }
|
|
52
|
+
}
|
|
53
|
+
throw httpError(404)
|
|
54
|
+
},
|
|
55
|
+
async patch(path: string, body: any = {}) {
|
|
56
|
+
let m
|
|
57
|
+
if ((m = path.match(/^dirs\/(\w+)$/))) { const d = dirs.get(m[1]); Object.assign(d, body); return { data: d } }
|
|
58
|
+
if ((m = path.match(/^files\/(\w+)$/))) { const f = fileOr404(m[1]); patches.push({ id: m[1], body }); Object.assign(f, body); return { data: present(f) } }
|
|
59
|
+
throw httpError(404)
|
|
60
|
+
},
|
|
61
|
+
async delete(path: string, o: any = {}) {
|
|
62
|
+
let m
|
|
63
|
+
if ((m = path.match(/^dirs\/(\w+)$/))) {
|
|
64
|
+
dirs.delete(m[1])
|
|
65
|
+
for (const f of [...files.values()]) if (f.directory_id === m[1]) { files.delete(f.id); blobs.delete(f.id) }
|
|
66
|
+
return ''
|
|
67
|
+
}
|
|
68
|
+
if ((m = path.match(/^files\/(\w+)\/grants$/))) {
|
|
69
|
+
grants.set(m[1], (grants.get(m[1]) ?? []).filter(g => g.action !== o.params?.action)); return ''
|
|
70
|
+
}
|
|
71
|
+
if ((m = path.match(/^files\/(\w+)$/))) {
|
|
72
|
+
const f = fileOr404(m[1])
|
|
73
|
+
ops.push(o.params?.force ? `force:${m[1]}` : `soft:${m[1]}`)
|
|
74
|
+
if (o.params?.force) { files.delete(f.id); blobs.delete(f.id) } else f.deleted_at = '2026-11-04T00:00:00Z'
|
|
75
|
+
return ''
|
|
76
|
+
}
|
|
77
|
+
throw httpError(404)
|
|
78
|
+
},
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function upload(endpoint: string, file: File, o: any = {}) {
|
|
82
|
+
if (endpoint !== 'files') throw httpError(404)
|
|
83
|
+
const f = {
|
|
84
|
+
id: nextId(), original_name: file.name, size: file.size, mime_type: file.type,
|
|
85
|
+
disk: opts.disk ?? 'cloud', visibility: o.extraData?.visibility ?? 'auth',
|
|
86
|
+
directory_id: o.extraData?.directory_id ?? null, deleted_at: null,
|
|
87
|
+
}
|
|
88
|
+
files.set(f.id, f)
|
|
89
|
+
blobs.set(f.id, opts.corrupt ? new Blob(['corrupto']) : file)
|
|
90
|
+
return { data: present(f) }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function fetchFn(url: string, init?: any) {
|
|
94
|
+
fetchInits.push(init)
|
|
95
|
+
const m = url.match(/^\/files\/(\w+)\/(view|download)(\?signature=\w+)?$/)
|
|
96
|
+
const f = m && files.get(m[1])
|
|
97
|
+
if (!m || !f) return new Response('', { status: 404 })
|
|
98
|
+
const signed = !!m[3]
|
|
99
|
+
if (!signed && f.visibility !== 'public' && !opts.leakPublic) return new Response('', { status: 403 })
|
|
100
|
+
return new Response(blobs.get(f.id)!, { status: 200, headers: { 'content-type': f.mime_type } })
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return { api, upload, fetchFn, dirs, files, patches, fetchInits, ops }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function ctxFor(be: ReturnType<typeof fakeBackend>, over: Partial<StorageTestCtx> = {}): StorageTestCtx {
|
|
107
|
+
return {
|
|
108
|
+
api: be.api, upload: be.upload, fetchFn: be.fetchFn as any, hash: sha256Hex,
|
|
109
|
+
filesBase: 'files', directoriesBase: 'dirs', expectedDisk: 'cloud', grants: true,
|
|
110
|
+
file: new File(['hola mundo'], 'prueba.txt', { type: 'text/plain' }),
|
|
111
|
+
stamp: 'abc', state: {}, ...over,
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const run = (ctx: StorageTestCtx) => runSteps(buildStorageSteps(), ctx, () => {})
|
|
116
|
+
|
|
117
|
+
describe('buildStorageSteps', () => {
|
|
118
|
+
it('camino feliz: 15/15 ok y sin residuos', async () => {
|
|
119
|
+
const be = fakeBackend()
|
|
120
|
+
const res = await run(ctxFor(be))
|
|
121
|
+
expect(res).toHaveLength(15)
|
|
122
|
+
expect(res.filter(r => r.status !== 'ok')).toEqual([])
|
|
123
|
+
expect(be.files.size).toBe(0)
|
|
124
|
+
expect(be.dirs.size).toBe(0)
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
it('disco inesperado: falla la subida, dependientes omitidos, limpieza corre', async () => {
|
|
128
|
+
const be = fakeBackend({ disk: 'local' })
|
|
129
|
+
const res = await run(ctxFor(be))
|
|
130
|
+
const byId = Object.fromEntries(res.map(r => [r.id, r]))
|
|
131
|
+
expect(byId.upload.status).toBe('failed')
|
|
132
|
+
expect(byId.upload.detail).toContain('"local"')
|
|
133
|
+
expect(byId.download.status).toBe('skipped')
|
|
134
|
+
expect(byId.cleanup.status).toBe('ok')
|
|
135
|
+
expect(be.files.size).toBe(0)
|
|
136
|
+
expect(be.dirs.size).toBe(0)
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
it('sin expectedDisk no valida el disco', async () => {
|
|
140
|
+
const be = fakeBackend({ disk: 'local' })
|
|
141
|
+
const res = await run(ctxFor(be, { expectedDisk: null }))
|
|
142
|
+
expect(res.find(r => r.id === 'upload')!.status).toBe('ok')
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
it('descarga corrupta: falla la integridad', async () => {
|
|
146
|
+
const res = await run(ctxFor(fakeBackend({ corrupt: true })))
|
|
147
|
+
const dl = res.find(r => r.id === 'download')!
|
|
148
|
+
expect(dl.status).toBe('failed')
|
|
149
|
+
expect(dl.detail).toContain('hash distinto')
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
it('URL pública que sigue respondiendo tras volver a privado: falla make-private', async () => {
|
|
153
|
+
const res = await run(ctxFor(fakeBackend({ leakPublic: true })))
|
|
154
|
+
expect(res.find(r => r.id === 'make-private')!.status).toBe('failed')
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
it('C1: todos los fetch van con cache no-store', async () => {
|
|
158
|
+
const be = fakeBackend()
|
|
159
|
+
await run(ctxFor(be))
|
|
160
|
+
expect(be.fetchInits.length).toBeGreaterThan(4)
|
|
161
|
+
expect(be.fetchInits.every(i => i?.cache === 'no-store')).toBe(true)
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
it('I2: un permiso devuelto sin id hace fallar grants', async () => {
|
|
165
|
+
const res = await run(ctxFor(fakeBackend({ grantNoId: true })))
|
|
166
|
+
const g = res.find(r => r.id === 'grants')!
|
|
167
|
+
expect(g.status).toBe('failed')
|
|
168
|
+
expect(g.detail).toContain('id del permiso')
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
it('M1: la papelera se verifica por GET del archivo, no por la lista', async () => {
|
|
172
|
+
const res = await run(ctxFor(fakeBackend({ trashListThrows: true })))
|
|
173
|
+
expect(res.find(r => r.id === 'trash')!.status).toBe('ok')
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
it('M2: TypeError de red en check negativo da error claro', async () => {
|
|
177
|
+
const be = fakeBackend()
|
|
178
|
+
const orig = be.fetchFn
|
|
179
|
+
let calls = 0
|
|
180
|
+
const ctx = ctxFor(be, { fetchFn: (async (u: string, i: any) => {
|
|
181
|
+
if (u.endsWith('/view') && ++calls > 0) throw new TypeError('Failed to fetch')
|
|
182
|
+
return orig(u, i)
|
|
183
|
+
}) as any })
|
|
184
|
+
const res = await run(ctx)
|
|
185
|
+
const mp = res.find(r => r.id === 'make-public')!
|
|
186
|
+
expect(mp.status).toBe('failed') // make-public usa expectFetchOk (positivo)
|
|
187
|
+
const hd = res.find(r => r.id === 'hard-delete')!
|
|
188
|
+
expect(hd.status).toBe('ok')
|
|
189
|
+
})
|
|
190
|
+
|
|
191
|
+
it('M3: la limpieza intenta volver a privado y luego borra con force', async () => {
|
|
192
|
+
const be = fakeBackend()
|
|
193
|
+
let failedOnce = false
|
|
194
|
+
const api = { ...be.api, delete: async (path: string, o: any = {}) => {
|
|
195
|
+
if (o.params?.force && /^files\/\w+$/.test(path) && !failedOnce) { failedOnce = true; throw httpError(500, 'boom') }
|
|
196
|
+
return be.api.delete(path, o)
|
|
197
|
+
} }
|
|
198
|
+
const res = await run(ctxFor(be, { api }))
|
|
199
|
+
expect(res.find(r => r.id === 'hard-delete')!.status).toBe('failed')
|
|
200
|
+
expect(res.find(r => r.id === 'cleanup')!.status).toBe('ok')
|
|
201
|
+
expect(be.patches.at(-1)!.body).toEqual({ visibility: 'auth' })
|
|
202
|
+
expect(be.ops.at(-1)).toMatch(/^force:/)
|
|
203
|
+
})
|
|
204
|
+
|
|
205
|
+
it('M4: content-type distinto falla la vista previa; octet-stream pasa con nota', async () => {
|
|
206
|
+
const be = fakeBackend()
|
|
207
|
+
const bad = await run(ctxFor(be, { fetchFn: (async (u: string, i: any) => {
|
|
208
|
+
const r = await be.fetchFn(u, i); return u.includes('/view') && r.ok ? new Response(await r.blob(), { headers: { 'content-type': 'image/png' } }) : r
|
|
209
|
+
}) as any }))
|
|
210
|
+
expect(bad.find(r => r.id === 'preview')!.status).toBe('failed')
|
|
211
|
+
const be2 = fakeBackend()
|
|
212
|
+
const ok = await run(ctxFor(be2, { fetchFn: (async (u: string, i: any) => {
|
|
213
|
+
const r = await be2.fetchFn(u, i); return u.includes('/view') && r.ok ? new Response(await r.blob(), { headers: { 'content-type': 'application/octet-stream' } }) : r
|
|
214
|
+
}) as any }))
|
|
215
|
+
const p = ok.find(r => r.id === 'preview')!
|
|
216
|
+
expect(p.status).toBe('ok')
|
|
217
|
+
expect(p.detail).toContain('octet-stream')
|
|
218
|
+
})
|
|
219
|
+
|
|
220
|
+
it('grants=false: paso de permisos desactivado', async () => {
|
|
221
|
+
const res = await run(ctxFor(fakeBackend(), { grants: false }))
|
|
222
|
+
expect(res.find(r => r.id === 'grants')).toMatchObject({ status: 'skipped', detail: 'Desactivado' })
|
|
223
|
+
})
|
|
224
|
+
})
|
|
225
|
+
|
|
226
|
+
describe('sha256Hex', () => {
|
|
227
|
+
it('hash hex de 64 chars, estable', async () => {
|
|
228
|
+
const a = await sha256Hex(new Blob(['x']))
|
|
229
|
+
expect(a).toMatch(/^[0-9a-f]{64}$/)
|
|
230
|
+
expect(await sha256Hex(new Blob(['x']))).toBe(a)
|
|
231
|
+
})
|
|
232
|
+
})
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Motor genérico de pasos de prueba: corre StepDef en orden, respeta dependencias
|
|
3
|
+
* (si una dependencia no quedó 'ok' → 'skipped'), `when` (desactivado), `always`
|
|
4
|
+
* (corre siempre, p. ej. limpieza) y abort. Emite un snapshot por cambio de estado.
|
|
5
|
+
*/
|
|
6
|
+
export type StepStatus = 'pending' | 'running' | 'ok' | 'failed' | 'skipped'
|
|
7
|
+
|
|
8
|
+
export interface StepResult {
|
|
9
|
+
id: string
|
|
10
|
+
label: string
|
|
11
|
+
status: StepStatus
|
|
12
|
+
ms?: number
|
|
13
|
+
detail?: string
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface StepDef<C> {
|
|
17
|
+
id: string
|
|
18
|
+
label: string
|
|
19
|
+
dependsOn?: string[]
|
|
20
|
+
/** Corre aunque fallen dependencias o se haya abortado (limpieza). */
|
|
21
|
+
always?: boolean
|
|
22
|
+
/** false → 'skipped' con detalle 'Desactivado'. */
|
|
23
|
+
when?: (ctx: C) => boolean
|
|
24
|
+
/** Devuelve un detalle opcional; lanzar = fallo. */
|
|
25
|
+
run: (ctx: C) => Promise<string | void>
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function describeError(e: any): string {
|
|
29
|
+
if (e?.status) return `HTTP ${e.status}: ${e?.data?.message ?? e?.message ?? 'error'}`
|
|
30
|
+
return e?.message ?? String(e)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function runSteps<C>(
|
|
34
|
+
defs: StepDef<C>[],
|
|
35
|
+
ctx: C,
|
|
36
|
+
onUpdate: (results: StepResult[]) => void,
|
|
37
|
+
signal?: AbortSignal,
|
|
38
|
+
): Promise<StepResult[]> {
|
|
39
|
+
const results: StepResult[] = defs.map(d => ({ id: d.id, label: d.label, status: 'pending' }))
|
|
40
|
+
const byId = Object.fromEntries(results.map(r => [r.id, r]))
|
|
41
|
+
const emit = () => onUpdate(results.map(r => ({ ...r })))
|
|
42
|
+
emit()
|
|
43
|
+
|
|
44
|
+
for (const def of defs) {
|
|
45
|
+
const r = byId[def.id]
|
|
46
|
+
|
|
47
|
+
if (def.when && !def.when(ctx)) {
|
|
48
|
+
Object.assign(r, { status: 'skipped', detail: 'Desactivado' })
|
|
49
|
+
emit()
|
|
50
|
+
continue
|
|
51
|
+
}
|
|
52
|
+
if (!def.always) {
|
|
53
|
+
if (signal?.aborted) {
|
|
54
|
+
Object.assign(r, { status: 'skipped', detail: 'Cancelado' })
|
|
55
|
+
emit()
|
|
56
|
+
continue
|
|
57
|
+
}
|
|
58
|
+
const blocked = (def.dependsOn ?? []).find(dep => byId[dep]?.status !== 'ok')
|
|
59
|
+
if (blocked) {
|
|
60
|
+
Object.assign(r, { status: 'skipped', detail: `Depende de: ${byId[blocked]?.label ?? blocked}` })
|
|
61
|
+
emit()
|
|
62
|
+
continue
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
r.status = 'running'
|
|
67
|
+
emit()
|
|
68
|
+
const t0 = Date.now()
|
|
69
|
+
try {
|
|
70
|
+
const detail = await def.run(ctx)
|
|
71
|
+
r.status = 'ok'
|
|
72
|
+
if (detail) r.detail = detail
|
|
73
|
+
} catch (e) {
|
|
74
|
+
r.status = 'failed'
|
|
75
|
+
r.detail = describeError(e)
|
|
76
|
+
}
|
|
77
|
+
r.ms = Date.now() - t0
|
|
78
|
+
emit()
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return results
|
|
82
|
+
}
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import type { StepDef } from './engine'
|
|
2
|
+
|
|
3
|
+
/** Deps inyectadas (en la app: useApi/useFile/fetch; en tests: backend falso). */
|
|
4
|
+
export interface StorageTestDeps {
|
|
5
|
+
api: {
|
|
6
|
+
get: (path: string, opts?: any) => Promise<any>
|
|
7
|
+
post: (path: string, body?: any, opts?: any) => Promise<any>
|
|
8
|
+
patch: (path: string, body?: any, opts?: any) => Promise<any>
|
|
9
|
+
delete: (path: string, opts?: any) => Promise<any>
|
|
10
|
+
}
|
|
11
|
+
upload: (endpoint: string, file: File, opts?: { extraData?: Record<string, any>, signal?: AbortSignal }) => Promise<any>
|
|
12
|
+
fetchFn: (url: string, init?: RequestInit) => Promise<Response>
|
|
13
|
+
hash: (blob: Blob) => Promise<string>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface StorageTestOptions {
|
|
17
|
+
filesBase: string
|
|
18
|
+
directoriesBase: string
|
|
19
|
+
/** Si viene, la subida exige file.disk === expectedDisk. */
|
|
20
|
+
expectedDisk?: string | null
|
|
21
|
+
/** Incluir el paso de permisos (grants). */
|
|
22
|
+
grants?: boolean
|
|
23
|
+
/**
|
|
24
|
+
* Campos del grantee: `{ grantable_type, grantable_id, grantable_class }`.
|
|
25
|
+
* Obligatorio salvo que el backend rellene por defecto el usuario autenticado
|
|
26
|
+
* (como hace el controlador de platform de sumando).
|
|
27
|
+
*/
|
|
28
|
+
grantee?: Record<string, string> | null
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface StorageTestState {
|
|
32
|
+
dirId?: string
|
|
33
|
+
fileId?: string
|
|
34
|
+
file?: any
|
|
35
|
+
publicUrl?: string
|
|
36
|
+
originalHash?: string
|
|
37
|
+
hardDeleted?: boolean
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface StorageTestCtx extends StorageTestDeps, StorageTestOptions {
|
|
41
|
+
file: File
|
|
42
|
+
stamp: string
|
|
43
|
+
state: StorageTestState
|
|
44
|
+
/** Abort en vuelo: se pasa a upload y a los fetch (la limpieza no lo usa). */
|
|
45
|
+
signal?: AbortSignal
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const unwrap = (r: any) => r?.data ?? r
|
|
49
|
+
|
|
50
|
+
export async function sha256Hex(blob: Blob): Promise<string> {
|
|
51
|
+
const buf = await globalThis.crypto.subtle.digest('SHA-256', await blob.arrayBuffer())
|
|
52
|
+
return [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join('')
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function extOf(name: string): string {
|
|
56
|
+
const i = name.lastIndexOf('.')
|
|
57
|
+
return i > 0 ? name.slice(i) : ''
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** fetch sin caché HTTP (el backend sirve públicos con max-age) y con abort. Sin query params: rompería firmas. */
|
|
61
|
+
function noCacheFetch(c: StorageTestCtx, url: string, credentials: RequestCredentials): Promise<Response> {
|
|
62
|
+
return c.fetchFn(url, { credentials, cache: 'no-store', signal: c.signal })
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Para verificaciones negativas: un TypeError de red = no se pudo verificar (típico: otro origen/CORS). */
|
|
66
|
+
async function negativeFetch(c: StorageTestCtx, url: string, credentials: RequestCredentials): Promise<Response> {
|
|
67
|
+
try {
|
|
68
|
+
return await noCacheFetch(c, url, credentials)
|
|
69
|
+
} catch (e) {
|
|
70
|
+
if (e instanceof TypeError) {
|
|
71
|
+
throw new Error('No se pudo verificar: la URL apunta a otro origen (revisa que APP_URL sea el origen del frontend).')
|
|
72
|
+
}
|
|
73
|
+
throw e
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const baseMime = (m?: string | null) => (m ?? '').split(';')[0].trim().toLowerCase()
|
|
78
|
+
|
|
79
|
+
async function expectFetchOk(c: StorageTestCtx, url: string, credentials: RequestCredentials): Promise<Response> {
|
|
80
|
+
const res = await noCacheFetch(c, url, credentials)
|
|
81
|
+
if (!res.ok) throw new Error(`HTTP ${res.status} al pedir ${url.split('?')[0]}`)
|
|
82
|
+
return res
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function setVisibility(c: StorageTestCtx, visibility: string) {
|
|
86
|
+
const f = unwrap(await c.api.patch(`${c.filesBase}/${c.state.fileId}`, { visibility }))
|
|
87
|
+
c.state.file = f
|
|
88
|
+
return f
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function buildStorageSteps(): StepDef<StorageTestCtx>[] {
|
|
92
|
+
return [
|
|
93
|
+
{
|
|
94
|
+
id: 'create-dir', label: 'Crear directorio de prueba',
|
|
95
|
+
run: async (c) => {
|
|
96
|
+
const d = unwrap(await c.api.post(c.directoriesBase, { name: `pruebas-almacenamiento-${c.stamp}` }))
|
|
97
|
+
if (!d?.id) throw new Error('El backend no devolvió el id del directorio.')
|
|
98
|
+
c.state.dirId = d.id
|
|
99
|
+
return `Directorio "${d.name}"`
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
id: 'upload', label: 'Subir tu archivo', dependsOn: ['create-dir'],
|
|
104
|
+
run: async (c) => {
|
|
105
|
+
const f = unwrap(await c.upload(c.filesBase, c.file, { extraData: { directory_id: c.state.dirId, visibility: 'auth' }, signal: c.signal }))
|
|
106
|
+
if (!f?.id) throw new Error('El backend no devolvió el id del archivo.')
|
|
107
|
+
c.state.fileId = f.id
|
|
108
|
+
c.state.file = f
|
|
109
|
+
if (Number(f.size) !== c.file.size) throw new Error(`Tamaño distinto: subido ${c.file.size} B, registrado ${f.size} B.`)
|
|
110
|
+
if (c.expectedDisk && f.disk !== c.expectedDisk) {
|
|
111
|
+
throw new Error(`El archivo quedó en el disco "${f.disk}", se esperaba "${c.expectedDisk}".`)
|
|
112
|
+
}
|
|
113
|
+
return `Disco: ${f.disk ?? '?'} · ${f.size} bytes`
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
id: 'download', label: 'Descargar y verificar integridad (SHA-256)', dependsOn: ['upload'],
|
|
118
|
+
run: async (c) => {
|
|
119
|
+
const res = await expectFetchOk(c, c.state.file.download_url, 'include')
|
|
120
|
+
const blob = await res.blob()
|
|
121
|
+
c.state.originalHash ??= await c.hash(c.file)
|
|
122
|
+
const h = await c.hash(blob)
|
|
123
|
+
if (h !== c.state.originalHash) throw new Error(`hash distinto (${blob.size} bytes descargados de ${c.file.size}).`)
|
|
124
|
+
return `SHA-256 ${h.slice(0, 12)}… coincide`
|
|
125
|
+
},
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
id: 'preview', label: 'Vista previa con URL firmada', dependsOn: ['upload'],
|
|
129
|
+
run: async (c) => {
|
|
130
|
+
const res = await expectFetchOk(c, c.state.file.view_url, 'include')
|
|
131
|
+
const got = res.headers.get('content-type')
|
|
132
|
+
const want = c.state.file.mime_type
|
|
133
|
+
if (baseMime(got) === 'application/octet-stream' && baseMime(want) !== 'application/octet-stream') {
|
|
134
|
+
return `200 · application/octet-stream (el backend fuerza este tipo; esperado ${baseMime(want) || 'desconocido'})`
|
|
135
|
+
}
|
|
136
|
+
if (want && baseMime(got) !== baseMime(want)) {
|
|
137
|
+
throw new Error(`Content-Type "${got ?? 'ausente'}" no coincide con "${want}".`)
|
|
138
|
+
}
|
|
139
|
+
return `200 · ${got ?? 'sin content-type'}`
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
id: 'rename', label: 'Renombrar archivo', dependsOn: ['upload'],
|
|
144
|
+
run: async (c) => {
|
|
145
|
+
const name = `renombrado-${c.stamp}${extOf(c.file.name)}`
|
|
146
|
+
const f = unwrap(await c.api.patch(`${c.filesBase}/${c.state.fileId}`, { original_name: name }))
|
|
147
|
+
if (f?.original_name !== name) throw new Error(`Nombre devuelto "${f?.original_name}", se esperaba "${name}".`)
|
|
148
|
+
c.state.file = f
|
|
149
|
+
return `Ahora se llama "${name}"`
|
|
150
|
+
},
|
|
151
|
+
},
|
|
152
|
+
{
|
|
153
|
+
id: 'make-public', label: 'Hacer público (acceso sin sesión)', dependsOn: ['upload'],
|
|
154
|
+
run: async (c) => {
|
|
155
|
+
const f = await setVisibility(c, 'public')
|
|
156
|
+
c.state.publicUrl = f.view_url
|
|
157
|
+
try {
|
|
158
|
+
await expectFetchOk(c, f.view_url, 'omit')
|
|
159
|
+
} catch (e) {
|
|
160
|
+
await setVisibility(c, 'auth').catch(() => {})
|
|
161
|
+
throw e
|
|
162
|
+
}
|
|
163
|
+
return 'La URL pública responde sin sesión'
|
|
164
|
+
},
|
|
165
|
+
},
|
|
166
|
+
{
|
|
167
|
+
id: 'make-private', label: 'Volver a privado (la URL pública deja de responder)', dependsOn: ['make-public'],
|
|
168
|
+
run: async (c) => {
|
|
169
|
+
await setVisibility(c, 'auth')
|
|
170
|
+
const res = await negativeFetch(c, c.state.publicUrl!, 'omit')
|
|
171
|
+
if (res.ok) {
|
|
172
|
+
throw new Error('La URL pública sigue respondiendo 200 después de pasar a privado (si hay CDN delante, puede servir la versión pública cacheada hasta 24 h).')
|
|
173
|
+
}
|
|
174
|
+
return `URL pública ahora responde ${res.status}`
|
|
175
|
+
},
|
|
176
|
+
},
|
|
177
|
+
{
|
|
178
|
+
id: 'share-link', label: 'Link compartido temporal (1 hora)', dependsOn: ['upload'],
|
|
179
|
+
run: async (c) => {
|
|
180
|
+
const { url } = await c.api.get(`${c.filesBase}/${c.state.fileId}/share-link`, { params: { hours: 1 } })
|
|
181
|
+
if (!url) throw new Error('El backend no devolvió la URL.')
|
|
182
|
+
await expectFetchOk(c, url, 'omit')
|
|
183
|
+
return 'El link abre sin sesión'
|
|
184
|
+
},
|
|
185
|
+
},
|
|
186
|
+
{
|
|
187
|
+
id: 'grants', label: 'Dar y quitar permiso a un usuario', dependsOn: ['upload'],
|
|
188
|
+
when: c => c.grants !== false,
|
|
189
|
+
run: async (c) => {
|
|
190
|
+
const base = `${c.filesBase}/${c.state.fileId}/grants`
|
|
191
|
+
const who = c.grantee ?? {}
|
|
192
|
+
await setVisibility(c, 'restricted')
|
|
193
|
+
try {
|
|
194
|
+
const g = unwrap(await c.api.post(base, { ...who, action: 'view' }))
|
|
195
|
+
if (!g?.id) throw new Error('El backend no devolvió el id del permiso.')
|
|
196
|
+
const listed = unwrap(await c.api.get(base)) ?? []
|
|
197
|
+
if (!listed.some((x: any) => x.id === g?.id)) throw new Error('El permiso creado no aparece en la lista.')
|
|
198
|
+
await c.api.delete(base, { params: { ...who, action: 'view' } })
|
|
199
|
+
const after = unwrap(await c.api.get(base)) ?? []
|
|
200
|
+
if (after.some((x: any) => x.id === g?.id)) throw new Error('El permiso sigue apareciendo después de quitarlo.')
|
|
201
|
+
} finally {
|
|
202
|
+
await setVisibility(c, 'auth').catch(() => {})
|
|
203
|
+
}
|
|
204
|
+
return 'Permiso "view" creado, listado y revocado'
|
|
205
|
+
},
|
|
206
|
+
},
|
|
207
|
+
{
|
|
208
|
+
id: 'move-root', label: 'Mover a la raíz', dependsOn: ['upload'],
|
|
209
|
+
run: async (c) => {
|
|
210
|
+
const f = unwrap(await c.api.patch(`${c.filesBase}/${c.state.fileId}`, { directory_id: null }))
|
|
211
|
+
if (f?.directory_id) throw new Error(`Sigue en el directorio ${f.directory_id}.`)
|
|
212
|
+
c.state.file = f
|
|
213
|
+
return 'Movido fuera del directorio'
|
|
214
|
+
},
|
|
215
|
+
},
|
|
216
|
+
{
|
|
217
|
+
id: 'rename-dir', label: 'Renombrar directorio', dependsOn: ['create-dir'],
|
|
218
|
+
run: async (c) => {
|
|
219
|
+
const name = `pruebas-almacenamiento-${c.stamp}-ok`
|
|
220
|
+
const d = unwrap(await c.api.patch(`${c.directoriesBase}/${c.state.dirId}`, { name }))
|
|
221
|
+
if (d?.name !== name) throw new Error(`Nombre devuelto "${d?.name}".`)
|
|
222
|
+
return `Ahora se llama "${name}"`
|
|
223
|
+
},
|
|
224
|
+
},
|
|
225
|
+
{
|
|
226
|
+
id: 'trash', label: 'Enviar a la papelera', dependsOn: ['upload'],
|
|
227
|
+
run: async (c) => {
|
|
228
|
+
await c.api.delete(`${c.filesBase}/${c.state.fileId}`)
|
|
229
|
+
const f = unwrap(await c.api.get(`${c.filesBase}/${c.state.fileId}`))
|
|
230
|
+
if (!f?.deleted_at) throw new Error('El archivo no quedó marcado como eliminado.')
|
|
231
|
+
return 'Marcado como eliminado (en papelera)'
|
|
232
|
+
},
|
|
233
|
+
},
|
|
234
|
+
{
|
|
235
|
+
id: 'restore', label: 'Restaurar desde la papelera', dependsOn: ['trash'],
|
|
236
|
+
run: async (c) => {
|
|
237
|
+
const f = unwrap(await c.api.post(`${c.filesBase}/${c.state.fileId}/restore`))
|
|
238
|
+
if (f?.deleted_at) throw new Error('Sigue marcado como eliminado.')
|
|
239
|
+
c.state.file = f
|
|
240
|
+
return 'Restaurado'
|
|
241
|
+
},
|
|
242
|
+
},
|
|
243
|
+
{
|
|
244
|
+
id: 'hard-delete', label: 'Borrado definitivo', dependsOn: ['upload'],
|
|
245
|
+
run: async (c) => {
|
|
246
|
+
const oldUrl = c.state.file.download_url
|
|
247
|
+
await c.api.delete(`${c.filesBase}/${c.state.fileId}`, { params: { force: 1 } })
|
|
248
|
+
c.state.hardDeleted = true
|
|
249
|
+
let stillThere = false
|
|
250
|
+
try {
|
|
251
|
+
await c.api.get(`${c.filesBase}/${c.state.fileId}`)
|
|
252
|
+
stillThere = true
|
|
253
|
+
} catch (e: any) {
|
|
254
|
+
if (e?.status !== 404) throw e
|
|
255
|
+
}
|
|
256
|
+
if (stillThere) throw new Error('El archivo sigue existiendo después del borrado definitivo.')
|
|
257
|
+
const res = await negativeFetch(c, oldUrl, 'include')
|
|
258
|
+
if (res.ok) throw new Error('La URL de descarga sigue entregando el archivo.')
|
|
259
|
+
return `Eliminado (descarga ahora responde ${res.status})`
|
|
260
|
+
},
|
|
261
|
+
},
|
|
262
|
+
{
|
|
263
|
+
id: 'cleanup', label: 'Limpieza', always: true,
|
|
264
|
+
run: async (c) => {
|
|
265
|
+
const problems: string[] = []
|
|
266
|
+
if (c.state.fileId && !c.state.hardDeleted) {
|
|
267
|
+
await c.api.patch(`${c.filesBase}/${c.state.fileId}`, { visibility: 'auth' }).catch(() => {})
|
|
268
|
+
await c.api.delete(`${c.filesBase}/${c.state.fileId}`, { params: { force: 1 } })
|
|
269
|
+
.catch((e: any) => problems.push(`archivo: ${e?.data?.message ?? e?.message}`))
|
|
270
|
+
}
|
|
271
|
+
if (c.state.dirId) {
|
|
272
|
+
await c.api.delete(`${c.directoriesBase}/${c.state.dirId}`, { params: { force: 1, cascade: 1 } })
|
|
273
|
+
.catch((e: any) => problems.push(`directorio: ${e?.data?.message ?? e?.message}`))
|
|
274
|
+
}
|
|
275
|
+
if (problems.length) throw new Error(`Quedaron residuos — ${problems.join('; ')}`)
|
|
276
|
+
return 'Sin residuos'
|
|
277
|
+
},
|
|
278
|
+
},
|
|
279
|
+
]
|
|
280
|
+
}
|
package/nuxt.config.ts
CHANGED
|
@@ -29,7 +29,7 @@ export default defineNuxtConfig({
|
|
|
29
29
|
{ path: './components', pathPrefix: true, prefix: '' },
|
|
30
30
|
],
|
|
31
31
|
imports: {
|
|
32
|
-
dirs: ['stores', 'composables', 'composables/useWorkflow'],
|
|
32
|
+
dirs: ['stores', 'composables', 'composables/useWorkflow', 'composables/useStorageTestRunner'],
|
|
33
33
|
presets: [
|
|
34
34
|
{
|
|
35
35
|
from: '@tanstack/vue-query',
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { defineEventHandler, proxyRequest, getRequestURL } from 'h3'
|
|
2
|
-
import { readSession } from '../../utils/session'
|
|
2
|
+
import { readSession, clearSession } from '../../utils/session'
|
|
3
3
|
import { resolveApiTarget, buildAuthHeaders } from '../../utils/bff'
|
|
4
4
|
|
|
5
5
|
// BFF: reenvía /api/** a Laravel inyectando el Bearer desde la sesión sellada.
|
|
@@ -11,5 +11,12 @@ export default defineEventHandler(async (event) => {
|
|
|
11
11
|
const path = (event.context.params?.path ?? '') as string
|
|
12
12
|
const search = getRequestURL(event).search
|
|
13
13
|
const target = resolveApiTarget(config.apiInternalUrl, path, search)
|
|
14
|
-
return proxyRequest(event, target, {
|
|
14
|
+
return proxyRequest(event, target, {
|
|
15
|
+
headers: buildAuthHeaders(token),
|
|
16
|
+
// Token rechazado por Laravel → la sesión sellada no sirve: borrarla para que
|
|
17
|
+
// /_auth/session deje de reportar authenticated (evita loops de redirección).
|
|
18
|
+
onResponse: (ev, response) => {
|
|
19
|
+
if (token && response.status === 401) clearSession(ev)
|
|
20
|
+
},
|
|
21
|
+
})
|
|
15
22
|
})
|