@innertia-solutions/innertia-nuxt 0.1.81 → 0.1.83
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/CHANGELOG.md +1 -1
- package/components/Auth/PasskeyButton.vue +4 -2
- package/components/Auth/PasskeyInvite.vue +4 -2
- package/components/Auth/PasskeyManager.vue +10 -2
- package/components/Auth/PasskeySettings.vue +130 -0
- package/components/Files/DriveBrowser.vue +155 -0
- package/components/Files/DriveFolderField.vue +77 -0
- package/components/Files/DriveImport.vue +157 -0
- package/components/Files/ProviderOrigin.vue +70 -0
- package/components/Files/VersionHistory.vue +90 -0
- package/components/Files/__tests__/sfc-compile.test.ts +25 -0
- package/composables/useDriveBrowser/index.ts +72 -0
- package/composables/useDriveBrowser/internal/__tests__/browser.test.ts +97 -0
- package/composables/useDriveBrowser/internal/browser.ts +113 -0
- package/composables/useFileImports/index.ts +40 -0
- package/composables/useFileImports/internal/__tests__/progress.test.ts +65 -0
- package/composables/useFileImports/internal/progress.ts +100 -0
- package/composables/useFileVersions/index.ts +34 -0
- package/composables/useFileVersions/internal/__tests__/versions.test.ts +30 -0
- package/composables/useFileVersions/internal/versions.ts +52 -0
- package/composables/usePasskeys/index.ts +52 -2
- package/composables/usePasskeys/internal/__tests__/statusCache.test.ts +38 -0
- package/composables/usePasskeys/internal/statusCache.ts +43 -0
- package/docs/files-drive.md +112 -0
- package/docs/passkeys.md +12 -5
- package/nuxt.config.ts +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lógica pura de importaciones desde Drive (sin Nuxt/Vue). La consumen
|
|
3
|
+
* useFileImports, <Files.DriveImport> y <Files.ProviderOrigin>.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export type ImportStatus = 'pending' | 'running' | 'done' | 'failed'
|
|
7
|
+
export type ItemResult = 'imported' | 'updated' | 'unchanged' | 'skipped' | 'failed'
|
|
8
|
+
|
|
9
|
+
export interface ImportItem {
|
|
10
|
+
result: ItemResult
|
|
11
|
+
external_id: string | null
|
|
12
|
+
name: string | null
|
|
13
|
+
path?: string
|
|
14
|
+
reason?: string
|
|
15
|
+
file_id?: string
|
|
16
|
+
is_folder?: boolean
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface FileImport {
|
|
20
|
+
id: string
|
|
21
|
+
kind: 'import' | 'refresh'
|
|
22
|
+
status: ImportStatus
|
|
23
|
+
found: number
|
|
24
|
+
imported: number
|
|
25
|
+
updated: number
|
|
26
|
+
unchanged: number
|
|
27
|
+
skipped: number
|
|
28
|
+
failed: number
|
|
29
|
+
items: ImportItem[]
|
|
30
|
+
error: string | null
|
|
31
|
+
file_id?: string | null
|
|
32
|
+
target_directory_id?: string | null
|
|
33
|
+
started_at?: string | null
|
|
34
|
+
finished_at?: string | null
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const RESULT_ORDER: ItemResult[] = ['imported', 'updated', 'unchanged', 'skipped', 'failed']
|
|
38
|
+
|
|
39
|
+
export const RESULT_LABELS: Record<ItemResult, string> = {
|
|
40
|
+
imported: 'Importados',
|
|
41
|
+
updated: 'Actualizados',
|
|
42
|
+
unchanged: 'Sin cambios',
|
|
43
|
+
skipped: 'Omitidos',
|
|
44
|
+
failed: 'Con error',
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function importPayload(opts: {
|
|
48
|
+
items: Array<string | { id: string }>
|
|
49
|
+
directoryId?: string | null
|
|
50
|
+
nativeFormat?: 'office' | 'pdf'
|
|
51
|
+
visibility?: 'public' | 'auth' | 'restricted' | null
|
|
52
|
+
}) {
|
|
53
|
+
const ids = [...new Set(opts.items.map(i => (typeof i === 'string' ? i : i.id)))]
|
|
54
|
+
const payload: Record<string, unknown> = { items: ids }
|
|
55
|
+
if (opts.directoryId) payload.target_directory_id = opts.directoryId
|
|
56
|
+
payload.native_format = opts.nativeFormat ?? 'office'
|
|
57
|
+
if (opts.visibility) payload.visibility = opts.visibility
|
|
58
|
+
return payload
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function isFinished(status: ImportStatus | undefined | null): boolean {
|
|
62
|
+
return status === 'done' || status === 'failed'
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function processedCount(imp: Pick<FileImport, 'imported' | 'updated' | 'unchanged' | 'skipped' | 'failed'>): number {
|
|
66
|
+
return imp.imported + imp.updated + imp.unchanged + imp.skipped + imp.failed
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** null mientras no se conoce el total (aún recorriendo Drive). */
|
|
70
|
+
export function progressPercent(imp: FileImport): number | null {
|
|
71
|
+
if (!imp.found) return null
|
|
72
|
+
return Math.min(100, Math.round((processedCount(imp) / imp.found) * 100))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function groupItems(items: ImportItem[]): { result: ItemResult; label: string; items: ImportItem[] }[] {
|
|
76
|
+
return RESULT_ORDER
|
|
77
|
+
.map(result => ({ result, label: RESULT_LABELS[result], items: items.filter(i => i.result === result) }))
|
|
78
|
+
.filter(g => g.items.length > 0)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function itemLabel(item: ImportItem): string {
|
|
82
|
+
const name = item.name ?? item.external_id ?? '—'
|
|
83
|
+
return item.path ? `${item.path}/${name}` : name
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function selectionFlags(entries: Array<{ is_folder: boolean; is_native: boolean }>) {
|
|
87
|
+
return {
|
|
88
|
+
hasFolders: entries.some(e => e.is_folder),
|
|
89
|
+
hasNatives: entries.some(e => e.is_native),
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function refreshOutcome(imp: FileImport): { kind: 'updated' | 'unchanged' | 'failed'; message: string } {
|
|
94
|
+
if (imp.status === 'failed') {
|
|
95
|
+
return { kind: 'failed', message: imp.error || 'No se pudo actualizar desde Google Drive.' }
|
|
96
|
+
}
|
|
97
|
+
return imp.updated > 0
|
|
98
|
+
? { kind: 'updated', message: 'Actualizado desde Google Drive: se creó una nueva versión.' }
|
|
99
|
+
: { kind: 'unchanged', message: 'Sin cambios: el archivo ya estaba al día con Google Drive.' }
|
|
100
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { computed, toValue, type MaybeRefOrGetter } from 'vue'
|
|
2
|
+
import { versionEndpoints, type FileVersionEntry } from './internal/versions'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Historial de versiones de un archivo (innertia-laravel, Files\Routes::register):
|
|
6
|
+
* GET {filesBase}/{id}/versions · POST …/versions/{n}/restore · POST …/contents (multipart)
|
|
7
|
+
*/
|
|
8
|
+
export function useFileVersions(options: MaybeRefOrGetter<{ filesBase: string; fileId: string | null }>) {
|
|
9
|
+
const api = useApi()
|
|
10
|
+
const { upload } = useFile()
|
|
11
|
+
const queryClient = useQueryClient()
|
|
12
|
+
const opts = computed(() => toValue(options))
|
|
13
|
+
const endpoints = computed(() => (opts.value.fileId ? versionEndpoints(opts.value.filesBase, opts.value.fileId) : null))
|
|
14
|
+
const key = computed(() => ['files', 'versions', opts.value.filesBase, opts.value.fileId])
|
|
15
|
+
const invalidate = () => queryClient.invalidateQueries({ queryKey: ['files', 'versions'] })
|
|
16
|
+
|
|
17
|
+
const list = useQuery({
|
|
18
|
+
queryKey: key,
|
|
19
|
+
queryFn: async () => ((await api.get(endpoints.value!.list)) as any).data as FileVersionEntry[],
|
|
20
|
+
enabled: computed(() => !!endpoints.value),
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
const restore = useMutation({
|
|
24
|
+
mutationFn: (version: number) => api.post(endpoints.value!.restore(version)) as Promise<any>,
|
|
25
|
+
onSuccess: invalidate,
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
const replace = useMutation({
|
|
29
|
+
mutationFn: (file: File) => upload(endpoints.value!.contents, file, { field: 'file' }) as Promise<any>,
|
|
30
|
+
onSuccess: invalidate,
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
return { list, restore, replace, invalidate }
|
|
34
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { versionEndpoints, versionSourceLabel, formatBytes, versionResultMessage } from '../versions'
|
|
3
|
+
|
|
4
|
+
describe('versiones', () => {
|
|
5
|
+
it('arma endpoints bajo el prefijo de Files', () => {
|
|
6
|
+
const ep = versionEndpoints('platform/files', 'f 1')
|
|
7
|
+
expect(ep.list).toBe('platform/files/f%201/versions')
|
|
8
|
+
expect(ep.restore(3)).toBe('platform/files/f%201/versions/3/restore')
|
|
9
|
+
expect(ep.contents).toBe('platform/files/f%201/contents')
|
|
10
|
+
})
|
|
11
|
+
it('etiqueta el origen', () => {
|
|
12
|
+
expect(versionSourceLabel('upload')).toBe('Subida')
|
|
13
|
+
expect(versionSourceLabel('replace')).toBe('Reemplazo')
|
|
14
|
+
expect(versionSourceLabel('provider_import')).toBe('Desde Drive')
|
|
15
|
+
expect(versionSourceLabel('provider_refresh')).toBe('Actualizada desde Drive')
|
|
16
|
+
expect(versionSourceLabel('restore', 2)).toBe('Restaurada desde v2')
|
|
17
|
+
expect(versionSourceLabel('restore', null)).toBe('Restaurada')
|
|
18
|
+
expect(versionSourceLabel('otro' as any)).toBe('Versión')
|
|
19
|
+
})
|
|
20
|
+
it('formatea tamaños', () => {
|
|
21
|
+
expect(formatBytes(512)).toBe('512 B')
|
|
22
|
+
expect(formatBytes(2048)).toBe('2.0 KB')
|
|
23
|
+
expect(formatBytes(5 * 1048576)).toBe('5.0 MB')
|
|
24
|
+
expect(formatBytes(null)).toBe('—')
|
|
25
|
+
})
|
|
26
|
+
it('mensajes de resultado', () => {
|
|
27
|
+
expect(versionResultMessage({ status: 'created', file: { version: 4 } })).toBe('Nueva versión v4 creada.')
|
|
28
|
+
expect(versionResultMessage({ status: 'unchanged', file: { version: 3 } })).toBe('Sin cambios: el contenido es igual a la versión vigente.')
|
|
29
|
+
})
|
|
30
|
+
})
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/** Lógica pura del historial de versiones (sin Nuxt/Vue). */
|
|
2
|
+
import { joinPath } from '../../useDriveBrowser/internal/browser'
|
|
3
|
+
|
|
4
|
+
export type VersionSource = 'upload' | 'replace' | 'provider_import' | 'provider_refresh' | 'restore'
|
|
5
|
+
|
|
6
|
+
export interface FileVersionEntry {
|
|
7
|
+
version: number
|
|
8
|
+
is_current: boolean
|
|
9
|
+
original_name: string
|
|
10
|
+
mime_type: string | null
|
|
11
|
+
extension: string | null
|
|
12
|
+
size: number
|
|
13
|
+
source: VersionSource
|
|
14
|
+
restored_from_version: number | null
|
|
15
|
+
created_by: string | null
|
|
16
|
+
created_at: string | null
|
|
17
|
+
superseded_at: string | null
|
|
18
|
+
download_url: string | null
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function versionEndpoints(filesBase: string, fileId: string) {
|
|
22
|
+
const id = encodeURIComponent(fileId)
|
|
23
|
+
return {
|
|
24
|
+
list: joinPath(filesBase, `${id}/versions`),
|
|
25
|
+
restore: (version: number) => joinPath(filesBase, `${id}/versions/${version}/restore`),
|
|
26
|
+
contents: joinPath(filesBase, `${id}/contents`),
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function versionSourceLabel(source: VersionSource, restoredFrom?: number | null): string {
|
|
31
|
+
switch (source) {
|
|
32
|
+
case 'upload': return 'Subida'
|
|
33
|
+
case 'replace': return 'Reemplazo'
|
|
34
|
+
case 'provider_import': return 'Desde Drive'
|
|
35
|
+
case 'provider_refresh': return 'Actualizada desde Drive'
|
|
36
|
+
case 'restore': return restoredFrom ? `Restaurada desde v${restoredFrom}` : 'Restaurada'
|
|
37
|
+
default: return 'Versión'
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function formatBytes(bytes: number | null | undefined): string {
|
|
42
|
+
if (bytes === null || bytes === undefined) return '—'
|
|
43
|
+
if (bytes < 1024) return `${bytes} B`
|
|
44
|
+
if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`
|
|
45
|
+
return `${(bytes / 1048576).toFixed(1)} MB`
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function versionResultMessage(res: { status: 'created' | 'unchanged'; file: { version: number } }): string {
|
|
49
|
+
return res.status === 'created'
|
|
50
|
+
? `Nueva versión v${res.file.version} creada.`
|
|
51
|
+
: 'Sin cambios: el contenido es igual a la versión vigente.'
|
|
52
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ref, getCurrentInstance, onMounted, onBeforeUnmount } from 'vue'
|
|
1
|
+
import { ref, computed, getCurrentInstance, onMounted, onBeforeUnmount } from 'vue'
|
|
2
2
|
import {
|
|
3
3
|
startAuthentication,
|
|
4
4
|
startRegistration,
|
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
WEBAUTHN_INPUT_SELECTOR,
|
|
17
17
|
} from './internal/passkeys'
|
|
18
18
|
import { createRunGuard } from './internal/runGuard'
|
|
19
|
+
import { createStatusCache } from './internal/statusCache'
|
|
19
20
|
|
|
20
21
|
// Solo se exporta el composable (los helpers de ./internal no se auto-importan).
|
|
21
22
|
|
|
@@ -33,6 +34,9 @@ function supportsAutofill(): Promise<boolean> {
|
|
|
33
34
|
return autofillSupport
|
|
34
35
|
}
|
|
35
36
|
|
|
37
|
+
/** Estado del interruptor de plataforma: una consulta por base durante la vida de la página. */
|
|
38
|
+
const statusCaches = createStatusCache()
|
|
39
|
+
|
|
36
40
|
function debug(...args: any[]) {
|
|
37
41
|
if (import.meta.dev) console.debug('[passkeys]', ...args)
|
|
38
42
|
}
|
|
@@ -51,12 +55,21 @@ export interface PasskeyItem {
|
|
|
51
55
|
* (/_auth/passkey/login) que sella la sesión solo si hay token.
|
|
52
56
|
* - Gestión propia: base 'auth' (tenant) o 'platform/auth' (cuenta de plataforma).
|
|
53
57
|
*
|
|
58
|
+
* Interruptor: el backend lo guarda en BD y lo expone en `GET auth/passkey/status`
|
|
59
|
+
* (o `platform/auth/passkey/status`). `usePasskeys({ platform: true })` consulta el de
|
|
60
|
+
* plataforma; sin opciones, el de tenant. `enabled` es false hasta saberlo y
|
|
61
|
+
* `available` = supported && enabled. Con el interruptor apagado, login/autocompletado/
|
|
62
|
+
* registro no hacen nada (el autocompletado devuelve null; el resto lanza un error legible).
|
|
63
|
+
* La administración por usuario (listForUser/revokeAll) sigue funcionando.
|
|
64
|
+
*
|
|
54
65
|
* Llamar durante el setup de un componente: `supported`/`autofillSupported` se
|
|
55
66
|
* resuelven en onMounted (false en SSR y en el primer render → sin hydration
|
|
56
67
|
* mismatch) y el autocompletado se libera en onBeforeUnmount.
|
|
57
68
|
*/
|
|
58
|
-
export function usePasskeys() {
|
|
69
|
+
export function usePasskeys({ platform: platformStatus = false }: { platform?: boolean } = {}) {
|
|
59
70
|
const api = useApi()
|
|
71
|
+
const statusBase = platformStatus ? 'platform/auth' : 'auth'
|
|
72
|
+
const statusCache = statusCaches.for(base => api.get(`${base}/passkey/status`))
|
|
60
73
|
const authStore = useAuthStore()
|
|
61
74
|
const { finishLogin } = useAuth()
|
|
62
75
|
|
|
@@ -64,10 +77,38 @@ export function usePasskeys() {
|
|
|
64
77
|
const autofillSupported = ref(false)
|
|
65
78
|
/** true una vez resuelto el soporte en el cliente (para no mostrar "no soportado" antes de tiempo). */
|
|
66
79
|
const ready = ref(false)
|
|
80
|
+
/** Interruptor de plataforma (false hasta conocerse y ante cualquier fallo). */
|
|
81
|
+
const enabled = ref(false)
|
|
82
|
+
/** Soporte del navegador Y interruptor encendido: lo que decide si se ofrece la función. */
|
|
83
|
+
const available = computed(() => supported.value && enabled.value)
|
|
84
|
+
|
|
85
|
+
/** Resuelve (con caché) el interruptor y lo refleja en `enabled`. */
|
|
86
|
+
async function ensureEnabled(): Promise<boolean> {
|
|
87
|
+
if (!import.meta.client) return false
|
|
88
|
+
enabled.value = await statusCache.get(statusBase)
|
|
89
|
+
return enabled.value
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Descarta la caché (tras guardar el interruptor en /platform) y lo vuelve a leer. */
|
|
93
|
+
async function refreshStatus(): Promise<boolean> {
|
|
94
|
+
statusCache.reset()
|
|
95
|
+
return ensureEnabled()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function disabledError() {
|
|
99
|
+
return Object.assign(new Error('El ingreso con passkey está desactivado.'), {
|
|
100
|
+
data: { message: 'El ingreso con passkey está desactivado.' },
|
|
101
|
+
})
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function assertEnabled() {
|
|
105
|
+
if (!(await ensureEnabled())) throw disabledError()
|
|
106
|
+
}
|
|
67
107
|
|
|
68
108
|
async function detectSupport() {
|
|
69
109
|
supported.value = browserSupportsWebAuthn()
|
|
70
110
|
autofillSupported.value = await supportsAutofill()
|
|
111
|
+
await ensureEnabled()
|
|
71
112
|
ready.value = true
|
|
72
113
|
}
|
|
73
114
|
|
|
@@ -133,6 +174,7 @@ export function usePasskeys() {
|
|
|
133
174
|
async function authenticate(platform: boolean, contexts: string[]) {
|
|
134
175
|
assertContexts(platform, contexts)
|
|
135
176
|
stopAutofill()
|
|
177
|
+
await assertEnabled()
|
|
136
178
|
const { key, options } = await fetchLoginOptions(platform)
|
|
137
179
|
const response = await startAuthentication({ optionsJSON: options })
|
|
138
180
|
return verify(platform, contexts, key, response)
|
|
@@ -162,6 +204,9 @@ export function usePasskeys() {
|
|
|
162
204
|
|
|
163
205
|
if (!(await supportsAutofill())) return null
|
|
164
206
|
if (!guard.isCurrent(id)) return null
|
|
207
|
+
// Interruptor apagado (o sin respuesta): silencio, sin pedir opciones.
|
|
208
|
+
if (!(await statusCache.get(platform ? 'platform/auth' : 'auth'))) return null
|
|
209
|
+
if (!guard.isCurrent(id)) return null
|
|
165
210
|
|
|
166
211
|
while (guard.isCurrent(id)) {
|
|
167
212
|
if (!document.querySelector(WEBAUTHN_INPUT_SELECTOR)) {
|
|
@@ -247,6 +292,7 @@ export function usePasskeys() {
|
|
|
247
292
|
}
|
|
248
293
|
|
|
249
294
|
async function register(name?: string, base = 'auth'): Promise<PasskeyItem> {
|
|
295
|
+
if (!(await statusCache.get(base))) throw disabledError()
|
|
250
296
|
const res: any = await api.post(`${base}/me/passkeys/options`)
|
|
251
297
|
if (!res?.key || !res?.options) throw sessionError()
|
|
252
298
|
const response = await startRegistration({ optionsJSON: res.options })
|
|
@@ -276,6 +322,10 @@ export function usePasskeys() {
|
|
|
276
322
|
supported,
|
|
277
323
|
autofillSupported,
|
|
278
324
|
ready,
|
|
325
|
+
enabled,
|
|
326
|
+
available,
|
|
327
|
+
ensureEnabled,
|
|
328
|
+
refreshStatus,
|
|
279
329
|
login,
|
|
280
330
|
loginPlatform,
|
|
281
331
|
startAutofill,
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest'
|
|
2
|
+
import { createStatusCache } from '../statusCache'
|
|
3
|
+
|
|
4
|
+
describe('createStatusCache', () => {
|
|
5
|
+
it('consulta una sola vez por base', async () => {
|
|
6
|
+
const fetcher = vi.fn(async () => ({ enabled: true }))
|
|
7
|
+
const c = createStatusCache().for(fetcher)
|
|
8
|
+
expect(await Promise.all([c.get('auth'), c.get('auth')])).toEqual([true, true])
|
|
9
|
+
expect(fetcher).toHaveBeenCalledTimes(1)
|
|
10
|
+
await c.get('platform/auth')
|
|
11
|
+
expect(fetcher).toHaveBeenCalledTimes(2)
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
it('fallo = desactivado y se reintenta después', async () => {
|
|
15
|
+
const fetcher = vi.fn()
|
|
16
|
+
.mockRejectedValueOnce(new Error('x'))
|
|
17
|
+
.mockResolvedValueOnce({ enabled: true })
|
|
18
|
+
const c = createStatusCache().for(fetcher)
|
|
19
|
+
expect(await c.get('auth')).toBe(false)
|
|
20
|
+
expect(await c.get('auth')).toBe(true)
|
|
21
|
+
expect(fetcher).toHaveBeenCalledTimes(2)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('respuesta nula o sin enabled es false', async () => {
|
|
25
|
+
const c = createStatusCache().for(async () => null)
|
|
26
|
+
expect(await c.get('auth')).toBe(false)
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('reset fuerza una nueva consulta', async () => {
|
|
30
|
+
let enabled = false
|
|
31
|
+
const c = createStatusCache().for(async () => ({ enabled }))
|
|
32
|
+
expect(await c.get('auth')).toBe(false)
|
|
33
|
+
enabled = true
|
|
34
|
+
expect(await c.get('auth')).toBe(false)
|
|
35
|
+
c.reset('auth')
|
|
36
|
+
expect(await c.get('auth')).toBe(true)
|
|
37
|
+
})
|
|
38
|
+
})
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Caché de la promesa del estado (interruptor) de passkeys, por base ('auth' | 'platform/auth').
|
|
2
|
+
// Lógica pura (testeable en node): una consulta por base durante la vida de la página;
|
|
3
|
+
// un fallo cuenta como "desactivado" y NO se cachea (la próxima lectura reintenta).
|
|
4
|
+
|
|
5
|
+
export type StatusFetcher = (base: string) => Promise<{ enabled?: boolean } | null | undefined>
|
|
6
|
+
|
|
7
|
+
export interface StatusCache {
|
|
8
|
+
/** Estado de la base; nunca rechaza (fallo → false). */
|
|
9
|
+
get(base: string): Promise<boolean>
|
|
10
|
+
/** Olvida una base (o todas) para que la próxima lectura consulte de nuevo. */
|
|
11
|
+
reset(base?: string): void
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function createStatusCache(): { for(fetcher: StatusFetcher): StatusCache } {
|
|
15
|
+
const promises = new Map<string, Promise<boolean>>()
|
|
16
|
+
return {
|
|
17
|
+
for(fetcher) {
|
|
18
|
+
return {
|
|
19
|
+
get(base) {
|
|
20
|
+
let p = promises.get(base)
|
|
21
|
+
if (!p) {
|
|
22
|
+
const created: Promise<boolean> = (async () => {
|
|
23
|
+
try {
|
|
24
|
+
const res = await fetcher(base)
|
|
25
|
+
return res?.enabled === true
|
|
26
|
+
} catch {
|
|
27
|
+
if (promises.get(base) === created) promises.delete(base)
|
|
28
|
+
return false
|
|
29
|
+
}
|
|
30
|
+
})()
|
|
31
|
+
p = created
|
|
32
|
+
promises.set(base, p)
|
|
33
|
+
}
|
|
34
|
+
return p
|
|
35
|
+
},
|
|
36
|
+
reset(base) {
|
|
37
|
+
if (base) promises.delete(base)
|
|
38
|
+
else promises.clear()
|
|
39
|
+
},
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# Google Drive y versiones de archivos
|
|
2
|
+
|
|
3
|
+
Componentes para importar desde Google Drive al storage del producto, elegir una carpeta de Drive como configuración, ver el origen de un archivo importado (con "Actualizar") y gestionar el historial de versiones. Se apoyan en `\Innertia\Files` de innertia-laravel.
|
|
4
|
+
|
|
5
|
+
> En los productos los componentes se usan con la notación con punto (`<Files.DriveImport>`, `<Files.VersionHistory>`, …). Dentro de la librería se referencian sin punto (`<FilesDriveBrowser>`).
|
|
6
|
+
|
|
7
|
+
## Requisitos (backend Laravel)
|
|
8
|
+
|
|
9
|
+
1. **Proveedor conectado:** Google Drive conectado vía `\Innertia\Files\Routes::registerProviderConnections()` (ver `<Files.ProviderConnectButton>`).
|
|
10
|
+
2. **Rutas de Drive e importaciones** (opt-in), dentro del grupo autenticado del producto:
|
|
11
|
+
|
|
12
|
+
```php
|
|
13
|
+
\Innertia\Files\Routes::registerDriveImport('platform');
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Con prefijo `platform` quedan:
|
|
17
|
+
|
|
18
|
+
| Método | Ruta | Uso |
|
|
19
|
+
|---|---|---|
|
|
20
|
+
| GET | `platform/drive/browse?parent=&drive_id=&folders_only=` | listar carpeta (`items`, y `shared_drives` en la raíz) |
|
|
21
|
+
| GET | `platform/drive/items/{id}` | metadatos + ruta (`{ item, path }`) |
|
|
22
|
+
| POST | `platform/drive/folders` | crear carpeta (`{ name, parent }`) |
|
|
23
|
+
| POST | `platform/files/imports` | iniciar importación (202, corre en cola) |
|
|
24
|
+
| GET | `platform/files/imports/{id}` | estado del proceso |
|
|
25
|
+
| POST | `platform/files/{id}/refresh` | actualizar un archivo desde Drive (202) |
|
|
26
|
+
|
|
27
|
+
El valor del prop `drive-base` de los componentes es ese mismo prefijo (`'platform'`, o `''` si se registró sin prefijo).
|
|
28
|
+
3. **Versiones:** `\Innertia\Files\Routes::register('platform/files')` ya expone `GET {id}/versions`, `POST {id}/versions/{n}/restore` y `POST {id}/contents` (multipart, campo `file`). El prop `files-base` es ese prefijo (`'platform/files'`).
|
|
29
|
+
4. Un worker de cola corriendo: importaciones y refresh son asíncronos; el front consulta el estado cada 2 s hasta `done`/`failed`.
|
|
30
|
+
|
|
31
|
+
## Componentes
|
|
32
|
+
|
|
33
|
+
### `<Files.DriveBrowser>`
|
|
34
|
+
|
|
35
|
+
Panel para navegar Mi unidad y las unidades compartidas, con migas y "Nueva carpeta".
|
|
36
|
+
|
|
37
|
+
| Prop | Tipo | Default | |
|
|
38
|
+
|---|---|---|---|
|
|
39
|
+
| `drive-base` | String | `''` | prefijo de las rutas de Drive |
|
|
40
|
+
| `mode` | `'items' \| 'folder'` | `'items'` | `items`: v-model con la selección; `folder`: solo carpetas, emite `pick` |
|
|
41
|
+
| `v-model` | `DriveEntry[]` | `[]` | selección (modo `items`) |
|
|
42
|
+
| `multiple` | Boolean | `true` | selección múltiple (tope 200) |
|
|
43
|
+
| `accept` | String[] | `[]` | mimes o comodines (`'image/*'`); con filtro las carpetas solo se navegan |
|
|
44
|
+
| `start-at` | String | `null` | abre el panel en esa carpeta |
|
|
45
|
+
| `allow-create` | Boolean | `true` | muestra "Nueva carpeta" |
|
|
46
|
+
|
|
47
|
+
Eventos: `update:modelValue`, `pick({ id, name })` (modo `folder`, botón "Usar …"; la raíz de Mi unidad no es elegible).
|
|
48
|
+
|
|
49
|
+
### `<Files.DriveFolderField>`
|
|
50
|
+
|
|
51
|
+
Campo de formulario "carpeta de Google Drive". `v-model` = id de la carpeta (`''` = ninguna). Muestra nombre, ruta y enlace a Drive, y abre `<Files.DriveBrowser mode="folder">` en un modal.
|
|
52
|
+
|
|
53
|
+
Props: `v-model`, `drive-base`, `title` (título del modal).
|
|
54
|
+
|
|
55
|
+
### `<Files.DriveImport>`
|
|
56
|
+
|
|
57
|
+
Modal autocontenido: **elegir → opciones → progreso/resumen**. Cerrar no cancela el proceso.
|
|
58
|
+
|
|
59
|
+
| Prop | Tipo | Default | |
|
|
60
|
+
|---|---|---|---|
|
|
61
|
+
| `v-model` | Boolean | `false` | abierto/cerrado |
|
|
62
|
+
| `drive-base` | String | `''` | prefijo de las rutas |
|
|
63
|
+
| `directory-id` | String | `null` | directorio destino |
|
|
64
|
+
| `folders-allowed` | Boolean | `true` | `false` si el producto no usa Directories: bloquea carpetas en la selección |
|
|
65
|
+
| `visibility` | String | `null` | `public \| auth \| restricted` para los archivos creados |
|
|
66
|
+
| `resume-id` | String | `null` | reabre el seguimiento de un import en curso |
|
|
67
|
+
|
|
68
|
+
Eventos: `update:modelValue`, `done(import)` al terminar (`done` o `failed`). Si hay documentos nativos de Google (Docs/Sheets/Slides) ofrece formato Office o PDF.
|
|
69
|
+
|
|
70
|
+
### `<Files.ProviderOrigin>`
|
|
71
|
+
|
|
72
|
+
Franja "Importado de Google Drive · sincronizado …" con "Abrir en Drive" y "Actualizar" (si `file.can_refresh`). No se muestra si `file.provider` está vacío.
|
|
73
|
+
|
|
74
|
+
Props: `file` (FileResource), `drive-base`. Evento: `changed` cuando el refresh creó una versión nueva (avisa con toast tanto si hubo cambios como si no).
|
|
75
|
+
|
|
76
|
+
### `<Files.VersionHistory>`
|
|
77
|
+
|
|
78
|
+
Lista de versiones (fuente, fecha, tamaño, vigente) con descarga, "Restaurar" (crea una versión nueva, pide confirmación) y "Subir nueva versión".
|
|
79
|
+
|
|
80
|
+
Props: `files-base` (requerido), `file-id` (requerido), `allow-restore` (true), `allow-upload` (true). Evento: `changed(file)` cuando se creó una versión.
|
|
81
|
+
|
|
82
|
+
## Composables
|
|
83
|
+
|
|
84
|
+
Auto-importados: `useDriveBrowser({ base, foldersOnly?, enabled? })`, `useFileImports(base)` (`start`, `refresh`, `track(importIdRef)`) y `useFileVersions({ filesBase, fileId })` (`list`, `restore`, `replace`). Los helpers de `internal/` no se auto-importan.
|
|
85
|
+
|
|
86
|
+
## Ejemplo en un explorador de producto
|
|
87
|
+
|
|
88
|
+
```vue
|
|
89
|
+
<script setup>
|
|
90
|
+
const showImport = ref(false)
|
|
91
|
+
const selected = ref(null) // archivo en vista previa
|
|
92
|
+
const { data, refetch } = useQuery(/* … listado del directorio actual … */)
|
|
93
|
+
</script>
|
|
94
|
+
|
|
95
|
+
<template>
|
|
96
|
+
<!-- Barra del explorador -->
|
|
97
|
+
<AppButton text="Importar desde Drive" @click="showImport = true" />
|
|
98
|
+
<Files.DriveImport v-model="showImport" drive-base="platform" :directory-id="currentDir?.id" @done="refetch" />
|
|
99
|
+
|
|
100
|
+
<!-- Vista previa -->
|
|
101
|
+
<template v-if="selected">
|
|
102
|
+
<Files.ProviderOrigin :file="selected" drive-base="platform" @changed="refetch" />
|
|
103
|
+
<Files.VersionHistory files-base="platform/files" :file-id="selected.id" @changed="refetch" />
|
|
104
|
+
</template>
|
|
105
|
+
</template>
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Configuración (p. ej. carpeta por defecto para exportaciones):
|
|
109
|
+
|
|
110
|
+
```vue
|
|
111
|
+
<Files.DriveFolderField v-model="form.drive_folder_id" drive-base="platform" />
|
|
112
|
+
```
|
package/docs/passkeys.md
CHANGED
|
@@ -4,12 +4,17 @@ Ingreso con huella, rostro o llave de seguridad sobre `\Innertia\Passkeys` de in
|
|
|
4
4
|
|
|
5
5
|
## Requisitos (backend Laravel)
|
|
6
6
|
|
|
7
|
-
1.
|
|
8
|
-
2.
|
|
9
|
-
3. `
|
|
10
|
-
4.
|
|
7
|
+
1. `php artisan migrate` (crea la tabla de passkeys y la de configuración).
|
|
8
|
+
2. **Activación:** el ingreso con passkey viene **encendido por defecto** y se controla desde la consola `/platform` con `<Auth.PasskeySettings />` (interruptores "Ingreso con passkey" y "Permitir subdominios"; se guardan en BD). No hay variables de entorno. El producto registra las rutas en su grupo platform: `\Innertia\Passkeys\Routes::platformSettings('')`.
|
|
9
|
+
3. El front consulta `GET auth/passkey/status` (o `platform/auth/passkey/status`, con `usePasskeys({ platform: true })`) y solo ofrece la función si responde `{ enabled: true }`; el resultado se cachea por página y un fallo cuenta como desactivado. Con el interruptor apagado el backend responde 404 en login y autogestión, pero `users/{id}/passkeys` (administración) sigue funcionando para revocar.
|
|
10
|
+
4. El dominio (`rp_id`) y los orígenes se derivan de la URL del front; `<Auth.PasskeySettings />` los muestra en solo lectura.
|
|
11
11
|
5. El cache store de Laravel debe ser **compartido** entre instancias (Redis); las opciones de la ceremonia se guardan ahí.
|
|
12
12
|
|
|
13
|
+
```vue
|
|
14
|
+
<!-- pages/platform/settings/passkeys.vue -->
|
|
15
|
+
<template><Auth.PasskeySettings /></template>
|
|
16
|
+
```
|
|
17
|
+
|
|
13
18
|
Notas:
|
|
14
19
|
|
|
15
20
|
- Las cuentas de plataforma con cambio de contraseña forzado pendiente no pueden registrar una passkey hasta cambiarla.
|
|
@@ -86,7 +91,9 @@ El ingreso de plataforma siempre devuelve token (no hay `pending`). Si la cuenta
|
|
|
86
91
|
|
|
87
92
|
| Método | Uso |
|
|
88
93
|
|--------|-----|
|
|
89
|
-
| `
|
|
94
|
+
| `usePasskeys({ platform })` | `platform: true` usa el estado de `platform/auth/passkey/status`; por defecto el de tenant (`auth/passkey/status`) |
|
|
95
|
+
| `supported`, `autofillSupported`, `enabled`, `available`, `ready` | refs; `false` en SSR y en el primer render, se resuelven en `onMounted` (`ready` indica que ya se resolvió). `enabled` = interruptor de plataforma; `available` = `supported && enabled` |
|
|
96
|
+
| `ensureEnabled()`, `refreshStatus()` | lee el interruptor (con caché) / descarta la caché y lo relee (tras guardar en `/platform`) |
|
|
90
97
|
| `login({ contexts })`, `loginPlatform()` | ceremonia de ingreso (tenant / plataforma) |
|
|
91
98
|
| `startAutofill({ contexts, platform })`, `stopAutofill()`, `dispose()` | autocompletado (conditional UI); se libera solo al desmontar el componente que llamó a `usePasskeys()` |
|
|
92
99
|
| `list(base)`, `register(name?, base)`, `rename(id, name, base)`, `remove(id, base)` | gestión propia |
|
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', 'composables/useStorageTestRunner', 'composables/useNotificationHistory', 'composables/usePasskeys'],
|
|
32
|
+
dirs: ['stores', 'composables', 'composables/useWorkflow', 'composables/useStorageTestRunner', 'composables/useNotificationHistory', 'composables/usePasskeys', 'composables/useDriveBrowser', 'composables/useFileImports', 'composables/useFileVersions'],
|
|
33
33
|
presets: [
|
|
34
34
|
{
|
|
35
35
|
from: '@tanstack/vue-query',
|