mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 02:34:21 +00:00
feat(plugins): add quota-limited session storage API
This commit is contained in:
@@ -358,4 +358,29 @@ describe('PluginFrame', () => {
|
||||
expect(posted.find((m) => m.requestId === 's3')).toMatchObject({ type: 'trek:response', data: undefined });
|
||||
expect(posted.find((m) => m.requestId === 's4')).toMatchObject({ type: 'trek:response', data: ['flight'] });
|
||||
});
|
||||
|
||||
it('FE-PLUGINS-FRAME-022: session storage enforces key, value and key-count limits', () => {
|
||||
const { container } = render(<PluginFrame pluginId="demo" />);
|
||||
const iframe = container.querySelector('iframe')!;
|
||||
const posted: Array<Record<string, unknown>> = [];
|
||||
(iframe.contentWindow as unknown as { postMessage: (m: unknown) => void }).postMessage = (m: unknown) =>
|
||||
posted.push(m as Record<string, unknown>);
|
||||
const set = (requestId: string, key: string, value: unknown) => {
|
||||
fromFrame(iframe, { type: 'trek:session:set', requestId, key, value });
|
||||
return posted.find((message) => message.requestId === requestId);
|
||||
};
|
||||
|
||||
expect(set('bad-key', 'x'.repeat(65), 1)).toMatchObject({ type: 'trek:error', code: 'SESSION_INVALID_KEY' });
|
||||
expect(set('big-value', 'large', 'x'.repeat(1024))).toMatchObject({
|
||||
type: 'trek:error',
|
||||
code: 'SESSION_VALUE_TOO_LARGE',
|
||||
});
|
||||
expect(set('at-limits', 'x'.repeat(64), 'x'.repeat(1022))).toMatchObject({ type: 'trek:response' });
|
||||
|
||||
sessionStorage.clear();
|
||||
for (let index = 0; index < 32; index += 1) {
|
||||
expect(set(`key-${index}`, `key-${index}`, index)).toMatchObject({ type: 'trek:response' });
|
||||
}
|
||||
expect(set('too-many', 'key-32', 32)).toMatchObject({ type: 'trek:error', code: 'SESSION_KEY_LIMIT' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -148,12 +148,39 @@ interface ConfirmRequest {
|
||||
danger: boolean
|
||||
}
|
||||
|
||||
const PLUGIN_SESSION_NAMESPACE = 'trek:plugin-session:'
|
||||
const PLUGIN_SESSION_MAX_KEY_LENGTH = 64
|
||||
const PLUGIN_SESSION_MAX_KEYS = 32
|
||||
const PLUGIN_SESSION_MAX_VALUE_BYTES = 1024
|
||||
|
||||
/**
|
||||
* Returns all host-owned storage keys in one plugin scope (plugin-wide or a
|
||||
* specific trip), excluding TREK state and every other plugin/scope.
|
||||
*/
|
||||
function getScopedSessionKeys(scopeKeyPrefix: string) {
|
||||
const keys: string[] = []
|
||||
for (let i = 0; i < sessionStorage.length; i += 1) {
|
||||
const key = sessionStorage.key(i)
|
||||
if (key?.startsWith(scopeKeyPrefix)) keys.push(key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the prefix and full key for host-owned plugin session storage.
|
||||
*
|
||||
* Storage Keys:
|
||||
* trek:plugin-session:{userId}:{pluginId}:plugin:{key}
|
||||
* trek:plugin-session:{userId}:{pluginId}:trip:{tripId}:{key}
|
||||
*
|
||||
* Scope Prefix:
|
||||
* trek:plugin-session:{userId}:{pluginId}:plugin
|
||||
* trek:plugin-session:{userId}:{pluginId}:trip:{tripId}
|
||||
*
|
||||
* Plugin Prefix:
|
||||
* trek:plugin-session:{userId}:{pluginId}
|
||||
*
|
||||
*
|
||||
* Each dynamic segment is URI-encoded, so plugin-controlled values cannot alter
|
||||
* the key format. For clear, omit logicalKey; the returned full key is then
|
||||
* the same as the scoped prefix.
|
||||
@@ -165,17 +192,17 @@ function createPluginSessionStorageKeys(
|
||||
tripId: string | null,
|
||||
logicalKey?: string,
|
||||
) {
|
||||
const namespace = 'trek:plugin-session:'
|
||||
const encodedUserId = encodeURIComponent(String(userId))
|
||||
const encodedPluginId = encodeURIComponent(pluginId)
|
||||
const encodedTripId = scope === 'trip' ? encodeURIComponent(tripId!) : null
|
||||
const encodedLogicalKey = logicalKey === undefined ? undefined : encodeURIComponent(logicalKey)
|
||||
const pluginKeyPrefix = `${PLUGIN_SESSION_NAMESPACE}${encodeURIComponent(String(userId))}:${encodeURIComponent(pluginId)}:`
|
||||
|
||||
const storageScopeSegment = encodedTripId === null ? scope : `${scope}:${encodedTripId}`
|
||||
const storageKeyPrefix = `${namespace}${encodedUserId}:${encodedPluginId}:${storageScopeSegment}:`
|
||||
const storageKey = encodedLogicalKey === undefined ? storageKeyPrefix : `${storageKeyPrefix}${encodedLogicalKey}`
|
||||
// Scope is either :plugin: or :trip:${tripId}:
|
||||
const scopeSegment = scope === 'trip' ? `trip:${encodeURIComponent(tripId!)}` : 'plugin'
|
||||
const scopeKeyPrefix = `${pluginKeyPrefix}${scopeSegment}:`
|
||||
|
||||
const encodedLogicalKey = logicalKey === undefined ? undefined : encodeURIComponent(logicalKey)
|
||||
const storageKey = encodedLogicalKey === undefined ? scopeKeyPrefix : `${scopeKeyPrefix}${encodedLogicalKey}`
|
||||
return {
|
||||
storageKeyPrefix,
|
||||
pluginKeyPrefix,
|
||||
scopeKeyPrefix,
|
||||
storageKey,
|
||||
}
|
||||
}
|
||||
@@ -397,14 +424,9 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
|
||||
break
|
||||
}
|
||||
|
||||
const { storageKeyPrefix } = createPluginSessionStorageKeys(userId, pluginId, scope, tripId)
|
||||
const { scopeKeyPrefix } = createPluginSessionStorageKeys(userId, pluginId, scope, tripId)
|
||||
try {
|
||||
const keysToRemove: string[] = []
|
||||
for (let i = 0; i < sessionStorage.length; i += 1) {
|
||||
const storageKey = sessionStorage.key(i)
|
||||
if (storageKey?.startsWith(storageKeyPrefix)) keysToRemove.push(storageKey)
|
||||
}
|
||||
keysToRemove.forEach((storageKey) => sessionStorage.removeItem(storageKey))
|
||||
getScopedSessionKeys(scopeKeyPrefix).forEach((storageKey) => sessionStorage.removeItem(storageKey))
|
||||
post({ type: 'trek:response', requestId: msg.requestId, data: undefined })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'session storage failed'
|
||||
@@ -420,7 +442,11 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
|
||||
post({ type: 'trek:error', requestId: msg.requestId, code: 'NO_TRIP_CONTEXT', message: 'trip session storage requires a trip context' })
|
||||
break
|
||||
}
|
||||
const { storageKey } = createPluginSessionStorageKeys(userId, pluginId, scope, tripId, msg.key)
|
||||
if (typeof msg.key !== 'string' || msg.key.length === 0 || msg.key.length > PLUGIN_SESSION_MAX_KEY_LENGTH) {
|
||||
post({ type: 'trek:error', requestId: msg.requestId, code: 'SESSION_INVALID_KEY', message: `session key must be 1-${PLUGIN_SESSION_MAX_KEY_LENGTH} characters` })
|
||||
break
|
||||
}
|
||||
const { scopeKeyPrefix, storageKey } = createPluginSessionStorageKeys(userId, pluginId, scope, tripId, msg.key)
|
||||
try {
|
||||
if (msg.type === 'trek:session:get') {
|
||||
const storedValue = sessionStorage.getItem(storageKey)
|
||||
@@ -434,6 +460,18 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
|
||||
post({ type: 'trek:error', requestId: msg.requestId, code: 'SESSION_INVALID_VALUE', message: 'session value must be JSON-serialisable' })
|
||||
break
|
||||
}
|
||||
|
||||
// Validate length based on unicode byte sizes
|
||||
const valueBytes = new TextEncoder().encode(serializedValue).byteLength
|
||||
if (valueBytes > PLUGIN_SESSION_MAX_VALUE_BYTES) {
|
||||
post({ type: 'trek:error', requestId: msg.requestId, code: 'SESSION_VALUE_TOO_LARGE', message: `session value exceeds ${PLUGIN_SESSION_MAX_VALUE_BYTES} bytes` })
|
||||
break
|
||||
}
|
||||
const keys = getScopedSessionKeys(scopeKeyPrefix)
|
||||
if (!keys.includes(storageKey) && keys.length >= PLUGIN_SESSION_MAX_KEYS) {
|
||||
post({ type: 'trek:error', requestId: msg.requestId, code: 'SESSION_KEY_LIMIT', message: `plugin session storage allows at most ${PLUGIN_SESSION_MAX_KEYS} keys` })
|
||||
break
|
||||
}
|
||||
sessionStorage.setItem(storageKey, serializedValue)
|
||||
post({ type: 'trek:response', requestId: msg.requestId, data: undefined })
|
||||
break
|
||||
|
||||
@@ -7,6 +7,7 @@ const initial = usePluginStore.getState();
|
||||
|
||||
beforeEach(() => {
|
||||
usePluginStore.setState(initial, true);
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
describe('pluginStore', () => {
|
||||
@@ -36,10 +37,12 @@ describe('pluginStore', () => {
|
||||
});
|
||||
|
||||
it('FE-STORE-PLUGIN-002: a failed fetch still marks the store loaded (no crash)', async () => {
|
||||
sessionStorage.setItem('trek:plugin-session:7:active:plugin:filters', '["flight"]');
|
||||
server.use(http.get('/api/plugins', () => HttpResponse.error()));
|
||||
await usePluginStore.getState().loadPlugins();
|
||||
expect(usePluginStore.getState().loaded).toBe(true);
|
||||
expect(usePluginStore.getState().plugins).toEqual([]);
|
||||
expect(sessionStorage.getItem('trek:plugin-session:7:active:plugin:filters')).toBe('["flight"]');
|
||||
});
|
||||
|
||||
it('FE-STORE-PLUGIN-003: tolerates a missing plugins array', async () => {
|
||||
@@ -47,4 +50,26 @@ describe('pluginStore', () => {
|
||||
await usePluginStore.getState().loadPlugins();
|
||||
expect(usePluginStore.getState().plugins).toEqual([]);
|
||||
});
|
||||
|
||||
it('FE-STORE-PLUGIN-004: clears session state for disabled plugins after a successful refresh', async () => {
|
||||
sessionStorage.setItem('trek:plugin-session:7:active:plugin:filters', '["flight"]');
|
||||
sessionStorage.setItem('trek:plugin-session:7:disabled:plugin:filters', '["hotel"]');
|
||||
sessionStorage.setItem('trek:plugin-session:7:disabled:trip:42:view', '"table"');
|
||||
sessionStorage.setItem('trek_session', 'app-session');
|
||||
|
||||
server.use(
|
||||
http.get('/api/plugins', () =>
|
||||
HttpResponse.json({
|
||||
plugins: [{ id: 'active', name: 'Active', type: 'widget', icon: null }],
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await usePluginStore.getState().loadPlugins();
|
||||
|
||||
expect(sessionStorage.getItem('trek:plugin-session:7:active:plugin:filters')).toBe('["flight"]');
|
||||
expect(sessionStorage.getItem('trek:plugin-session:7:disabled:plugin:filters')).toBeNull();
|
||||
expect(sessionStorage.getItem('trek:plugin-session:7:disabled:trip:42:view')).toBeNull();
|
||||
expect(sessionStorage.getItem('trek_session')).toBe('app-session');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,28 @@
|
||||
import { create } from 'zustand'
|
||||
import { pluginsApi } from '../api/client'
|
||||
|
||||
const PLUGIN_SESSION_NAMESPACE = 'trek:plugin-session:'
|
||||
|
||||
/**
|
||||
* Purges state for plugins absent from a successful active-plugin response.
|
||||
* A failed request never calls this, because plugin status is then unknown.
|
||||
*/
|
||||
function clearInactivePluginSessions(activePluginIds: Set<string>) {
|
||||
const keysToRemove: string[] = []
|
||||
for (let i = 0; i < sessionStorage.length; i += 1) {
|
||||
const storageKey = sessionStorage.key(i)
|
||||
if (!storageKey?.startsWith(PLUGIN_SESSION_NAMESPACE)) continue
|
||||
const encodedPluginId = storageKey.slice(PLUGIN_SESSION_NAMESPACE.length).split(':')[1]
|
||||
if (encodedPluginId === undefined) continue
|
||||
try {
|
||||
if (!activePluginIds.has(decodeURIComponent(encodedPluginId))) keysToRemove.push(storageKey)
|
||||
} catch {
|
||||
// Ignore malformed keys outside the host-owned format.
|
||||
}
|
||||
}
|
||||
keysToRemove.forEach((storageKey) => sessionStorage.removeItem(storageKey))
|
||||
}
|
||||
|
||||
/**
|
||||
* Active plugins the client renders (#plugins, M3). Page plugins become nav
|
||||
* entries + a full-page iframe route; widget plugins mount on the dashboard.
|
||||
@@ -47,7 +69,9 @@ export const usePluginStore = create<PluginState>((set, get) => ({
|
||||
loadPlugins: async () => {
|
||||
try {
|
||||
const data = await pluginsApi.active()
|
||||
set({ plugins: (data.plugins as ActivePlugin[]) || [], loaded: true })
|
||||
const plugins = (data.plugins as ActivePlugin[]) || []
|
||||
clearInactivePluginSessions(new Set(plugins.map((plugin) => plugin.id)))
|
||||
set({ plugins, loaded: true })
|
||||
} catch {
|
||||
set({ loaded: true })
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user