@innertia-solutions/innertia-nuxt 0.1.90 → 0.1.91
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/Integrations/ApiKeys.vue +297 -0
- package/components/Integrations/Developers.vue +60 -0
- package/components/Integrations/Webhooks.vue +458 -0
- package/components/Integrations/__tests__/sfc-compile.test.ts +31 -0
- package/composables/useIntegrations/index.ts +136 -0
- package/composables/useIntegrations/internal/__tests__/integrations.test.ts +112 -0
- package/composables/useIntegrations/internal/integrations.ts +276 -0
- package/docs/webhooks-api.md +88 -0
- package/nuxt.config.ts +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import {
|
|
3
|
+
apiKeyStatus, deliveryStatus, webhookState, httpSeverity, scopeResource, groupScopes, toggleValue,
|
|
4
|
+
eventMatches, isEventSelected, groupEvents, toggleFamily, toggleEvent, familyState,
|
|
5
|
+
validateWebhookUrl, relativeTime, expiryLabel, expiryFromPreset, appendPage, prettyJson,
|
|
6
|
+
} from '../integrations'
|
|
7
|
+
|
|
8
|
+
const catalog = [
|
|
9
|
+
{ key: 'call.ringing' }, { key: 'call.answered' }, { key: 'call.ended' },
|
|
10
|
+
{ key: 'person.created' }, { key: 'person.updated' },
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
describe('status labels', () => {
|
|
14
|
+
it('maps key and delivery statuses with fallback', () => {
|
|
15
|
+
expect(apiKeyStatus('active')).toEqual({ label: 'Activa', severity: 'success' })
|
|
16
|
+
expect(apiKeyStatus('revoked').severity).toBe('danger')
|
|
17
|
+
expect(apiKeyStatus('weird').label).toBe('weird')
|
|
18
|
+
expect(deliveryStatus('retrying').label).toBe('Reintentando')
|
|
19
|
+
expect(deliveryStatus(null).label).toBe('—')
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('derives the webhook state', () => {
|
|
23
|
+
expect(webhookState({ active: false, disabled_at: '2026-11-19T00:00:00Z' }).label).toBe('Desactivado por fallas')
|
|
24
|
+
expect(webhookState({ active: false }).label).toBe('Pausado')
|
|
25
|
+
expect(webhookState({ active: true, failing_since: 'x' }).severity).toBe('warning')
|
|
26
|
+
expect(webhookState({ active: true }).label).toBe('Activo')
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('colors http statuses', () => {
|
|
30
|
+
expect(httpSeverity(200)).toBe('success')
|
|
31
|
+
expect(httpSeverity(404)).toBe('warning')
|
|
32
|
+
expect(httpSeverity(503)).toBe('danger')
|
|
33
|
+
expect(httpSeverity(null)).toBe('secondary')
|
|
34
|
+
})
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
describe('scopes', () => {
|
|
38
|
+
it('groups by explicit group or resource', () => {
|
|
39
|
+
expect(scopeResource('calls:read')).toBe('calls')
|
|
40
|
+
const g = groupScopes([{ key: 'calls:read' }, { key: 'people:read' }, { key: 'calls:write' }, { key: 'people:pii', group: 'people' }])
|
|
41
|
+
expect(g.map(x => x.group)).toEqual(['calls', 'people'])
|
|
42
|
+
expect(g[0].items.map(i => i.key)).toEqual(['calls:read', 'calls:write'])
|
|
43
|
+
expect(g[1].items).toHaveLength(2)
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it('toggles values without duplicates', () => {
|
|
47
|
+
expect(toggleValue(['a'], 'a', true)).toEqual(['a'])
|
|
48
|
+
expect(toggleValue(['a', 'b'], 'a', false)).toEqual(['b'])
|
|
49
|
+
})
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
describe('event selection with wildcards', () => {
|
|
53
|
+
it('matches patterns', () => {
|
|
54
|
+
expect(eventMatches('*', 'call.ended')).toBe(true)
|
|
55
|
+
expect(eventMatches('call.*', 'call.ended')).toBe(true)
|
|
56
|
+
expect(eventMatches('call.*', 'callback.x')).toBe(false)
|
|
57
|
+
expect(isEventSelected(['person.created'], 'person.updated')).toBe(false)
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it('groups events by family', () => {
|
|
61
|
+
expect(groupEvents(catalog).map(g => [g.family, g.items.length])).toEqual([['call', 3], ['person', 2]])
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it('toggles a family as wildcard', () => {
|
|
65
|
+
expect(toggleFamily(['call.ended', 'person.created'], 'call', true)).toEqual(['person.created', 'call.*'])
|
|
66
|
+
expect(toggleFamily(['call.*', 'person.created'], 'call', false)).toEqual(['person.created'])
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it('expands a wildcard when one event is turned off', () => {
|
|
70
|
+
expect(toggleEvent(['call.*'], 'call.ringing', false, catalog)).toEqual(['call.answered', 'call.ended'])
|
|
71
|
+
expect(toggleEvent(['*'], 'person.updated', false, catalog).sort()).toEqual(['call.*', 'person.created'].sort())
|
|
72
|
+
expect(toggleEvent(['call.*'], 'call.ended', true, catalog)).toEqual(['call.*'])
|
|
73
|
+
expect(toggleEvent([], 'call.ended', true, catalog)).toEqual(['call.ended'])
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it('reports family state', () => {
|
|
77
|
+
expect(familyState(['call.*'], 'call', catalog)).toBe('all')
|
|
78
|
+
expect(familyState(['call.ended'], 'call', catalog)).toBe('some')
|
|
79
|
+
expect(familyState(['person.created', 'person.updated'], 'person', catalog)).toBe('all')
|
|
80
|
+
expect(familyState([], 'person', catalog)).toBe('none')
|
|
81
|
+
})
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
describe('validation and dates', () => {
|
|
85
|
+
it('validates https webhook URLs', () => {
|
|
86
|
+
expect(validateWebhookUrl('')).toMatch(/Ingresa/)
|
|
87
|
+
expect(validateWebhookUrl('http://x.cl/hook')).toMatch(/https/)
|
|
88
|
+
expect(validateWebhookUrl('nope')).toMatch(/no es válida/)
|
|
89
|
+
expect(validateWebhookUrl('https://u:p@x.cl')).toMatch(/credenciales/)
|
|
90
|
+
expect(validateWebhookUrl('https://hooks.example.com/in')).toBeNull()
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
it('formats relative times and expiry', () => {
|
|
94
|
+
const now = new Date('2026-11-19T12:00:00Z')
|
|
95
|
+
expect(relativeTime('2026-11-19T11:55:00Z', now)).toBe('hace 5 min')
|
|
96
|
+
expect(relativeTime('2026-11-22T12:00:00Z', now)).toBe('en 3 días')
|
|
97
|
+
expect(relativeTime(null, now)).toBe('—')
|
|
98
|
+
expect(expiryLabel(null, now)).toBe('Sin vencimiento')
|
|
99
|
+
expect(expiryLabel('2026-11-20T12:00:00Z', now)).toBe('Vence en 1 día')
|
|
100
|
+
expect(expiryLabel('2026-11-18T12:00:00Z', now)).toBe('Venció hace 1 día')
|
|
101
|
+
expect(expiryFromPreset('30', now)).toBe('2026-12-19T12:00:00.000Z')
|
|
102
|
+
expect(expiryFromPreset('', now)).toBeNull()
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
it('appends cursor pages without duplicates and pretty-prints json', () => {
|
|
106
|
+
expect(appendPage([{ id: 1 }, { id: 2 }], [{ id: 2 }, { id: 3 }]).map(i => i.id)).toEqual([1, 2, 3])
|
|
107
|
+
expect(prettyJson('{"a":1}')).toBe('{\n "a": 1\n}')
|
|
108
|
+
expect(prettyJson({ a: 1 })).toBe('{\n "a": 1\n}')
|
|
109
|
+
expect(prettyJson('plain')).toBe('plain')
|
|
110
|
+
expect(prettyJson(null)).toBe('')
|
|
111
|
+
})
|
|
112
|
+
})
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure helpers for the Integrations screens (API keys + webhooks), no Nuxt/Vue: testable in node.
|
|
3
|
+
* Consumed by useApiKeys / useWebhooks and <Integrations.ApiKeys> / <Integrations.Webhooks>.
|
|
4
|
+
* Backend: innertia-laravel \Innertia\PublicApi\Routes::manage().
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export type Severity = 'primary' | 'secondary' | 'success' | 'danger' | 'warning' | 'info'
|
|
8
|
+
|
|
9
|
+
export type ApiKeyStatus = 'active' | 'expiring' | 'expired' | 'revoked'
|
|
10
|
+
export type DeliveryStatus = 'pending' | 'delivered' | 'failed' | 'retrying'
|
|
11
|
+
|
|
12
|
+
export interface ApiKey {
|
|
13
|
+
id: string
|
|
14
|
+
name: string
|
|
15
|
+
prefix: string
|
|
16
|
+
hint?: string | null
|
|
17
|
+
scopes: string[]
|
|
18
|
+
organization_id?: string | null
|
|
19
|
+
expires_at?: string | null
|
|
20
|
+
last_used_at?: string | null
|
|
21
|
+
last_used_ip?: string | null
|
|
22
|
+
created_by?: string | null
|
|
23
|
+
revoked_at?: string | null
|
|
24
|
+
rotated_to_id?: string | null
|
|
25
|
+
status: ApiKeyStatus
|
|
26
|
+
created_at?: string | null
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface ApiScope { key: string; description?: string | null; group?: string | null }
|
|
30
|
+
|
|
31
|
+
export interface Webhook {
|
|
32
|
+
id: string | number
|
|
33
|
+
url: string
|
|
34
|
+
description?: string | null
|
|
35
|
+
events: string[]
|
|
36
|
+
active: boolean
|
|
37
|
+
organization_id?: string | null
|
|
38
|
+
scopes?: string[]
|
|
39
|
+
secret_hint?: string | null
|
|
40
|
+
previous_secret_expires_at?: string | null
|
|
41
|
+
disabled_at?: string | null
|
|
42
|
+
disabled_reason?: string | null
|
|
43
|
+
failing_since?: string | null
|
|
44
|
+
last_success_at?: string | null
|
|
45
|
+
last_failure_at?: string | null
|
|
46
|
+
legacy?: boolean
|
|
47
|
+
created_at?: string | null
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface WebhookEvent { key: string; description?: string | null; version?: string | null; scope?: string | null; example?: any }
|
|
51
|
+
|
|
52
|
+
export interface WebhookLog {
|
|
53
|
+
id: string | number
|
|
54
|
+
message_id?: string | null
|
|
55
|
+
event_key: string
|
|
56
|
+
status: DeliveryStatus
|
|
57
|
+
attempts?: number
|
|
58
|
+
response_status?: number | null
|
|
59
|
+
duration_ms?: number | null
|
|
60
|
+
error?: string | null
|
|
61
|
+
is_test?: boolean
|
|
62
|
+
created_at?: string | null
|
|
63
|
+
delivered_at?: string | null
|
|
64
|
+
failed_at?: string | null
|
|
65
|
+
next_retry_at?: string | null
|
|
66
|
+
[key: string]: any
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ── Status labels ────────────────────────────────────────────────────────────
|
|
70
|
+
|
|
71
|
+
export const API_KEY_STATUS: Record<ApiKeyStatus, { label: string; severity: Severity }> = {
|
|
72
|
+
active: { label: 'Activa', severity: 'success' },
|
|
73
|
+
expiring: { label: 'Por vencer', severity: 'warning' },
|
|
74
|
+
expired: { label: 'Vencida', severity: 'secondary' },
|
|
75
|
+
revoked: { label: 'Revocada', severity: 'danger' },
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export const DELIVERY_STATUS: Record<DeliveryStatus, { label: string; severity: Severity }> = {
|
|
79
|
+
pending: { label: 'Pendiente', severity: 'info' },
|
|
80
|
+
delivered: { label: 'Entregado', severity: 'success' },
|
|
81
|
+
retrying: { label: 'Reintentando', severity: 'warning' },
|
|
82
|
+
failed: { label: 'Fallido', severity: 'danger' },
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function apiKeyStatus(status: string | null | undefined) {
|
|
86
|
+
return API_KEY_STATUS[status as ApiKeyStatus] ?? { label: status || '—', severity: 'secondary' as Severity }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function deliveryStatus(status: string | null | undefined) {
|
|
90
|
+
return DELIVERY_STATUS[status as DeliveryStatus] ?? { label: status || '—', severity: 'secondary' as Severity }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Webhook state: disabled by health check, paused by a user, or active. */
|
|
94
|
+
export function webhookState(w: Pick<Webhook, 'active' | 'disabled_at' | 'failing_since'>): { label: string; severity: Severity } {
|
|
95
|
+
if (w.disabled_at) return { label: 'Desactivado por fallas', severity: 'danger' }
|
|
96
|
+
if (!w.active) return { label: 'Pausado', severity: 'secondary' }
|
|
97
|
+
if (w.failing_since) return { label: 'Con fallas', severity: 'warning' }
|
|
98
|
+
return { label: 'Activo', severity: 'success' }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Severity for an HTTP status code shown in logs. */
|
|
102
|
+
export function httpSeverity(status: number | null | undefined): Severity {
|
|
103
|
+
if (!status) return 'secondary'
|
|
104
|
+
if (status < 300) return 'success'
|
|
105
|
+
if (status < 400) return 'info'
|
|
106
|
+
if (status === 429 || status < 500) return 'warning'
|
|
107
|
+
return 'danger'
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ── Scopes ───────────────────────────────────────────────────────────────────
|
|
111
|
+
|
|
112
|
+
/** Resource of a scope: `calls:read` → `calls`, `people:pii` → `people`. */
|
|
113
|
+
export function scopeResource(scope: string): string {
|
|
114
|
+
const i = scope.indexOf(':')
|
|
115
|
+
return i === -1 ? scope : scope.slice(0, i)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Groups scopes by `group` (or the resource of the key), keeping the server order. */
|
|
119
|
+
export function groupScopes(scopes: ApiScope[]): { group: string; items: ApiScope[] }[] {
|
|
120
|
+
const groups: { group: string; items: ApiScope[] }[] = []
|
|
121
|
+
for (const s of scopes) {
|
|
122
|
+
const g = s.group || scopeResource(s.key)
|
|
123
|
+
let entry = groups.find(x => x.group === g)
|
|
124
|
+
if (!entry) groups.push(entry = { group: g, items: [] })
|
|
125
|
+
entry.items.push(s)
|
|
126
|
+
}
|
|
127
|
+
return groups
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function toggleValue(list: string[], value: string, on: boolean): string[] {
|
|
131
|
+
const set = new Set(list)
|
|
132
|
+
on ? set.add(value) : set.delete(value)
|
|
133
|
+
return [...set]
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// ── Events (wildcards) ───────────────────────────────────────────────────────
|
|
137
|
+
|
|
138
|
+
/** Family of an event key: `call.ended` → `call`. */
|
|
139
|
+
export function eventFamily(key: string): string {
|
|
140
|
+
const i = key.indexOf('.')
|
|
141
|
+
return i === -1 ? key : key.slice(0, i)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Does a subscription pattern (`*`, `call.*`, `call.ended`) match the event key? */
|
|
145
|
+
export function eventMatches(pattern: string, key: string): boolean {
|
|
146
|
+
if (pattern === '*') return true
|
|
147
|
+
if (pattern.endsWith('.*')) return key.startsWith(pattern.slice(0, -1))
|
|
148
|
+
return pattern === key
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Is the event covered by the selection (directly or by a wildcard)? */
|
|
152
|
+
export function isEventSelected(selection: string[], key: string): boolean {
|
|
153
|
+
return selection.some(p => eventMatches(p, key))
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function groupEvents(events: WebhookEvent[]): { family: string; items: WebhookEvent[] }[] {
|
|
157
|
+
const groups: { family: string; items: WebhookEvent[] }[] = []
|
|
158
|
+
for (const e of events) {
|
|
159
|
+
const f = eventFamily(e.key)
|
|
160
|
+
let entry = groups.find(x => x.family === f)
|
|
161
|
+
if (!entry) groups.push(entry = { family: f, items: [] })
|
|
162
|
+
entry.items.push(e)
|
|
163
|
+
}
|
|
164
|
+
return groups
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Toggles a whole family as `family.*`: on → replaces its individual events with the wildcard;
|
|
169
|
+
* off → removes the wildcard and every individual event of the family.
|
|
170
|
+
*/
|
|
171
|
+
export function toggleFamily(selection: string[], family: string, on: boolean): string[] {
|
|
172
|
+
const rest = selection.filter(p => p !== `${family}.*` && eventFamily(p) !== family)
|
|
173
|
+
return on ? [...rest, `${family}.*`] : rest
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Toggles one event. Turning one off while its family wildcard (or `*`) is selected expands the
|
|
178
|
+
* wildcard into the remaining events of the catalog.
|
|
179
|
+
*/
|
|
180
|
+
export function toggleEvent(selection: string[], key: string, on: boolean, catalog: WebhookEvent[]): string[] {
|
|
181
|
+
if (on) return isEventSelected(selection, key) ? selection : [...selection, key]
|
|
182
|
+
|
|
183
|
+
const family = eventFamily(key)
|
|
184
|
+
let next = selection
|
|
185
|
+
if (next.includes('*')) {
|
|
186
|
+
next = [...next.filter(p => p !== '*'), ...[...new Set(catalog.map(e => eventFamily(e.key)))].map(f => `${f}.*`)]
|
|
187
|
+
}
|
|
188
|
+
if (next.includes(`${family}.*`)) {
|
|
189
|
+
const siblings = catalog.map(e => e.key).filter(k => eventFamily(k) === family && k !== key)
|
|
190
|
+
next = [...next.filter(p => p !== `${family}.*`), ...siblings]
|
|
191
|
+
}
|
|
192
|
+
return next.filter(p => p !== key)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function familyState(selection: string[], family: string, catalog: WebhookEvent[]): 'all' | 'some' | 'none' {
|
|
196
|
+
if (selection.includes('*') || selection.includes(`${family}.*`)) return 'all'
|
|
197
|
+
const keys = catalog.map(e => e.key).filter(k => eventFamily(k) === family)
|
|
198
|
+
const n = keys.filter(k => selection.includes(k)).length
|
|
199
|
+
return n === 0 ? 'none' : n === keys.length ? 'all' : 'some'
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ── Validation ───────────────────────────────────────────────────────────────
|
|
203
|
+
|
|
204
|
+
/** Webhook URL: absolute https with a host (the server also blocks private addresses). */
|
|
205
|
+
export function validateWebhookUrl(url: string): string | null {
|
|
206
|
+
const v = (url || '').trim()
|
|
207
|
+
if (!v) return 'Ingresa la URL del receptor.'
|
|
208
|
+
let parsed: URL
|
|
209
|
+
try { parsed = new URL(v) } catch { return 'La URL no es válida.' }
|
|
210
|
+
if (parsed.protocol !== 'https:') return 'La URL debe usar https.'
|
|
211
|
+
if (!parsed.hostname) return 'La URL no es válida.'
|
|
212
|
+
if (parsed.username || parsed.password) return 'La URL no puede incluir credenciales.'
|
|
213
|
+
return null
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// ── Dates ────────────────────────────────────────────────────────────────────
|
|
217
|
+
|
|
218
|
+
/** Relative Spanish label ("hace 5 min", "en 3 días"). */
|
|
219
|
+
export function relativeTime(iso: string | null | undefined, now: Date = new Date()): string {
|
|
220
|
+
if (!iso) return '—'
|
|
221
|
+
const d = new Date(iso)
|
|
222
|
+
if (isNaN(d.getTime())) return '—'
|
|
223
|
+
const diff = Math.round((d.getTime() - now.getTime()) / 1000)
|
|
224
|
+
const abs = Math.abs(diff)
|
|
225
|
+
const fmt = (n: number, unit: string) => (diff < 0 ? `hace ${n} ${unit}` : `en ${n} ${unit}`)
|
|
226
|
+
if (abs < 45) return diff < 0 ? 'recién' : 'en unos segundos'
|
|
227
|
+
if (abs < 3600) return fmt(Math.round(abs / 60), 'min')
|
|
228
|
+
if (abs < 86400) { const h = Math.round(abs / 3600); return fmt(h, h === 1 ? 'hora' : 'horas') }
|
|
229
|
+
const days = Math.round(abs / 86400)
|
|
230
|
+
if (days < 30) return fmt(days, days === 1 ? 'día' : 'días')
|
|
231
|
+
return d.toLocaleDateString('es-CL', { day: 'numeric', month: 'short', year: 'numeric' })
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Expiry label for an API key. */
|
|
235
|
+
export function expiryLabel(expiresAt: string | null | undefined, now: Date = new Date()): string {
|
|
236
|
+
if (!expiresAt) return 'Sin vencimiento'
|
|
237
|
+
const d = new Date(expiresAt)
|
|
238
|
+
if (isNaN(d.getTime())) return 'Sin vencimiento'
|
|
239
|
+
return d.getTime() <= now.getTime() ? `Venció ${relativeTime(expiresAt, now)}` : `Vence ${relativeTime(expiresAt, now)}`
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function formatDateTime(iso: string | null | undefined): string {
|
|
243
|
+
if (!iso) return '—'
|
|
244
|
+
const d = new Date(iso)
|
|
245
|
+
if (isNaN(d.getTime())) return '—'
|
|
246
|
+
return d.toLocaleString('es-CL', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Expiry presets for the create form → ISO date (null = never). */
|
|
250
|
+
export const EXPIRY_PRESETS = [
|
|
251
|
+
{ value: '', label: 'Sin vencimiento' },
|
|
252
|
+
{ value: '30', label: '30 días' },
|
|
253
|
+
{ value: '90', label: '90 días' },
|
|
254
|
+
{ value: '365', label: '1 año' },
|
|
255
|
+
]
|
|
256
|
+
|
|
257
|
+
export function expiryFromPreset(days: string, now: Date = new Date()): string | null {
|
|
258
|
+
const n = Number(days)
|
|
259
|
+
if (!days || !Number.isFinite(n) || n <= 0) return null
|
|
260
|
+
return new Date(now.getTime() + n * 86400000).toISOString()
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Appends a cursor page to the accumulated list (dedup by id). */
|
|
264
|
+
export function appendPage<T extends { id: string | number }>(items: T[], page: T[]): T[] {
|
|
265
|
+
const seen = new Set(items.map(i => String(i.id)))
|
|
266
|
+
return [...items, ...page.filter(i => !seen.has(String(i.id)))]
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Pretty JSON for payload/headers previews. */
|
|
270
|
+
export function prettyJson(value: unknown): string {
|
|
271
|
+
if (value === null || value === undefined || value === '') return ''
|
|
272
|
+
if (typeof value === 'string') {
|
|
273
|
+
try { return JSON.stringify(JSON.parse(value), null, 2) } catch { return value }
|
|
274
|
+
}
|
|
275
|
+
try { return JSON.stringify(value, null, 2) } catch { return String(value) }
|
|
276
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Integraciones: API keys, webhooks y documentación de la API
|
|
2
|
+
|
|
3
|
+
Pantallas listas para montar en el producto sobre el motor de **innertia-laravel**
|
|
4
|
+
(`\Innertia\PublicApi`, `\Innertia\ApiKeys`, `\Innertia\Webhooks`). Ver también
|
|
5
|
+
`docs/webhooks-api.md` de innertia-laravel (eventos, scopes, descriptores y firma).
|
|
6
|
+
|
|
7
|
+
## Backend requerido
|
|
8
|
+
|
|
9
|
+
```php
|
|
10
|
+
// routes/api.private.php — gestión desde el backoffice (solo admins)
|
|
11
|
+
Route::middleware(['auth:api', 'tenant.require', 'permission:settings.manage'])
|
|
12
|
+
->prefix('integrations')
|
|
13
|
+
->group(fn () => \Innertia\PublicApi\Routes::manage());
|
|
14
|
+
|
|
15
|
+
// routes/api.php — especificación pública
|
|
16
|
+
\Innertia\PublicApi\Routes::docs(); // GET v1/openapi.json
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
`Routes::manage()` expone `api-keys` (lista, scopes, crear, rotar, revocar, registro de uso) y
|
|
20
|
+
`webhooks` (lista, catálogo de eventos, crear/editar/eliminar, rotar secreto, evento de prueba,
|
|
21
|
+
entregas, reenviar). Si se monta con otro prefijo, pásalo en la prop `endpoint`.
|
|
22
|
+
|
|
23
|
+
## Componentes
|
|
24
|
+
|
|
25
|
+
### `<Integrations.ApiKeys>`
|
|
26
|
+
|
|
27
|
+
Lista de claves del espacio, alta con permisos (scopes agrupados por recurso), sede opcional y
|
|
28
|
+
vencimiento; la clave (`pk_live_…`) se muestra **una sola vez** con botón copiar. Detalle con el
|
|
29
|
+
registro de uso (30 días, "Cargar más" por cursor), **Rotar** (la clave anterior convive 24 h) y
|
|
30
|
+
**Revocar** (inmediato).
|
|
31
|
+
|
|
32
|
+
### `<Integrations.Webhooks>`
|
|
33
|
+
|
|
34
|
+
Lista de suscripciones con estado (activo, pausado, con fallas, desactivado por fallas + motivo),
|
|
35
|
+
alta/edición con URL https, eventos (familias `call.*` o eventos sueltos), sede opcional y
|
|
36
|
+
permisos de datos sensibles (`people:pii`, `recordings:read`, … según los scopes que declaran los
|
|
37
|
+
eventos). El secreto `whsec_…` se muestra **una sola vez**. Detalle con entregas (filtro por estado,
|
|
38
|
+
payload, headers enviados, respuesta truncada a 64 KB), **Reenviar**, **Enviar evento de prueba**,
|
|
39
|
+
**Rotar secreto** (24 h firmando con ambos), **Pausar/Activar** y **Eliminar**.
|
|
40
|
+
|
|
41
|
+
Props comunes de ambos:
|
|
42
|
+
|
|
43
|
+
| Prop | Tipo | Default | Uso |
|
|
44
|
+
|---|---|---|---|
|
|
45
|
+
| `endpoint` | `string` | `'integrations'` | Prefijo donde el producto montó `Routes::manage()` |
|
|
46
|
+
| `organizations` | `{ value, label }[]` | `[]` | Sedes para limitar la clave/suscripción; si está vacío no se muestra el selector |
|
|
47
|
+
| `canManage` | `boolean` | `true` | `false` oculta crear/rotar/revocar/probar/reenviar (solo lectura) |
|
|
48
|
+
| `developersUrl` | `string` | `''` | Enlace "Documentación de la API" |
|
|
49
|
+
|
|
50
|
+
### `<Integrations.Developers>`
|
|
51
|
+
|
|
52
|
+
Referencia interactiva de la API (OpenAPI 3.1 con endpoints y eventos de webhook) con Scalar,
|
|
53
|
+
cargado en el cliente desde `cdn.jsdelivr.net/npm/@scalar/api-reference@1.76.4` (versión fija).
|
|
54
|
+
|
|
55
|
+
| Prop | Tipo | Uso |
|
|
56
|
+
|---|---|---|
|
|
57
|
+
| `specUrl` | `string` (requerida) | URL de `v1/openapi.json` del backend |
|
|
58
|
+
|
|
59
|
+
## Ejemplo (pomely, Sistema › Integraciones)
|
|
60
|
+
|
|
61
|
+
```vue
|
|
62
|
+
<script setup lang="ts">
|
|
63
|
+
const tab = ref<'keys' | 'webhooks' | 'connectors'>('keys')
|
|
64
|
+
const { can } = usePermissions()
|
|
65
|
+
const sites = computed(() => organizations.value.map(o => ({ value: o.id, label: o.name })))
|
|
66
|
+
</script>
|
|
67
|
+
|
|
68
|
+
<template>
|
|
69
|
+
<App.SegmentedControl v-model="tab" :options="[...]" />
|
|
70
|
+
<Integrations.ApiKeys v-if="tab === 'keys'" :organizations="sites" :can-manage="can('settings.manage')" developers-url="/developers" />
|
|
71
|
+
<Integrations.Webhooks v-else-if="tab === 'webhooks'" :organizations="sites" :can-manage="can('settings.manage')" developers-url="/developers" />
|
|
72
|
+
</template>
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
```vue
|
|
76
|
+
<!-- pages/developers.vue (pública) -->
|
|
77
|
+
<template>
|
|
78
|
+
<Integrations.Developers :spec-url="`${useRuntimeConfig().public.apiBase}/v1/openapi.json`" />
|
|
79
|
+
</template>
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Composables
|
|
83
|
+
|
|
84
|
+
`useApiKeys({ base })` → `{ list, scopes, create, rotate, revoke, requests(id, cursor) }` y
|
|
85
|
+
`useWebhooks({ base })` → `{ list, events, create, update, remove, rotateSecret, test, resend,
|
|
86
|
+
logs(id, { cursor, status }), log(id, logId) }` (vue-query). Los helpers puros (estados, comodines
|
|
87
|
+
de eventos, validación de URL, fechas) viven en `composables/useIntegrations/internal` y no se
|
|
88
|
+
auto-importan.
|
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', 'composables/useDriveBrowser', 'composables/useFileImports', 'composables/useFileVersions', 'composables/useNotificationPreferences'],
|
|
32
|
+
dirs: ['stores', 'composables', 'composables/useWorkflow', 'composables/useStorageTestRunner', 'composables/useNotificationHistory', 'composables/usePasskeys', 'composables/useDriveBrowser', 'composables/useFileImports', 'composables/useFileVersions', 'composables/useNotificationPreferences', 'composables/useIntegrations'],
|
|
33
33
|
presets: [
|
|
34
34
|
{
|
|
35
35
|
from: '@tanstack/vue-query',
|