@nodestackapp/server 2.5.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/README.md +40 -28
  2. package/dist/NodeStack.d.ts +1 -1
  3. package/dist/NodeStack.d.ts.map +1 -1
  4. package/dist/NodeStack.js +73 -12
  5. package/dist/NodeStack.js.map +1 -1
  6. package/dist/admin/AdminUIBundler.d.ts.map +1 -1
  7. package/dist/admin/AdminUIBundler.js +1 -0
  8. package/dist/admin/AdminUIBundler.js.map +1 -1
  9. package/dist/admin/ui/css/main.css +34 -0
  10. package/dist/admin/ui/css/webhooks.css +8 -0
  11. package/dist/admin/ui/index.html +19150 -17212
  12. package/dist/admin/ui/js/api-keys.js +1381 -0
  13. package/dist/admin/ui/js/app.js +667 -641
  14. package/dist/admin/ui/js/apps.js +496 -489
  15. package/dist/admin/ui/js/collections.js +486 -484
  16. package/dist/admin/ui/js/command-palette.js +683 -673
  17. package/dist/admin/ui/js/flows-designer.js +1125 -1076
  18. package/dist/admin/ui/js/flows.js +908 -890
  19. package/dist/admin/ui/js/functions-tester.js +1 -1
  20. package/dist/admin/ui/js/functions-workbench.js +1144 -1101
  21. package/dist/admin/ui/js/functions.js +980 -979
  22. package/dist/admin/ui/js/rules.js +1080 -775
  23. package/dist/admin/ui/js/schema.js +346 -304
  24. package/dist/admin/ui/js/views.js +1 -1
  25. package/dist/apps/AppManager.d.ts +1 -1
  26. package/dist/apps/AppManager.d.ts.map +1 -1
  27. package/dist/apps/AppManager.js +4 -18
  28. package/dist/apps/AppManager.js.map +1 -1
  29. package/dist/apps/AppRegistry.d.ts +1 -0
  30. package/dist/apps/AppRegistry.d.ts.map +1 -1
  31. package/dist/apps/AppRegistry.js +78 -23
  32. package/dist/apps/AppRegistry.js.map +1 -1
  33. package/dist/apps/AppScope.d.ts +0 -1
  34. package/dist/apps/AppScope.d.ts.map +1 -1
  35. package/dist/apps/AppScope.js +5 -15
  36. package/dist/apps/AppScope.js.map +1 -1
  37. package/dist/auth/ApiKeyService.d.ts +62 -2
  38. package/dist/auth/ApiKeyService.d.ts.map +1 -1
  39. package/dist/auth/ApiKeyService.js +503 -8
  40. package/dist/auth/ApiKeyService.js.map +1 -1
  41. package/dist/auth/AuthService.d.ts +30 -1
  42. package/dist/auth/AuthService.d.ts.map +1 -1
  43. package/dist/auth/AuthService.js +468 -65
  44. package/dist/auth/AuthService.js.map +1 -1
  45. package/dist/auth/oauth/AppleProvider.d.ts +2 -0
  46. package/dist/auth/oauth/AppleProvider.d.ts.map +1 -1
  47. package/dist/auth/oauth/AppleProvider.js +40 -3
  48. package/dist/auth/oauth/AppleProvider.js.map +1 -1
  49. package/dist/auth/oauth/BaseOAuthProvider.d.ts +3 -2
  50. package/dist/auth/oauth/BaseOAuthProvider.d.ts.map +1 -1
  51. package/dist/auth/oauth/BaseOAuthProvider.js +29 -3
  52. package/dist/auth/oauth/BaseOAuthProvider.js.map +1 -1
  53. package/dist/auth/oauth/DiscordProvider.d.ts.map +1 -1
  54. package/dist/auth/oauth/DiscordProvider.js +4 -1
  55. package/dist/auth/oauth/DiscordProvider.js.map +1 -1
  56. package/dist/auth/oauth/GitHubProvider.d.ts.map +1 -1
  57. package/dist/auth/oauth/GitHubProvider.js +4 -1
  58. package/dist/auth/oauth/GitHubProvider.js.map +1 -1
  59. package/dist/auth/oauth/GoogleProvider.d.ts.map +1 -1
  60. package/dist/auth/oauth/GoogleProvider.js +4 -1
  61. package/dist/auth/oauth/GoogleProvider.js.map +1 -1
  62. package/dist/auth/oauth/MicrosoftProvider.d.ts.map +1 -1
  63. package/dist/auth/oauth/MicrosoftProvider.js +4 -1
  64. package/dist/auth/oauth/MicrosoftProvider.js.map +1 -1
  65. package/dist/auth/oauth/OAuthProviderRegistry.d.ts +6 -2
  66. package/dist/auth/oauth/OAuthProviderRegistry.d.ts.map +1 -1
  67. package/dist/auth/oauth/OAuthProviderRegistry.js +25 -10
  68. package/dist/auth/oauth/OAuthProviderRegistry.js.map +1 -1
  69. package/dist/auth/oauth/types.d.ts +4 -2
  70. package/dist/auth/oauth/types.d.ts.map +1 -1
  71. package/dist/cli/cli.d.ts.map +1 -1
  72. package/dist/cli/cli.js +228 -12
  73. package/dist/cli/cli.js.map +1 -1
  74. package/dist/core/config/ConfigService.d.ts.map +1 -1
  75. package/dist/core/config/ConfigService.js +5 -3
  76. package/dist/core/config/ConfigService.js.map +1 -1
  77. package/dist/core/config/EnvLoader.d.ts +14 -0
  78. package/dist/core/config/EnvLoader.d.ts.map +1 -1
  79. package/dist/core/config/EnvLoader.js +44 -0
  80. package/dist/core/config/EnvLoader.js.map +1 -1
  81. package/dist/core/container/Container.d.ts +14 -0
  82. package/dist/core/container/Container.d.ts.map +1 -1
  83. package/dist/core/container/Container.js +32 -0
  84. package/dist/core/container/Container.js.map +1 -1
  85. package/dist/core/errors/AppError.d.ts +7 -7
  86. package/dist/core/errors/AppError.d.ts.map +1 -1
  87. package/dist/core/errors/AppError.js +18 -14
  88. package/dist/core/errors/AppError.js.map +1 -1
  89. package/dist/core/events/EventBus.d.ts.map +1 -1
  90. package/dist/core/events/EventBus.js +36 -6
  91. package/dist/core/events/EventBus.js.map +1 -1
  92. package/dist/core/maintenance/MaintenanceGate.d.ts +47 -0
  93. package/dist/core/maintenance/MaintenanceGate.d.ts.map +1 -1
  94. package/dist/core/maintenance/MaintenanceGate.js +265 -7
  95. package/dist/core/maintenance/MaintenanceGate.js.map +1 -1
  96. package/dist/core/plugins/PluginManager.d.ts +20 -1
  97. package/dist/core/plugins/PluginManager.d.ts.map +1 -1
  98. package/dist/core/plugins/PluginManager.js +231 -146
  99. package/dist/core/plugins/PluginManager.js.map +1 -1
  100. package/dist/core/plugins/types.d.ts +48 -31
  101. package/dist/core/plugins/types.d.ts.map +1 -1
  102. package/dist/database/DatabaseService.d.ts +1 -0
  103. package/dist/database/DatabaseService.d.ts.map +1 -1
  104. package/dist/database/DatabaseService.js +24 -6
  105. package/dist/database/DatabaseService.js.map +1 -1
  106. package/dist/database/drivers/DriverRegistry.d.ts +1 -0
  107. package/dist/database/drivers/DriverRegistry.d.ts.map +1 -1
  108. package/dist/database/drivers/DriverRegistry.js +29 -0
  109. package/dist/database/drivers/DriverRegistry.js.map +1 -1
  110. package/dist/database/drivers/IDatabaseDriver.d.ts +1 -0
  111. package/dist/database/drivers/IDatabaseDriver.d.ts.map +1 -1
  112. package/dist/database/drivers/MssqlDriver.d.ts.map +1 -1
  113. package/dist/database/drivers/MssqlDriver.js +8 -2
  114. package/dist/database/drivers/MssqlDriver.js.map +1 -1
  115. package/dist/database/drivers/NodeSqliteDriver.d.ts.map +1 -1
  116. package/dist/database/drivers/NodeSqliteDriver.js +15 -1
  117. package/dist/database/drivers/NodeSqliteDriver.js.map +1 -1
  118. package/dist/database/migrations/SystemMigrations.d.ts.map +1 -1
  119. package/dist/database/migrations/SystemMigrations.js +62 -5
  120. package/dist/database/migrations/SystemMigrations.js.map +1 -1
  121. package/dist/flows/FlowEngine.js.map +1 -1
  122. package/dist/flows/FlowService.d.ts +7 -1
  123. package/dist/flows/FlowService.d.ts.map +1 -1
  124. package/dist/flows/FlowService.js +126 -12
  125. package/dist/flows/FlowService.js.map +1 -1
  126. package/dist/flows/FlowValidator.d.ts +1 -0
  127. package/dist/flows/FlowValidator.d.ts.map +1 -1
  128. package/dist/flows/FlowValidator.js +76 -1
  129. package/dist/flows/FlowValidator.js.map +1 -1
  130. package/dist/flows/types.d.ts +14 -2
  131. package/dist/flows/types.d.ts.map +1 -1
  132. package/dist/functions/FunctionService.d.ts +5 -1
  133. package/dist/functions/FunctionService.d.ts.map +1 -1
  134. package/dist/functions/FunctionService.js +84 -33
  135. package/dist/functions/FunctionService.js.map +1 -1
  136. package/dist/functions/runtime/QuickJsWasmRuntime.d.ts.map +1 -1
  137. package/dist/functions/runtime/QuickJsWasmRuntime.js +19 -10
  138. package/dist/functions/runtime/QuickJsWasmRuntime.js.map +1 -1
  139. package/dist/functions/types.d.ts +16 -2
  140. package/dist/functions/types.d.ts.map +1 -1
  141. package/dist/http/HttpServer.d.ts +3 -0
  142. package/dist/http/HttpServer.d.ts.map +1 -1
  143. package/dist/http/HttpServer.js +153 -6
  144. package/dist/http/HttpServer.js.map +1 -1
  145. package/dist/http/controllers/ApiKeyController.d.ts +1 -0
  146. package/dist/http/controllers/ApiKeyController.d.ts.map +1 -1
  147. package/dist/http/controllers/ApiKeyController.js +47 -1
  148. package/dist/http/controllers/ApiKeyController.js.map +1 -1
  149. package/dist/http/controllers/AuthController.d.ts +12 -0
  150. package/dist/http/controllers/AuthController.d.ts.map +1 -1
  151. package/dist/http/controllers/AuthController.js +40 -2
  152. package/dist/http/controllers/AuthController.js.map +1 -1
  153. package/dist/http/controllers/FlowController.d.ts.map +1 -1
  154. package/dist/http/controllers/FlowController.js +45 -4
  155. package/dist/http/controllers/FlowController.js.map +1 -1
  156. package/dist/http/controllers/FunctionController.d.ts.map +1 -1
  157. package/dist/http/controllers/FunctionController.js +16 -2
  158. package/dist/http/controllers/FunctionController.js.map +1 -1
  159. package/dist/http/controllers/HealthController.js +2 -2
  160. package/dist/http/middleware/AppResolutionMiddleware.d.ts +1 -1
  161. package/dist/http/middleware/AppResolutionMiddleware.d.ts.map +1 -1
  162. package/dist/http/middleware/AppResolutionMiddleware.js +2 -3
  163. package/dist/http/middleware/AppResolutionMiddleware.js.map +1 -1
  164. package/dist/http/middleware/AuthMiddleware.d.ts.map +1 -1
  165. package/dist/http/middleware/AuthMiddleware.js +6 -3
  166. package/dist/http/middleware/AuthMiddleware.js.map +1 -1
  167. package/dist/http/middleware/ChaosMiddleware.js +6 -6
  168. package/dist/http/middleware/ChaosMiddleware.js.map +1 -1
  169. package/dist/index.d.ts +2 -2
  170. package/dist/index.d.ts.map +1 -1
  171. package/dist/index.js +6 -2
  172. package/dist/index.js.map +1 -1
  173. package/dist/queue/QueueService.d.ts +9 -0
  174. package/dist/queue/QueueService.d.ts.map +1 -1
  175. package/dist/queue/QueueService.js +143 -60
  176. package/dist/queue/QueueService.js.map +1 -1
  177. package/dist/queue/drivers/SqliteQueueDriver.d.ts +3 -0
  178. package/dist/queue/drivers/SqliteQueueDriver.d.ts.map +1 -1
  179. package/dist/queue/drivers/SqliteQueueDriver.js +315 -255
  180. package/dist/queue/drivers/SqliteQueueDriver.js.map +1 -1
  181. package/dist/records/FtsService.d.ts +7 -3
  182. package/dist/records/FtsService.d.ts.map +1 -1
  183. package/dist/records/FtsService.js +69 -5
  184. package/dist/records/FtsService.js.map +1 -1
  185. package/dist/records/QueryFilterParser.d.ts.map +1 -1
  186. package/dist/records/QueryFilterParser.js +58 -20
  187. package/dist/records/QueryFilterParser.js.map +1 -1
  188. package/dist/records/RecordSanitizer.d.ts.map +1 -1
  189. package/dist/records/RecordSanitizer.js +32 -4
  190. package/dist/records/RecordSanitizer.js.map +1 -1
  191. package/dist/records/RecordService.d.ts +6 -0
  192. package/dist/records/RecordService.d.ts.map +1 -1
  193. package/dist/records/RecordService.js +95 -14
  194. package/dist/records/RecordService.js.map +1 -1
  195. package/dist/records/RecordValidator.d.ts +10 -0
  196. package/dist/records/RecordValidator.d.ts.map +1 -1
  197. package/dist/records/RecordValidator.js +110 -2
  198. package/dist/records/RecordValidator.js.map +1 -1
  199. package/dist/records/fts/IFtsDriver.d.ts +7 -6
  200. package/dist/records/fts/IFtsDriver.d.ts.map +1 -1
  201. package/dist/records/fts/MssqlFtsDriver.d.ts +5 -1
  202. package/dist/records/fts/MssqlFtsDriver.d.ts.map +1 -1
  203. package/dist/records/fts/MssqlFtsDriver.js +35 -3
  204. package/dist/records/fts/MssqlFtsDriver.js.map +1 -1
  205. package/dist/records/fts/PostgresFtsDriver.d.ts +9 -2
  206. package/dist/records/fts/PostgresFtsDriver.d.ts.map +1 -1
  207. package/dist/records/fts/PostgresFtsDriver.js +116 -11
  208. package/dist/records/fts/PostgresFtsDriver.js.map +1 -1
  209. package/dist/records/fts/SqliteFts5Driver.d.ts +7 -1
  210. package/dist/records/fts/SqliteFts5Driver.d.ts.map +1 -1
  211. package/dist/records/fts/SqliteFts5Driver.js +66 -6
  212. package/dist/records/fts/SqliteFts5Driver.js.map +1 -1
  213. package/dist/schema/OpenApiGenerator.d.ts.map +1 -1
  214. package/dist/schema/OpenApiGenerator.js +103 -3
  215. package/dist/schema/OpenApiGenerator.js.map +1 -1
  216. package/dist/schema/models/Field.d.ts +1 -0
  217. package/dist/schema/models/Field.d.ts.map +1 -1
  218. package/dist/templates/definitions/ecommerce.js +6 -6
  219. package/dist/templates/definitions/ecommerce.js.map +1 -1
  220. package/dist/webhooks/WebhookService.js +1 -1
  221. package/package.json +4 -3
@@ -0,0 +1,1381 @@
1
+ // ==========================================
2
+ // API Keys & Visual Scope Matrix Management
3
+ // ==========================================
4
+
5
+ const apiKeysState = {
6
+ keys: [],
7
+ functions: [],
8
+ flows: [],
9
+ queues: [],
10
+ isLoading: false,
11
+ editingKeyId: null,
12
+ lastFocusedElement: null,
13
+ };
14
+
15
+ function setAppShellInert(isInert) {
16
+ if (typeof document === 'undefined') return;
17
+ const appRoot = document.getElementById('app');
18
+ if (!appRoot) return;
19
+ try {
20
+ if (isInert) {
21
+ appRoot.setAttribute('inert', '');
22
+ } else {
23
+ appRoot.removeAttribute('inert');
24
+ }
25
+ } catch (_) {}
26
+ }
27
+
28
+ function updateSidebarApiKeysBadge(keysList) {
29
+ if (typeof document === 'undefined') return;
30
+ const badge = document.getElementById('sidebar-api-keys-count');
31
+ if (!badge) return;
32
+ const list = Array.isArray(keysList) ? keysList : apiKeysState.keys;
33
+ const activeCount = list.filter(k => k.status === 'active').length;
34
+ badge.textContent = String(activeCount);
35
+ badge.style.display = activeCount > 0 ? 'inline-block' : 'none';
36
+ }
37
+
38
+ function getApiKeysApiPrefix() {
39
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : (typeof state !== 'undefined' && state?.activeApp?.slug) || 'default';
40
+ return slug && slug !== 'default' ? `/api/apps/${encodeURIComponent(slug)}/api-keys` : '/api/api-keys';
41
+ }
42
+
43
+ async function loadApiKeys() {
44
+ apiKeysState.isLoading = true;
45
+ if (state.activeNav === 'api-keys') {
46
+ renderApiKeysView();
47
+ }
48
+ try {
49
+ const res = await api(getApiKeysApiPrefix());
50
+ apiKeysState.keys = Array.isArray(res) ? res : (res?.items || []);
51
+ updateSidebarApiKeysBadge(apiKeysState.keys);
52
+ } catch (err) {
53
+ apiKeysState.keys = [];
54
+ if (state.activeNav === 'api-keys' && typeof toast === 'function') {
55
+ toast('Failed to load API keys: ' + (err.message || err), 'error');
56
+ }
57
+ } finally {
58
+ apiKeysState.isLoading = false;
59
+ if (state.activeNav === 'api-keys') {
60
+ renderApiKeysView();
61
+ }
62
+ }
63
+ }
64
+
65
+ function formatApiKeyDate(iso) {
66
+ if (!iso) return '—';
67
+ const d = new Date(iso);
68
+ if (isNaN(d.getTime())) return escapeHtml(String(iso));
69
+ return d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
70
+ }
71
+
72
+ function renderScopeChipsHtml(key) {
73
+ if (key.role === 'admin' || (Array.isArray(key.scopes) && (key.scopes.includes('*') || key.scopes.includes('admin:*')))) {
74
+ return '<span class="badge badge-danger" style="font-size: 10.5px;">Full Admin (*)</span>';
75
+ }
76
+ const scopes = Array.isArray(key.scopes) ? key.scopes : [];
77
+ if (scopes.length === 0) {
78
+ return '<span style="font-size: 11px; color: var(--text-muted); font-style: italic;">No scopes assigned</span>';
79
+ }
80
+ const visible = scopes.slice(0, 4);
81
+ const extra = scopes.length - visible.length;
82
+ return `
83
+ <div style="display: flex; flex-wrap: wrap; gap: 4px; max-width: 320px;">
84
+ ${visible.map(s => `<code style="font-size: 10.5px; padding: 1px 6px; border-radius: 4px; background: var(--bg-card-hover); border: 1px solid var(--border-subtle); color: var(--text-main);">${escapeHtml(s)}</code>`).join('')}
85
+ ${extra > 0 ? `<span class="badge badge-primary" style="font-size: 10px;">+${extra} more</span>` : ''}
86
+ </div>
87
+ `;
88
+ }
89
+
90
+ function renderApiKeysView() {
91
+ const container = document.getElementById('page-view-api-keys');
92
+ if (!container) return;
93
+
94
+ const keys = apiKeysState.keys || [];
95
+ const activeCount = keys.filter(k => k.status === 'active').length;
96
+ const scopedCount = keys.filter(k => k.status === 'active' && k.role !== 'admin' && !(k.scopes || []).includes('*')).length;
97
+ const adminCount = keys.filter(k => k.status === 'active' && (k.role === 'admin' || (k.scopes || []).includes('*'))).length;
98
+ const totalRequests = keys.reduce((sum, k) => sum + Number(k.totalRequests || 0), 0);
99
+
100
+ const activeAppLabel = (typeof state !== 'undefined' && state.activeApp)
101
+ ? `${state.activeApp.name || 'Default App'} (${state.activeApp.slug || 'default'})`
102
+ : 'Default App (default)';
103
+
104
+ container.innerHTML = `
105
+ <div class="webhooks-container" style="max-width: 1400px; margin: 0 auto; padding: 1.5rem; display: flex; flex-direction: column; gap: 1.25rem;">
106
+ <!-- Header -->
107
+ <div class="webhooks-header">
108
+ <div class="webhooks-title-area">
109
+ <h2>
110
+ <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
111
+ <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/>
112
+ </svg>
113
+ API Keys
114
+ </h2>
115
+ <p>
116
+ Provision scoped machine-to-machine credentials for <strong style="color: var(--accent-primary); font-family: var(--font-mono);">${escapeHtml(activeAppLabel)}</strong> across Collections, Functions, Flows, and Queues.
117
+ </p>
118
+ </div>
119
+ <div style="display: flex; align-items: center; gap: 8px;">
120
+ <button type="button" class="btn btn-secondary btn-sm" onclick="loadApiKeys()" aria-label="Refresh API keys list" title="Refresh API keys">
121
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
122
+ Refresh
123
+ </button>
124
+ <button type="button" id="btn-create-api-key" class="btn btn-primary btn-sm" onclick="openApiKeyDrawer()" style="font-weight: 600;">
125
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
126
+ Create API Key
127
+ </button>
128
+ </div>
129
+ </div>
130
+
131
+ <!-- Summary Metric Cards -->
132
+ <div class="webhooks-stats-grid" id="api-keys-stats-grid">
133
+ <div class="webhook-stat-card">
134
+ <span class="webhook-stat-label">Active Keys</span>
135
+ <div class="webhook-stat-value">${activeCount}</div>
136
+ </div>
137
+ <div class="webhook-stat-card">
138
+ <span class="webhook-stat-label">Scoped Service Keys</span>
139
+ <div class="webhook-stat-value" style="color: var(--accent-primary);">${scopedCount}</div>
140
+ </div>
141
+ <div class="webhook-stat-card">
142
+ <span class="webhook-stat-label">Full Admin Keys</span>
143
+ <div class="webhook-stat-value" style="color: ${adminCount > 0 ? 'var(--accent-danger)' : 'var(--text-heading)'};">${adminCount}</div>
144
+ </div>
145
+ <div class="webhook-stat-card">
146
+ <span class="webhook-stat-label">Total Requests</span>
147
+ <div class="webhook-stat-value">${totalRequests}</div>
148
+ </div>
149
+ </div>
150
+
151
+ <!-- Main Content / Table Region -->
152
+ ${apiKeysState.isLoading && keys.length === 0 ? `
153
+ <div style="padding: 4rem 2rem; text-align: center; background: var(--bg-card); border: 1px solid var(--border-subtle); border-radius: 8px; color: var(--text-muted); font-size: 13px; box-shadow: 0 1px 3px rgba(0,0,0,0.05);">
154
+ <span class="spinner" style="margin-right: 8px; display: inline-block;"></span> Loading API keys...
155
+ </div>
156
+ ` : keys.length === 0 ? `
157
+ <div style="text-align: center; padding: 4rem 2rem; background: var(--bg-card); border: 1px dashed var(--border-subtle); border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.05);">
158
+ <div style="display: flex; justify-content: center; margin-bottom: 0.75rem;" aria-hidden="true">
159
+ <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="color: var(--text-muted);"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
160
+ </div>
161
+ <h3 style="font-size: 1.1rem; font-weight: 700; color: var(--text-heading); margin: 0 0 0.5rem 0;">No API Keys Configured</h3>
162
+ <p style="font-size: 0.85rem; color: var(--text-muted); max-width: 480px; margin: 0 auto 1.5rem auto; line-height: 1.5;">
163
+ Create a scoped API key to grant microservices least-privilege access to specific collections, functions, queues, or HTTP flows without sharing superuser credentials.
164
+ </p>
165
+ <button type="button" class="btn btn-primary btn-sm" onclick="openApiKeyDrawer()" style="font-weight: 600;">+ Create First API Key</button>
166
+ </div>
167
+ ` : `
168
+ <div class="webhook-table-wrapper" style="box-shadow: 0 1px 3px rgba(0,0,0,0.05); overflow-x: auto; width: 100%;">
169
+ <table class="webhook-table" style="min-width: 1100px; width: 100%; border-collapse: collapse;">
170
+ <caption id="api-keys-table-caption" class="visually-hidden">Configured API keys and access scopes</caption>
171
+ <thead>
172
+ <tr>
173
+ <th scope="col" style="min-width: 200px; width: 20%;">Name &amp; Description</th>
174
+ <th scope="col" style="min-width: 140px; width: 14%;">Key Prefix</th>
175
+ <th scope="col" style="min-width: 250px; width: 24%;">Permissions / Scopes</th>
176
+ <th scope="col" style="min-width: 130px; width: 12%;">Status &amp; Usage</th>
177
+ <th scope="col" style="min-width: 320px; width: 30%; text-align: right; white-space: nowrap; padding-right: 16px;">Actions</th>
178
+ </tr>
179
+ </thead>
180
+ <tbody>
181
+ ${keys.map(key => {
182
+ const isActive = key.status === 'active';
183
+ const statusBadge = isActive
184
+ ? '<span class="badge badge-success" style="font-size: 10.5px;">Active</span>'
185
+ : (key.status === 'revoked'
186
+ ? '<span class="badge badge-danger" style="font-size: 10.5px;">Revoked</span>'
187
+ : '<span class="badge badge-warning" style="font-size: 10.5px;">Expired</span>');
188
+ const safeName = escapeHtml(key.name || 'Unnamed Key');
189
+ return `
190
+ <tr>
191
+ <td>
192
+ <div style="font-weight: 600; color: var(--text-heading); word-break: break-word;">${safeName}</div>
193
+ ${key.description ? `<div style="font-size: 11px; font-weight: 400; color: var(--text-muted); margin-top: 2px;">${escapeHtml(key.description)}</div>` : ''}
194
+ ${Array.isArray(key.allowedIps) && key.allowedIps.length > 0 ? `<div style="font-size: 10.5px; font-weight: 400; color: var(--text-muted); margin-top: 3px;">IPs: <code>${escapeHtml(key.allowedIps.join(', '))}</code></div>` : ''}
195
+ </td>
196
+ <td>
197
+ <code style="font-size: 11.5px; background: var(--bg-input); padding: 2px 6px; border-radius: 4px; border: 1px solid var(--border-subtle);">${escapeHtml(key.redactedKey || (key.keyPrefix + '...'))}</code>
198
+ <div style="font-size: 10.5px; color: var(--text-muted); margin-top: 4px;">
199
+ Expires: ${key.expiresAt ? formatApiKeyDate(key.expiresAt) : 'Never'}
200
+ </div>
201
+ </td>
202
+ <td>
203
+ ${renderScopeChipsHtml(key)}
204
+ </td>
205
+ <td>
206
+ <div>${statusBadge}</div>
207
+ <div style="font-size: 11px; color: var(--text-muted); margin-top: 4px;">${Number(key.totalRequests || 0)} requests</div>
208
+ <div style="font-size: 10.5px; color: var(--text-muted);">Last used: ${key.lastUsedAt ? formatApiKeyDate(key.lastUsedAt) : 'Never'}</div>
209
+ </td>
210
+ <td style="text-align: right; white-space: nowrap; min-width: 320px; padding-right: 16px;">
211
+ <div style="display: inline-flex; gap: 4px; align-items: center; justify-content: flex-end;">
212
+ <button type="button" class="btn btn-secondary btn-sm" data-action="test" data-key-id="${escapeHtml(key.id)}" aria-label="Test permissions for ${safeName}" title="Test permissions">Test</button>
213
+ <button type="button" class="btn btn-secondary btn-sm" data-action="edit" data-key-id="${escapeHtml(key.id)}" aria-label="Edit scopes for ${safeName}">Edit</button>
214
+ <button type="button" class="btn btn-secondary btn-sm" data-action="rotate" data-key-id="${escapeHtml(key.id)}" aria-label="Rotate secret for ${safeName}" title="Rotate secret key">Rotate</button>
215
+ <button type="button" class="btn btn-secondary btn-sm" data-action="toggle-status" data-key-id="${escapeHtml(key.id)}" data-next-status="${isActive ? 'revoked' : 'active'}" aria-label="${isActive ? 'Revoke' : 'Restore'} ${safeName}">
216
+ ${isActive ? 'Revoke' : 'Restore'}
217
+ </button>
218
+ <button type="button" class="btn btn-danger btn-sm" data-action="delete" data-key-id="${escapeHtml(key.id)}" aria-label="Delete ${safeName}" title="Permanently delete key">✕</button>
219
+ </div>
220
+ </td>
221
+ </tr>
222
+ `;
223
+ }).join('')}
224
+ </tbody>
225
+ </table>
226
+ </div>
227
+ `}
228
+ </div>
229
+ `;
230
+
231
+ const tableWrapper = container.querySelector('.webhook-table-wrapper');
232
+ if (tableWrapper) {
233
+ tableWrapper.addEventListener('click', (e) => {
234
+ const btn = e.target.closest('button[data-action]');
235
+ if (!btn) return;
236
+ const action = btn.getAttribute('data-action');
237
+ const keyId = btn.getAttribute('data-key-id');
238
+ if (!keyId) return;
239
+
240
+ if (action === 'test') {
241
+ openApiKeyTesterModal(keyId);
242
+ } else if (action === 'edit') {
243
+ openApiKeyDrawer(keyId);
244
+ } else if (action === 'rotate') {
245
+ handleRotateApiKey(keyId);
246
+ } else if (action === 'toggle-status') {
247
+ const nextStatus = btn.getAttribute('data-next-status') || 'revoked';
248
+ handleToggleApiKeyStatus(keyId, nextStatus);
249
+ } else if (action === 'delete') {
250
+ handleDeleteApiKey(keyId);
251
+ }
252
+ });
253
+ }
254
+ }
255
+
256
+ function handleApiKeyDrawerKeyDown(e) {
257
+ if (e.key === 'Escape') {
258
+ e.preventDefault();
259
+ if (typeof e.stopPropagation === 'function') e.stopPropagation();
260
+ if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation();
261
+ closeApiKeyDrawer();
262
+ }
263
+ }
264
+
265
+ async function openApiKeyDrawer(keyId = null) {
266
+ apiKeysState.editingKeyId = keyId;
267
+ apiKeysState.lastFocusedElement = typeof document !== 'undefined' ? document.activeElement : null;
268
+
269
+ // Fetch subsystem resources for active app so scope checkboxes stay up-to-date
270
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : (typeof state !== 'undefined' && state?.activeApp?.slug) || 'default';
271
+ const fnEndpoint = slug && slug !== 'default' ? `/api/apps/${encodeURIComponent(slug)}/functions` : '/api/functions';
272
+ const flowEndpoint = slug && slug !== 'default' ? `/api/apps/${encodeURIComponent(slug)}/flows` : '/api/flows';
273
+ const queueEndpoint = slug && slug !== 'default' ? `/api/apps/${encodeURIComponent(slug)}/queues` : '/api/queues';
274
+
275
+ const [fnRes, flowRes, queueRes] = await Promise.allSettled([
276
+ api(fnEndpoint),
277
+ api(flowEndpoint),
278
+ api(queueEndpoint),
279
+ ]);
280
+ apiKeysState.functions = fnRes.status === 'fulfilled' && Array.isArray(fnRes.value) ? fnRes.value : (fnRes.status === 'fulfilled' && fnRes.value?.items ? fnRes.value.items : []);
281
+ apiKeysState.flows = flowRes.status === 'fulfilled' && Array.isArray(flowRes.value) ? flowRes.value : (flowRes.status === 'fulfilled' && flowRes.value?.items ? flowRes.value.items : []);
282
+ const rawQueues = queueRes.status === 'fulfilled' && Array.isArray(queueRes.value) ? queueRes.value : (queueRes.status === 'fulfilled' && queueRes.value?.items ? queueRes.value.items : []);
283
+ apiKeysState.queues = rawQueues.filter(q => q && q.name && !String(q.name).startsWith('_system:') && !q.isSystem);
284
+
285
+ const existing = keyId ? (apiKeysState.keys || []).find(k => k.id === keyId) : null;
286
+ const isEdit = Boolean(existing);
287
+ const existingScopes = new Set(Array.isArray(existing?.scopes) ? existing.scopes.map(s => String(s).trim()) : []);
288
+ const isAdminTier = Boolean(existing && (existing.role === 'admin' || existingScopes.has('*') || existingScopes.has('admin:*')));
289
+
290
+ const collections = (typeof state !== 'undefined' && Array.isArray(state.collections) ? state.collections : [])
291
+ .filter(c => c && c.name && !c.system && !String(c.name).startsWith('_'));
292
+ const httpFlows = (apiKeysState.flows || []).filter(f => !f.triggerType || f.triggerType === 'http');
293
+
294
+ // Identify known matrix scopes so unknown manual scopes stay preserved in Raw Extras
295
+ const knownMatrixScopes = new Set([
296
+ '*', 'admin:*', '*:read', '*:write',
297
+ 'functions:invoke', 'functions:execute', 'functions:*',
298
+ 'flows:execute', 'flows:invoke', 'flows:*',
299
+ 'queues:send', 'queues:read', 'queues:delete', 'queues:*',
300
+ ]);
301
+ for (const col of collections) {
302
+ knownMatrixScopes.add(`${col.name}:read`);
303
+ knownMatrixScopes.add(`${col.name}:write`);
304
+ }
305
+ for (const fn of apiKeysState.functions) {
306
+ knownMatrixScopes.add(`functions:${fn.name}`);
307
+ }
308
+ for (const fl of httpFlows) {
309
+ knownMatrixScopes.add(`flows:${fl.name}`);
310
+ }
311
+ for (const q of apiKeysState.queues) {
312
+ knownMatrixScopes.add(`queues:${q.name}:send`);
313
+ knownMatrixScopes.add(`queues:${q.name}:read`);
314
+ knownMatrixScopes.add(`queues:${q.name}:delete`);
315
+ }
316
+
317
+ const extraScopes = Array.from(existingScopes).filter(s => !knownMatrixScopes.has(s));
318
+
319
+ let root = document.getElementById('drawer-root');
320
+ if (!root) {
321
+ root = document.createElement('div');
322
+ root.id = 'drawer-root';
323
+ document.body.appendChild(root);
324
+ }
325
+
326
+ root.innerHTML = `
327
+ <div id="apikey-drawer-backdrop" class="drawer-backdrop open" onclick="if(event.target===this)closeApiKeyDrawer()"></div>
328
+ <aside
329
+ id="apikey-drawer-panel"
330
+ class="record-drawer webhook-drawer open"
331
+ role="dialog"
332
+ aria-modal="true"
333
+ aria-labelledby="apikey-drawer-title"
334
+ tabindex="-1"
335
+ style="width: 640px; max-width: 96vw;"
336
+ >
337
+ <div class="drawer-header">
338
+ <div class="drawer-title-area" style="display: flex; align-items: center; gap: 8px;">
339
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color: var(--accent-primary);"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
340
+ <h2 id="apikey-drawer-title" class="drawer-title" style="margin: 0;">${isEdit ? 'Edit API Key Scopes' : 'Create Scoped API Key'}</h2>
341
+ </div>
342
+ <button type="button" class="btn btn-secondary btn-sm" onclick="closeApiKeyDrawer()" aria-label="Close drawer">✕</button>
343
+ </div>
344
+
345
+ <form id="api-key-form" onsubmit="handleSaveApiKey(event)" style="display: flex; flex-direction: column; flex: 1; min-height: 0;">
346
+ <div class="drawer-body" style="flex: 1; overflow-y: auto;">
347
+ <!-- General Details -->
348
+ <div class="drawer-card">
349
+ <div class="form-group" style="margin: 0;">
350
+ <label class="form-label" for="apikey-name-input">Key Name <span aria-hidden="true">*</span></label>
351
+ <input
352
+ type="text"
353
+ id="apikey-name-input"
354
+ name="name"
355
+ class="form-input"
356
+ value="${escapeHtml(existing?.name || '')}"
357
+ placeholder="e.g. billing-worker-service"
358
+ required
359
+ autocorrect="off"
360
+ autocapitalize="none"
361
+ spellcheck="false"
362
+ />
363
+ </div>
364
+
365
+ <div class="form-group" style="margin: 0;">
366
+ <label class="form-label" for="apikey-desc-input">Description</label>
367
+ <input
368
+ type="text"
369
+ id="apikey-desc-input"
370
+ name="description"
371
+ class="form-input"
372
+ value="${escapeHtml(existing?.description || '')}"
373
+ placeholder="What microservice or automation uses this key?"
374
+ />
375
+ </div>
376
+
377
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem;">
378
+ ${!isEdit ? `
379
+ <div class="form-group" style="margin: 0;">
380
+ <label class="form-label" for="apikey-expiry-select">Expiration</label>
381
+ <select id="apikey-expiry-select" name="expiresInDays" class="form-select">
382
+ <option value="">Never expires</option>
383
+ <option value="7">7 days</option>
384
+ <option value="30">30 days</option>
385
+ <option value="90">90 days</option>
386
+ <option value="365">365 days</option>
387
+ </select>
388
+ </div>
389
+ ` : `
390
+ <div class="form-group" style="margin: 0;">
391
+ <label class="form-label" for="apikey-prefix-readonly">Key Prefix</label>
392
+ <input type="text" id="apikey-prefix-readonly" class="form-input" value="${escapeHtml(existing?.redactedKey || '')}" readonly style="opacity: 0.75; font-family: monospace;" />
393
+ </div>
394
+ `}
395
+ <div class="form-group" style="margin: 0;">
396
+ <label class="form-label" for="apikey-ips-input">Allowed IPs (Optional)</label>
397
+ <input
398
+ type="text"
399
+ id="apikey-ips-input"
400
+ name="allowedIps"
401
+ class="form-input"
402
+ value="${escapeHtml(Array.isArray(existing?.allowedIps) ? existing.allowedIps.join(', ') : '')}"
403
+ placeholder="e.g. 10.0.0.1, 192.168.1.50"
404
+ aria-describedby="apikey-ips-help"
405
+ autocorrect="off"
406
+ autocapitalize="none"
407
+ spellcheck="false"
408
+ />
409
+ <span id="apikey-ips-help" style="font-size: 10.5px; color: var(--text-muted);">Comma-separated IPv4/IPv6 addresses. Leave blank for any IP.</span>
410
+ </div>
411
+ </div>
412
+ </div>
413
+
414
+ <!-- Access Tier Selector -->
415
+ <fieldset class="drawer-card" style="border: 1px solid var(--border-subtle); margin: 0;">
416
+ <legend style="font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; color: var(--text-muted); padding: 0 6px;">Access Tier</legend>
417
+ <div style="display: flex; flex-direction: column; gap: 0.5rem;">
418
+ <label for="apikey-tier-service" style="display: flex; align-items: flex-start; gap: 8px; cursor: pointer;">
419
+ <input type="radio" id="apikey-tier-service" name="keyTier" value="service" ${!isAdminTier ? 'checked' : ''} onchange="toggleApiKeyTier('service')" style="margin-top: 3px;">
420
+ <div>
421
+ <strong style="font-size: 13px; color: var(--text-heading);">Scoped Service Key (Recommended)</strong>
422
+ <div style="font-size: 11.5px; color: var(--text-muted);">Least-privilege access: select only the exact Collections, Functions, Flows, and Queues needed.</div>
423
+ </div>
424
+ </label>
425
+
426
+ <label for="apikey-tier-admin" style="display: flex; align-items: flex-start; gap: 8px; cursor: pointer;">
427
+ <input type="radio" id="apikey-tier-admin" name="keyTier" value="admin" ${isAdminTier ? 'checked' : ''} onchange="toggleApiKeyTier('admin')" style="margin-top: 3px;">
428
+ <div>
429
+ <strong style="font-size: 13px; color: #ef4444;">Full Admin Key (<code>*</code>)</strong>
430
+ <div style="font-size: 11.5px; color: var(--text-muted);">Grants unrestricted super-admin access and bypasses collection rules.</div>
431
+ </div>
432
+ </label>
433
+ </div>
434
+ </fieldset>
435
+
436
+ <div id="apikey-admin-warning" style="display: ${isAdminTier ? 'block' : 'none'}; padding: 0.85rem 1rem; border-radius: 8px; border: 1px solid rgba(239, 68, 68, 0.35); background: rgba(239, 68, 68, 0.08); font-size: 12px; color: #ef4444;">
437
+ <strong>Caution:</strong> A Full Admin Key grants total administrative authority over schemas, queues, snapshots, and all records in this application.
438
+ </div>
439
+
440
+ <!-- 4-Subsystem Scope Matrix -->
441
+ <div id="apikey-scope-matrix" style="display: ${isAdminTier ? 'none' : 'flex'}; flex-direction: column; gap: 1rem;">
442
+ <!-- 1. Collections -->
443
+ <fieldset class="drawer-card" style="border: 1px solid var(--border-subtle); margin: 0;">
444
+ <legend style="font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; color: var(--text-muted); padding: 0 6px;">Collections Scopes</legend>
445
+ <div style="display: flex; gap: 1rem; flex-wrap: wrap; padding-bottom: 6px; border-bottom: 1px solid var(--border-subtle);">
446
+ <label for="scope-col-all-read" style="display: inline-flex; align-items: center; gap: 5px; font-size: 12px; cursor: pointer;">
447
+ <input type="checkbox" id="scope-col-all-read" class="apikey-scope-cb" data-scope-group="col-read" data-scope-role="all" onchange="syncApiKeyScopeExclusions('col-read')" value="*:read" ${existingScopes.has('*:read') ? 'checked' : ''}>
448
+ <span>All Collections Read (<code>*:read</code>)</span>
449
+ </label>
450
+ <label for="scope-col-all-write" style="display: inline-flex; align-items: center; gap: 5px; font-size: 12px; cursor: pointer;">
451
+ <input type="checkbox" id="scope-col-all-write" class="apikey-scope-cb" data-scope-group="col-write" data-scope-role="all" onchange="syncApiKeyScopeExclusions('col-write')" value="*:write" ${existingScopes.has('*:write') ? 'checked' : ''}>
452
+ <span>All Collections Write (<code>*:write</code>)</span>
453
+ </label>
454
+ </div>
455
+ ${collections.length === 0 ? '<div style="font-size: 11.5px; color: var(--text-muted);">No user collections available.</div>' : `
456
+ <div style="display: flex; flex-direction: column; gap: 6px; max-height: 180px; overflow-y: auto;">
457
+ ${collections.map((c, idx) => `
458
+ <div style="display: flex; align-items: center; justify-content: space-between; font-size: 12px; padding: 3px 0;">
459
+ <code style="color: var(--text-heading); font-weight: 600;">${escapeHtml(c.name)}</code>
460
+ <div style="display: flex; gap: 12px;">
461
+ <label for="scope-col-r-${idx}" style="display: inline-flex; align-items: center; gap: 4px; cursor: pointer;">
462
+ <input type="checkbox" id="scope-col-r-${idx}" class="apikey-scope-cb" data-scope-group="col-read" data-scope-role="specific" onchange="syncApiKeyScopeExclusions('col-read')" value="${escapeHtml(c.name)}:read" ${existingScopes.has(`${c.name}:read`) ? 'checked' : ''}> Read
463
+ </label>
464
+ <label for="scope-col-w-${idx}" style="display: inline-flex; align-items: center; gap: 4px; cursor: pointer;">
465
+ <input type="checkbox" id="scope-col-w-${idx}" class="apikey-scope-cb" data-scope-group="col-write" data-scope-role="specific" onchange="syncApiKeyScopeExclusions('col-write')" value="${escapeHtml(c.name)}:write" ${existingScopes.has(`${c.name}:write`) ? 'checked' : ''}> Write
466
+ </label>
467
+ </div>
468
+ </div>
469
+ `).join('')}
470
+ </div>
471
+ `}
472
+ </fieldset>
473
+
474
+ <!-- 2. Functions -->
475
+ <fieldset class="drawer-card" style="border: 1px solid var(--border-subtle); margin: 0;">
476
+ <legend style="font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; color: var(--text-muted); padding: 0 6px;">Serverless Functions Scopes</legend>
477
+ <div style="padding-bottom: 6px; border-bottom: 1px solid var(--border-subtle);">
478
+ <label for="scope-fn-all" style="display: inline-flex; align-items: center; gap: 5px; font-size: 12px; cursor: pointer;">
479
+ <input type="checkbox" id="scope-fn-all" class="apikey-scope-cb" data-scope-group="fn-invoke" data-scope-role="all" onchange="syncApiKeyScopeExclusions('fn-invoke')" value="functions:invoke" ${existingScopes.has('functions:invoke') || existingScopes.has('functions:execute') || existingScopes.has('functions:*') ? 'checked' : ''}>
480
+ <span>Invoke All Functions (<code>functions:invoke</code>)</span>
481
+ </label>
482
+ </div>
483
+ ${apiKeysState.functions.length === 0 ? '<div style="font-size: 11.5px; color: var(--text-muted);">No serverless functions created yet.</div>' : `
484
+ <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 6px; max-height: 150px; overflow-y: auto;">
485
+ ${apiKeysState.functions.map((fn, idx) => `
486
+ <label for="scope-fn-${idx}" style="display: inline-flex; align-items: center; gap: 5px; font-size: 12px; cursor: pointer;">
487
+ <input type="checkbox" id="scope-fn-${idx}" class="apikey-scope-cb" data-scope-group="fn-invoke" data-scope-role="specific" onchange="syncApiKeyScopeExclusions('fn-invoke')" value="functions:${escapeHtml(fn.name)}" ${existingScopes.has(`functions:${fn.name}`) ? 'checked' : ''}>
488
+ <code style="font-size: 11.5px;">${escapeHtml(fn.name)}</code>
489
+ </label>
490
+ `).join('')}
491
+ </div>
492
+ `}
493
+ </fieldset>
494
+
495
+ <!-- 3. Flows -->
496
+ <fieldset class="drawer-card" style="border: 1px solid var(--border-subtle); margin: 0;">
497
+ <legend style="font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; color: var(--text-muted); padding: 0 6px;">HTTP Flows Scopes</legend>
498
+ <div style="padding-bottom: 6px; border-bottom: 1px solid var(--border-subtle);">
499
+ <label for="scope-flow-all" style="display: inline-flex; align-items: center; gap: 5px; font-size: 12px; cursor: pointer;">
500
+ <input type="checkbox" id="scope-flow-all" class="apikey-scope-cb" data-scope-group="flow-execute" data-scope-role="all" onchange="syncApiKeyScopeExclusions('flow-execute')" value="flows:execute" ${existingScopes.has('flows:execute') || existingScopes.has('flows:invoke') || existingScopes.has('flows:*') ? 'checked' : ''}>
501
+ <span>Execute All HTTP Flows (<code>flows:execute</code>)</span>
502
+ </label>
503
+ </div>
504
+ ${httpFlows.length === 0 ? '<div style="font-size: 11.5px; color: var(--text-muted);">No HTTP-triggered flows created yet.</div>' : `
505
+ <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 6px; max-height: 150px; overflow-y: auto;">
506
+ ${httpFlows.map((fl, idx) => `
507
+ <label for="scope-flow-${idx}" style="display: inline-flex; align-items: center; gap: 5px; font-size: 12px; cursor: pointer;">
508
+ <input type="checkbox" id="scope-flow-${idx}" class="apikey-scope-cb" data-scope-group="flow-execute" data-scope-role="specific" onchange="syncApiKeyScopeExclusions('flow-execute')" value="flows:${escapeHtml(fl.name)}" ${existingScopes.has(`flows:${fl.name}`) ? 'checked' : ''}>
509
+ <code style="font-size: 11.5px;">${escapeHtml(fl.name)}</code>
510
+ </label>
511
+ `).join('')}
512
+ </div>
513
+ `}
514
+ </fieldset>
515
+
516
+ <!-- 4. Queues -->
517
+ <fieldset class="drawer-card" style="border: 1px solid var(--border-subtle); margin: 0;">
518
+ <legend style="font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; color: var(--text-muted); padding: 0 6px;">Message Queues Scopes</legend>
519
+ <div style="display: flex; gap: 1rem; flex-wrap: wrap; padding-bottom: 6px; border-bottom: 1px solid var(--border-subtle);">
520
+ <label for="scope-q-all-send" style="display: inline-flex; align-items: center; gap: 5px; font-size: 12px; cursor: pointer;">
521
+ <input type="checkbox" id="scope-q-all-send" class="apikey-scope-cb" data-scope-group="queue-send" data-scope-role="all" onchange="syncApiKeyScopeExclusions('queue-send')" value="queues:send" ${existingScopes.has('queues:send') || existingScopes.has('queues:*') ? 'checked' : ''}>
522
+ <span>Send All (<code>queues:send</code>)</span>
523
+ </label>
524
+ <label for="scope-q-all-read" style="display: inline-flex; align-items: center; gap: 5px; font-size: 12px; cursor: pointer;">
525
+ <input type="checkbox" id="scope-q-all-read" class="apikey-scope-cb" data-scope-group="queue-read" data-scope-role="all" onchange="syncApiKeyScopeExclusions('queue-read')" value="queues:read" ${existingScopes.has('queues:read') || existingScopes.has('queues:*') ? 'checked' : ''}>
526
+ <span>Read All (<code>queues:read</code>)</span>
527
+ </label>
528
+ <label for="scope-q-all-delete" style="display: inline-flex; align-items: center; gap: 5px; font-size: 12px; cursor: pointer;">
529
+ <input type="checkbox" id="scope-q-all-delete" class="apikey-scope-cb" data-scope-group="queue-delete" data-scope-role="all" onchange="syncApiKeyScopeExclusions('queue-delete')" value="queues:delete" ${existingScopes.has('queues:delete') || existingScopes.has('queues:*') ? 'checked' : ''}>
530
+ <span>Delete All (<code>queues:delete</code>)</span>
531
+ </label>
532
+ </div>
533
+ ${apiKeysState.queues.length === 0 ? '<div style="font-size: 11.5px; color: var(--text-muted);">No user queues configured yet.</div>' : `
534
+ <div style="display: flex; flex-direction: column; gap: 6px; max-height: 180px; overflow-y: auto;">
535
+ ${apiKeysState.queues.map((q, idx) => `
536
+ <div style="display: flex; align-items: center; justify-content: space-between; font-size: 12px; padding: 3px 0;">
537
+ <code style="color: var(--text-heading); font-weight: 600;">${escapeHtml(q.name)}</code>
538
+ <div style="display: flex; gap: 10px;">
539
+ <label for="scope-q-s-${idx}" style="display: inline-flex; align-items: center; gap: 4px; cursor: pointer;">
540
+ <input type="checkbox" id="scope-q-s-${idx}" class="apikey-scope-cb" data-scope-group="queue-send" data-scope-role="specific" onchange="syncApiKeyScopeExclusions('queue-send')" value="queues:${escapeHtml(q.name)}:send" ${existingScopes.has(`queues:${q.name}:send`) ? 'checked' : ''}> Send
541
+ </label>
542
+ <label for="scope-q-r-${idx}" style="display: inline-flex; align-items: center; gap: 4px; cursor: pointer;">
543
+ <input type="checkbox" id="scope-q-r-${idx}" class="apikey-scope-cb" data-scope-group="queue-read" data-scope-role="specific" onchange="syncApiKeyScopeExclusions('queue-read')" value="queues:${escapeHtml(q.name)}:read" ${existingScopes.has(`queues:${q.name}:read`) ? 'checked' : ''}> Read
544
+ </label>
545
+ <label for="scope-q-d-${idx}" style="display: inline-flex; align-items: center; gap: 4px; cursor: pointer;">
546
+ <input type="checkbox" id="scope-q-d-${idx}" class="apikey-scope-cb" data-scope-group="queue-delete" data-scope-role="specific" onchange="syncApiKeyScopeExclusions('queue-delete')" value="queues:${escapeHtml(q.name)}:delete" ${existingScopes.has(`queues:${q.name}:delete`) ? 'checked' : ''}> Delete
547
+ </label>
548
+ </div>
549
+ </div>
550
+ `).join('')}
551
+ </div>
552
+ `}
553
+ </fieldset>
554
+
555
+ <!-- Custom Extra Scopes -->
556
+ <div class="form-group" style="margin: 0;">
557
+ <label class="form-label" for="apikey-extra-scopes">Additional Custom Scopes (Optional)</label>
558
+ <input
559
+ type="text"
560
+ id="apikey-extra-scopes"
561
+ name="extraScopes"
562
+ class="form-input"
563
+ value="${escapeHtml(extraScopes.join(', '))}"
564
+ placeholder="e.g. orders:export, custom:billing"
565
+ aria-describedby="apikey-extra-help"
566
+ autocorrect="off"
567
+ autocapitalize="none"
568
+ spellcheck="false"
569
+ />
570
+ <span id="apikey-extra-help" style="font-size: 10.5px; color: var(--text-muted);">Comma-separated custom scope strings preserved alongside checked permissions.</span>
571
+ </div>
572
+ </div>
573
+ </div>
574
+
575
+ <div class="drawer-footer" style="padding: 1rem 1.5rem; border-top: 1px solid var(--border-subtle); display: flex; justify-content: flex-end; gap: 0.65rem; background: var(--bg-card);">
576
+ <button type="button" class="btn btn-secondary btn-sm" onclick="closeApiKeyDrawer()">Cancel</button>
577
+ <button type="submit" id="btn-save-api-key" class="btn btn-primary btn-sm" style="font-weight: 600;">
578
+ ${isEdit ? 'Save Key Scopes' : 'Generate API Key'}
579
+ </button>
580
+ </div>
581
+ </form>
582
+ </aside>
583
+ `;
584
+
585
+ syncApiKeyScopeExclusions();
586
+ setAppShellInert(true);
587
+ if (typeof window !== 'undefined') {
588
+ window.removeEventListener('keydown', handleApiKeyDrawerKeyDown);
589
+ window.addEventListener('keydown', handleApiKeyDrawerKeyDown);
590
+ }
591
+ const nameInput = document.getElementById('apikey-name-input');
592
+ if (nameInput && typeof nameInput.focus === 'function') {
593
+ nameInput.focus();
594
+ }
595
+ }
596
+
597
+ function closeApiKeyDrawer() {
598
+ if (typeof window !== 'undefined') {
599
+ window.removeEventListener('keydown', handleApiKeyDrawerKeyDown);
600
+ }
601
+ const panel = typeof document !== 'undefined' ? document.getElementById('apikey-drawer-panel') : null;
602
+ if (!panel) return;
603
+ const root = document.getElementById('drawer-root');
604
+ if (root) root.innerHTML = '';
605
+ setAppShellInert(false);
606
+ apiKeysState.editingKeyId = null;
607
+ if (apiKeysState.lastFocusedElement && typeof apiKeysState.lastFocusedElement.focus === 'function') {
608
+ try {
609
+ apiKeysState.lastFocusedElement.focus();
610
+ } catch (_) {}
611
+ }
612
+ apiKeysState.lastFocusedElement = null;
613
+ }
614
+
615
+ const APIKEY_SCOPE_GROUPS = [
616
+ 'col-read',
617
+ 'col-write',
618
+ 'fn-invoke',
619
+ 'flow-execute',
620
+ 'queue-send',
621
+ 'queue-read',
622
+ 'queue-delete',
623
+ ];
624
+
625
+ function setScopeCheckboxDisabled(cb, disabled) {
626
+ if (!cb) return;
627
+ cb.disabled = Boolean(disabled);
628
+ if (disabled) {
629
+ cb.checked = false;
630
+ }
631
+ const lbl = cb.closest('label') || (cb.id ? document.querySelector(`label[for="${cb.id}"]`) : null);
632
+ if (lbl) {
633
+ lbl.style.opacity = disabled ? '0.45' : '1';
634
+ lbl.style.cursor = disabled ? 'not-allowed' : 'pointer';
635
+ }
636
+ }
637
+
638
+ function syncApiKeyScopeExclusions(targetGroup) {
639
+ const groups = targetGroup ? [targetGroup] : APIKEY_SCOPE_GROUPS;
640
+ for (const group of groups) {
641
+ const allCb = document.querySelector(`.apikey-scope-cb[data-scope-group="${group}"][data-scope-role="all"]`);
642
+ const specificCbs = Array.from(
643
+ document.querySelectorAll(`.apikey-scope-cb[data-scope-group="${group}"][data-scope-role="specific"]`)
644
+ );
645
+
646
+ if (allCb && allCb.checked) {
647
+ setScopeCheckboxDisabled(allCb, false);
648
+ specificCbs.forEach(cb => setScopeCheckboxDisabled(cb, true));
649
+ } else if (specificCbs.some(cb => cb.checked)) {
650
+ if (allCb) setScopeCheckboxDisabled(allCb, true);
651
+ specificCbs.forEach(cb => setScopeCheckboxDisabled(cb, false));
652
+ } else {
653
+ if (allCb) setScopeCheckboxDisabled(allCb, false);
654
+ specificCbs.forEach(cb => setScopeCheckboxDisabled(cb, false));
655
+ }
656
+ }
657
+ }
658
+
659
+ function toggleApiKeyTier(tier) {
660
+ const isAdmin = tier === 'admin';
661
+ const warn = document.getElementById('apikey-admin-warning');
662
+ const matrix = document.getElementById('apikey-scope-matrix');
663
+ if (warn) warn.style.display = isAdmin ? 'block' : 'none';
664
+ if (matrix) matrix.style.display = isAdmin ? 'none' : 'flex';
665
+ }
666
+
667
+ async function handleSaveApiKey(e) {
668
+ if (e && typeof e.preventDefault === 'function') e.preventDefault();
669
+
670
+ const name = document.getElementById('apikey-name-input')?.value?.trim() || '';
671
+ if (!name) {
672
+ if (typeof toast === 'function') toast('Key Name is required', 'error');
673
+ return;
674
+ }
675
+
676
+ const description = document.getElementById('apikey-desc-input')?.value?.trim() || '';
677
+ const ipsRaw = document.getElementById('apikey-ips-input')?.value || '';
678
+ const allowedIps = ipsRaw.split(',').map(s => s.trim()).filter(Boolean);
679
+
680
+ const tierEl = document.querySelector('input[name="keyTier"]:checked');
681
+ const isAdminTier = tierEl && tierEl.value === 'admin';
682
+
683
+ let scopes = [];
684
+ if (isAdminTier) {
685
+ scopes = ['*'];
686
+ } else {
687
+ const checked = Array.from(document.querySelectorAll('.apikey-scope-cb:checked:not(:disabled)')).map(cb => cb.value);
688
+ const extraRaw = document.getElementById('apikey-extra-scopes')?.value || '';
689
+ const extra = extraRaw.split(',').map(s => s.trim()).filter(Boolean);
690
+ scopes = Array.from(new Set([...checked, ...extra]));
691
+ }
692
+
693
+ const role = isAdminTier ? 'admin' : 'service';
694
+ const isEdit = Boolean(apiKeysState.editingKeyId);
695
+ const submitBtn = document.getElementById('btn-save-api-key');
696
+ if (submitBtn) submitBtn.disabled = true;
697
+
698
+ try {
699
+ const prefix = getApiKeysApiPrefix();
700
+ if (isEdit) {
701
+ await api(`${prefix}/${encodeURIComponent(apiKeysState.editingKeyId)}`, {
702
+ method: 'PATCH',
703
+ body: JSON.stringify({ name, description, role, scopes, allowedIps }),
704
+ });
705
+ closeApiKeyDrawer();
706
+ if (typeof toast === 'function') toast('API key updated successfully', 'success');
707
+ await loadApiKeys();
708
+ } else {
709
+ const expiryRaw = document.getElementById('apikey-expiry-select')?.value;
710
+ const createPayload = {
711
+ name,
712
+ description,
713
+ role,
714
+ scopes,
715
+ allowedIps,
716
+ };
717
+ if (expiryRaw) {
718
+ createPayload.expiresInDays = parseInt(expiryRaw, 10);
719
+ }
720
+ const created = await api(prefix, {
721
+ method: 'POST',
722
+ body: JSON.stringify(createPayload),
723
+ });
724
+ closeApiKeyDrawer();
725
+ await loadApiKeys();
726
+ showApiKeySecretModal(created);
727
+ }
728
+ } catch (err) {
729
+ if (typeof toast === 'function') toast(err.message || 'Failed to save API key', 'error');
730
+ } finally {
731
+ if (submitBtn) submitBtn.disabled = false;
732
+ }
733
+ }
734
+
735
+ function showApiKeySecretModal(keyResult) {
736
+ let modalRoot = document.getElementById('modal-root');
737
+ if (!modalRoot) {
738
+ modalRoot = document.createElement('div');
739
+ modalRoot.id = 'modal-root';
740
+ document.body.appendChild(modalRoot);
741
+ }
742
+ const secret = keyResult?.secretKey || '';
743
+ const safeSecret = escapeHtml(secret);
744
+
745
+ modalRoot.innerHTML = `
746
+ <div class="modal-backdrop" onclick="if(event.target===this)closeApiKeySecretModal()">
747
+ <div class="modal" role="dialog" aria-modal="true" aria-labelledby="apikey-secret-title" style="max-width: 560px;">
748
+ <div class="modal-header">
749
+ <h2 id="apikey-secret-title" class="modal-title" style="margin: 0; display: flex; align-items: center; gap: 8px;">
750
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color: var(--accent-primary);"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
751
+ API Key Generated
752
+ </h2>
753
+ <button type="button" class="btn btn-secondary btn-sm" onclick="closeApiKeySecretModal()" aria-label="Close modal">✕</button>
754
+ </div>
755
+ <div class="modal-body" style="display: flex; flex-direction: column; gap: 0.9rem;">
756
+ <div style="padding: 0.75rem 1rem; border-radius: 6px; border: 1px solid rgba(245, 158, 11, 0.35); background: rgba(245, 158, 11, 0.1); color: #f59e0b; font-size: 12px;">
757
+ <strong>Save this key now:</strong> For your security, the full plaintext secret key is shown only once and cannot be retrieved later.
758
+ </div>
759
+ <div>
760
+ <label class="form-label" for="generated-apikey-secret">Secret Key</label>
761
+ <div style="display: flex; gap: 6px;">
762
+ <input type="text" id="generated-apikey-secret" class="form-input" value="${safeSecret}" readonly style="font-family: monospace; font-size: 12.5px;" />
763
+ <button type="button" class="btn btn-primary btn-sm" onclick="copyGeneratedApiKeySecret()">Copy</button>
764
+ </div>
765
+ </div>
766
+ <div>
767
+ <div style="font-size: 11.5px; font-weight: 600; color: var(--text-muted); margin-bottom: 4px;">HTTP Usage Header</div>
768
+ <pre style="margin: 0; padding: 0.65rem 0.85rem; border-radius: 6px; background: var(--bg-input); border: 1px solid var(--border-subtle); font-size: 11.5px; overflow-x: auto;">Authorization: ApiKey ${safeSecret}</pre>
769
+ </div>
770
+ </div>
771
+ <div class="modal-footer">
772
+ <button type="button" class="btn btn-primary btn-sm" onclick="closeApiKeySecretModal()">I Have Saved This Key</button>
773
+ </div>
774
+ </div>
775
+ </div>
776
+ `;
777
+ }
778
+
779
+ function copyGeneratedApiKeySecret() {
780
+ const input = document.getElementById('generated-apikey-secret');
781
+ if (!input) return;
782
+ if (typeof navigator !== 'undefined' && navigator.clipboard && navigator.clipboard.writeText) {
783
+ navigator.clipboard.writeText(input.value);
784
+ }
785
+ if (typeof toast === 'function') toast('API secret key copied to clipboard', 'success');
786
+ }
787
+
788
+ function closeApiKeySecretModal() {
789
+ const titleEl = typeof document !== 'undefined' ? document.getElementById('apikey-secret-title') : null;
790
+ if (!titleEl) return;
791
+ const modalRoot = document.getElementById('modal-root');
792
+ if (modalRoot) modalRoot.innerHTML = '';
793
+ }
794
+
795
+ const API_KEY_SUBSYSTEM_META = {
796
+ collections: {
797
+ label: 'Collections',
798
+ icon: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color: var(--accent-primary); flex-shrink: 0;"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>',
799
+ },
800
+ functions: {
801
+ label: 'Functions',
802
+ icon: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color: var(--accent-primary); flex-shrink: 0;"><polyline points="16 18 22 12 16 6"></polyline><polyline points="8 6 2 12 8 18"></polyline></svg>',
803
+ },
804
+ flows: {
805
+ label: 'Flows',
806
+ icon: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color: var(--accent-primary); flex-shrink: 0;"><circle cx="12" cy="5" r="3"></circle><line x1="12" y1="8" x2="12" y2="12"></line><circle cx="6" cy="19" r="3"></circle><circle cx="18" cy="19" r="3"></circle><path d="M12 12h-6v4"></path><path d="M12 12h6v4"></path></svg>',
807
+ },
808
+ queues: {
809
+ label: 'Queues',
810
+ icon: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color: var(--accent-primary); flex-shrink: 0;"><line x1="8" y1="6" x2="21" y2="6"></line><line x1="8" y1="12" x2="21" y2="12"></line><line x1="8" y1="18" x2="21" y2="18"></line><line x1="3" y1="6" x2="3.01" y2="6"></line><line x1="3" y1="12" x2="3.01" y2="12"></line><line x1="3" y1="18" x2="3.01" y2="18"></line></svg>',
811
+ },
812
+ };
813
+
814
+ function toggleTesterSubsystemMenu(e) {
815
+ if (e && typeof e.stopPropagation === 'function') e.stopPropagation();
816
+ const popover = document.getElementById('tester-subsystem-popover');
817
+ if (popover) {
818
+ popover.style.display = popover.style.display === 'none' ? 'flex' : 'none';
819
+ }
820
+ }
821
+
822
+ function selectTesterSubsystem(subsystem, keyId) {
823
+ const select = document.getElementById('tester-subsystem-select');
824
+ if (select) select.value = subsystem;
825
+ const popover = document.getElementById('tester-subsystem-popover');
826
+ if (popover) popover.style.display = 'none';
827
+ handleTesterSubsystemChange(subsystem, keyId);
828
+ }
829
+
830
+ let currentTesterKeyId = null;
831
+
832
+ async function openApiKeyTesterModal(keyId) {
833
+ currentTesterKeyId = keyId;
834
+ const key = (apiKeysState.keys || []).find(k => k.id === keyId);
835
+ if (!key) {
836
+ if (typeof toast === 'function') toast('API key not found', 'error');
837
+ return;
838
+ }
839
+
840
+ // Ensure functions, flows, queues are loaded
841
+ if (!apiKeysState.functions.length || !apiKeysState.flows.length || !apiKeysState.queues.length) {
842
+ try {
843
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : (typeof state !== 'undefined' && state?.activeApp?.slug) || 'default';
844
+ const fnEndpoint = slug && slug !== 'default' ? `/api/apps/${encodeURIComponent(slug)}/functions` : '/api/functions';
845
+ const flowEndpoint = slug && slug !== 'default' ? `/api/apps/${encodeURIComponent(slug)}/flows` : '/api/flows';
846
+ const queueEndpoint = slug && slug !== 'default' ? `/api/apps/${encodeURIComponent(slug)}/queues` : '/api/queues';
847
+
848
+ const [fnRes, flowRes, queueRes] = await Promise.allSettled([
849
+ api(fnEndpoint),
850
+ api(flowEndpoint),
851
+ api(queueEndpoint),
852
+ ]);
853
+ apiKeysState.functions = fnRes.status === 'fulfilled' && Array.isArray(fnRes.value) ? fnRes.value : (fnRes.status === 'fulfilled' && fnRes.value?.items ? fnRes.value.items : []);
854
+ apiKeysState.flows = flowRes.status === 'fulfilled' && Array.isArray(flowRes.value) ? flowRes.value : (flowRes.status === 'fulfilled' && flowRes.value?.items ? flowRes.value.items : []);
855
+ const rawQueues = queueRes.status === 'fulfilled' && Array.isArray(queueRes.value) ? queueRes.value : (queueRes.status === 'fulfilled' && queueRes.value?.items ? queueRes.value.items : []);
856
+ apiKeysState.queues = rawQueues.filter(q => q && q.name && !String(q.name).startsWith('_system:') && !q.isSystem);
857
+ } catch (_) {}
858
+ }
859
+
860
+ let modalRoot = document.getElementById('modal-root');
861
+ if (!modalRoot) {
862
+ modalRoot = document.createElement('div');
863
+ modalRoot.id = 'modal-root';
864
+ document.body.appendChild(modalRoot);
865
+ }
866
+
867
+ const safeName = escapeHtml(key.name || 'Unnamed Key');
868
+ const roleBadge = key.role === 'admin'
869
+ ? '<span class="badge badge-danger" style="font-size: 11px;">Admin Key</span>'
870
+ : (key.role === 'service'
871
+ ? '<span class="badge badge-primary" style="font-size: 11px;">Service Key</span>'
872
+ : '<span class="badge badge-warning" style="font-size: 11px;">Custom Role</span>');
873
+
874
+ const statusBadge = key.status === 'active'
875
+ ? '<span class="badge badge-success" style="font-size: 11px;">Active</span>'
876
+ : (key.status === 'revoked'
877
+ ? '<span class="badge badge-danger" style="font-size: 11px;">Revoked</span>'
878
+ : '<span class="badge badge-warning" style="font-size: 11px;">Expired</span>');
879
+
880
+ const scopesList = Array.isArray(key.scopes) ? key.scopes : [];
881
+ const ipList = Array.isArray(key.allowedIps) && key.allowedIps.length > 0 ? key.allowedIps.join(', ') : 'None (Any IP allowed)';
882
+
883
+ modalRoot.innerHTML = `
884
+ <div class="modal-backdrop" onclick="if(event.target===this)closeApiKeyTesterModal()">
885
+ <div class="modal modal-lg" role="dialog" aria-modal="true" aria-labelledby="apikey-tester-title" style="max-width: 680px; width: 95vw;">
886
+ <div class="modal-header" style="display: flex; align-items: center; justify-content: space-between;">
887
+ <div style="display: flex; align-items: center; gap: 8px;">
888
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color: var(--accent-primary);"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
889
+ <h2 id="apikey-tester-title" class="modal-title" style="margin: 0; font-size: 1.1rem;">API Key Permissions Tester</h2>
890
+ </div>
891
+ <button type="button" class="btn btn-secondary btn-sm" onclick="closeApiKeyTesterModal()" aria-label="Close tester">✕</button>
892
+ </div>
893
+
894
+ <div class="modal-body" style="display: flex; flex-direction: column; gap: 1rem; max-height: 80vh; overflow-y: auto;">
895
+ <!-- Key Meta Info Card -->
896
+ <div style="background: var(--bg-card-hover); border: 1px solid var(--border-subtle); border-radius: 8px; padding: 0.85rem 1rem; display: flex; flex-direction: column; gap: 6px;">
897
+ <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
898
+ <div style="font-weight: 700; color: var(--text-heading); font-size: 13.5px;">${safeName}</div>
899
+ <div style="display: flex; align-items: center; gap: 6px;">
900
+ ${roleBadge}
901
+ ${statusBadge}
902
+ </div>
903
+ </div>
904
+ <div style="font-size: 11.5px; color: var(--text-muted); display: flex; flex-wrap: wrap; gap: 12px;">
905
+ <span>Key ID: <code style="font-size: 11px;">${escapeHtml(key.id)}</code></span>
906
+ <span>Prefix: <code style="font-size: 11px;">${escapeHtml(key.redactedKey || key.keyPrefix + '...')}</code></span>
907
+ <span>Allowed IPs: <code style="font-size: 11px;">${escapeHtml(ipList)}</code></span>
908
+ </div>
909
+ <div style="font-size: 11px; color: var(--text-muted); margin-top: 2px;">
910
+ Configured Scopes (${scopesList.length}): <code style="font-size: 10.5px;">${escapeHtml(scopesList.slice(0, 5).join(', '))}${scopesList.length > 5 ? ` +${scopesList.length - 5} more` : ''}</code>
911
+ </div>
912
+ </div>
913
+
914
+ <!-- Configuration Controls -->
915
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem;">
916
+ <!-- Subsystem -->
917
+ <div class="form-group" style="margin: 0; position: relative;">
918
+ <label class="form-label" style="font-weight: 600; font-size: 12px;">Target Subsystem</label>
919
+ <div class="dropdown-wrapper" style="width: 100%;">
920
+ <button type="button" id="tester-subsystem-trigger" class="form-select" onclick="toggleTesterSubsystemMenu(event)" style="width: 100%; display: flex; align-items: center; justify-content: space-between; text-align: left; cursor: pointer; padding: 0.55rem 0.75rem; background: var(--bg-input);">
921
+ <div id="tester-subsystem-selected" style="display: flex; align-items: center; gap: 8px;">
922
+ ${API_KEY_SUBSYSTEM_META.collections.icon}
923
+ <span style="font-size: 13px; font-weight: 500;">Collections</span>
924
+ </div>
925
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="color: var(--text-muted); flex-shrink: 0;"><polyline points="6 9 12 15 18 9"></polyline></svg>
926
+ </button>
927
+ <div id="tester-subsystem-popover" class="dropdown-menu-popover" style="display: none; position: absolute; left: 0; right: 0; width: 100%; top: calc(100% + 4px); z-index: 1000; background: var(--bg-card); border: 1px solid var(--border-subtle); border-radius: 8px; box-shadow: var(--shadow-dropdown); padding: 4px;">
928
+ ${['collections', 'functions', 'flows', 'queues'].map(s => `
929
+ <button type="button" class="dropdown-menu-item tester-subsystem-item" data-subsystem="${s}" onclick="selectTesterSubsystem('${s}', '${escapeHtml(key.id)}')" style="display: flex; align-items: center; gap: 8px; border-radius: 6px; padding: 7px 10px; font-size: 13px; font-weight: 500; border: none; cursor: pointer; text-align: left; width: 100%; transition: background 0.15s ease;">
930
+ ${API_KEY_SUBSYSTEM_META[s].icon}
931
+ <span>${API_KEY_SUBSYSTEM_META[s].label}</span>
932
+ </button>
933
+ `).join('')}
934
+ </div>
935
+ </div>
936
+ <select id="tester-subsystem-select" style="display: none;" onchange="handleTesterSubsystemChange(this.value, '${escapeHtml(key.id)}')">
937
+ <option value="collections">Collections</option>
938
+ <option value="functions">Functions</option>
939
+ <option value="flows">Flows</option>
940
+ <option value="queues">Queues</option>
941
+ </select>
942
+ </div>
943
+
944
+ <!-- Resource -->
945
+ <div class="form-group" style="margin: 0;">
946
+ <label class="form-label" for="tester-resource-select" style="font-weight: 600; font-size: 12px;">Target Resource</label>
947
+ <div id="tester-resource-container">
948
+ <!-- Dynamically populated -->
949
+ </div>
950
+ </div>
951
+ </div>
952
+
953
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem;">
954
+ <!-- Action -->
955
+ <div class="form-group" style="margin: 0;">
956
+ <label class="form-label" for="tester-action-select" style="font-weight: 600; font-size: 12px;">Action / Operation</label>
957
+ <div id="tester-action-container">
958
+ <!-- Dynamically populated -->
959
+ </div>
960
+ </div>
961
+
962
+ <!-- Client IP Simulation -->
963
+ <div class="form-group" style="margin: 0;">
964
+ <label class="form-label" for="tester-ip-input" style="font-weight: 600; font-size: 12px;">Simulated Client IP <span style="font-weight: 400; color: var(--text-muted);">(optional)</span></label>
965
+ <input type="text" id="tester-ip-input" class="form-input" placeholder="127.0.0.1" value="127.0.0.1" />
966
+ </div>
967
+ </div>
968
+
969
+ <!-- Action Buttons -->
970
+ <div style="display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 4px;">
971
+ <button type="button" id="btn-run-api-key-test" class="btn btn-primary btn-sm" onclick="runApiKeySimulation('${escapeHtml(key.id)}')" style="font-weight: 600; padding: 6px 14px;">
972
+ Test Permission
973
+ </button>
974
+ <button type="button" id="btn-run-api-key-audit" class="btn btn-secondary btn-sm" onclick="runApiKeyFullAudit('${escapeHtml(key.id)}')" style="font-weight: 500;">
975
+ Audit All Resources
976
+ </button>
977
+ </div>
978
+
979
+ <!-- Result Area -->
980
+ <div id="api-key-tester-result" style="margin-top: 4px;">
981
+ <div style="padding: 1.5rem; text-align: center; background: var(--bg-card); border: 1px dashed var(--border-subtle); border-radius: 8px; color: var(--text-muted); font-size: 12px;">
982
+ Select a target resource and action above, then click <strong>Test Permission</strong> to evaluate the authorization engine.
983
+ </div>
984
+ </div>
985
+ </div>
986
+
987
+ <div class="modal-footer" style="display: flex; justify-content: flex-end;">
988
+ <button type="button" class="btn btn-secondary btn-sm" onclick="closeApiKeyTesterModal()">Close</button>
989
+ </div>
990
+ </div>
991
+ </div>
992
+ `;
993
+
994
+ handleTesterSubsystemChange('collections', key.id);
995
+ }
996
+
997
+ function closeApiKeyTesterModal() {
998
+ const modalRoot = document.getElementById('modal-root');
999
+ if (modalRoot) modalRoot.innerHTML = '';
1000
+ currentTesterKeyId = null;
1001
+ }
1002
+
1003
+ function handleTesterSubsystemChange(subsystem, keyId) {
1004
+ const select = document.getElementById('tester-subsystem-select');
1005
+ if (select && select.value !== subsystem) select.value = subsystem;
1006
+
1007
+ const display = document.getElementById('tester-subsystem-selected');
1008
+ const meta = API_KEY_SUBSYSTEM_META[subsystem];
1009
+ if (display && meta) {
1010
+ display.innerHTML = `
1011
+ ${meta.icon}
1012
+ <span style="font-size: 13px; font-weight: 500;">${meta.label}</span>
1013
+ `;
1014
+ }
1015
+
1016
+ if (typeof document !== 'undefined') {
1017
+ document.querySelectorAll('.tester-subsystem-item').forEach(btn => {
1018
+ const isCur = btn.getAttribute('data-subsystem') === subsystem;
1019
+ btn.style.background = isCur ? 'var(--nav-active-bg)' : 'transparent';
1020
+ btn.style.color = isCur ? 'var(--nav-active-text)' : 'var(--text-main)';
1021
+ });
1022
+ }
1023
+
1024
+ const resContainer = document.getElementById('tester-resource-container');
1025
+ const actContainer = document.getElementById('tester-action-container');
1026
+ if (!resContainer || !actContainer) return;
1027
+
1028
+ const collections = (typeof state !== 'undefined' && Array.isArray(state.collections) ? state.collections : [])
1029
+ .filter(c => c && c.name && !c.system && !String(c.name).startsWith('_'));
1030
+ const functions = apiKeysState.functions || [];
1031
+ const flows = apiKeysState.flows || [];
1032
+ const queues = apiKeysState.queues || [];
1033
+
1034
+ if (subsystem === 'collections') {
1035
+ const optionsHtml = collections.length > 0
1036
+ ? collections.map(c => `<option value="${escapeHtml(c.name)}">${escapeHtml(c.name)}</option>`).join('')
1037
+ : '<option value="orders">orders</option>';
1038
+ resContainer.innerHTML = `
1039
+ <select id="tester-resource-select" class="form-select">
1040
+ ${optionsHtml}
1041
+ </select>
1042
+ `;
1043
+ actContainer.innerHTML = `
1044
+ <select id="tester-action-select" class="form-select">
1045
+ <option value="list">list (List records)</option>
1046
+ <option value="view">view (Get record by ID)</option>
1047
+ <option value="create">create (Insert record)</option>
1048
+ <option value="update">update (Modify record)</option>
1049
+ <option value="delete">delete (Remove record)</option>
1050
+ </select>
1051
+ `;
1052
+ } else if (subsystem === 'functions') {
1053
+ const optionsHtml = functions.length > 0
1054
+ ? functions.map(fn => `<option value="${escapeHtml(fn.name)}">${escapeHtml(fn.name)}</option>`).join('')
1055
+ : '<option value="hello-world">hello-world</option>';
1056
+ resContainer.innerHTML = `
1057
+ <select id="tester-resource-select" class="form-select">
1058
+ ${optionsHtml}
1059
+ </select>
1060
+ `;
1061
+ actContainer.innerHTML = `
1062
+ <select id="tester-action-select" class="form-select">
1063
+ <option value="invoke">invoke (Execute function)</option>
1064
+ </select>
1065
+ `;
1066
+ } else if (subsystem === 'flows') {
1067
+ const optionsHtml = flows.length > 0
1068
+ ? flows.map(fl => `<option value="${escapeHtml(fl.name)}">${escapeHtml(fl.name)}</option>`).join('')
1069
+ : '<option value="approval-flow">approval-flow</option>';
1070
+ resContainer.innerHTML = `
1071
+ <select id="tester-resource-select" class="form-select">
1072
+ ${optionsHtml}
1073
+ </select>
1074
+ `;
1075
+ actContainer.innerHTML = `
1076
+ <select id="tester-action-select" class="form-select">
1077
+ <option value="execute">execute (Trigger flow)</option>
1078
+ <option value="poll">poll (Check execution status)</option>
1079
+ </select>
1080
+ `;
1081
+ } else if (subsystem === 'queues') {
1082
+ const optionsHtml = queues.length > 0
1083
+ ? queues.map(q => `<option value="${escapeHtml(q.name)}">${escapeHtml(q.name)}</option>`).join('')
1084
+ : '<option value="email-jobs">email-jobs</option>';
1085
+ resContainer.innerHTML = `
1086
+ <select id="tester-resource-select" class="form-select">
1087
+ ${optionsHtml}
1088
+ </select>
1089
+ `;
1090
+ actContainer.innerHTML = `
1091
+ <select id="tester-action-select" class="form-select">
1092
+ <option value="send">send (Enqueue job / message)</option>
1093
+ <option value="read">read / claim (Consume job)</option>
1094
+ <option value="delete">delete (Purge / cancel message)</option>
1095
+ </select>
1096
+ `;
1097
+ }
1098
+ }
1099
+
1100
+ async function runApiKeySimulation(keyId) {
1101
+ const subEl = document.getElementById('tester-subsystem-select');
1102
+ const resEl = document.getElementById('tester-resource-select');
1103
+ const actEl = document.getElementById('tester-action-select');
1104
+ const ipEl = document.getElementById('tester-ip-input');
1105
+ const resultContainer = document.getElementById('api-key-tester-result');
1106
+ if (!resultContainer) return;
1107
+
1108
+ const subsystem = subEl?.value || 'collections';
1109
+ const resource = resEl?.value || '';
1110
+ const action = actEl?.value || 'list';
1111
+ const clientIp = ipEl?.value?.trim() || undefined;
1112
+
1113
+ resultContainer.innerHTML = `
1114
+ <div style="padding: 1rem; text-align: center; color: var(--text-muted); font-size: 12.5px;">
1115
+ <span class="spinner" style="margin-right: 6px;"></span> Evaluating authorization engine...
1116
+ </div>
1117
+ `;
1118
+
1119
+ try {
1120
+ const prefix = getApiKeysApiPrefix();
1121
+ const res = await api(`${prefix}/${encodeURIComponent(keyId)}/simulate`, {
1122
+ method: 'POST',
1123
+ body: JSON.stringify({
1124
+ subsystem,
1125
+ resource,
1126
+ action,
1127
+ clientIp,
1128
+ }),
1129
+ });
1130
+
1131
+ if (res.allowed) {
1132
+ resultContainer.innerHTML = `
1133
+ <div class="tester-result-card allowed" style="padding: 1rem; border-radius: 8px; background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.35); display: flex; flex-direction: column; gap: 8px;">
1134
+ <div style="display: flex; align-items: center; justify-content: space-between;">
1135
+ <span style="display: inline-flex; align-items: center; gap: 6px; font-weight: 700; color: #10b981; font-size: 13.5px;">
1136
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"></polyline></svg>
1137
+ ACCESS GRANTED (HTTP 200)
1138
+ </span>
1139
+ <span class="badge badge-success" style="font-size: 11px;">${escapeHtml(res.matchedScope || 'Admin / Wildcard')}</span>
1140
+ </div>
1141
+ <div style="font-size: 12.5px; color: var(--text-heading); font-weight: 500;">
1142
+ ${escapeHtml(res.reason)}
1143
+ </div>
1144
+ ${res.ipCheck && res.ipCheck.enforced ? `
1145
+ <div style="font-size: 11px; color: #10b981;">
1146
+ Client IP verified: <code>${escapeHtml(res.ipCheck.clientIp || 'client')}</code>
1147
+ </div>
1148
+ ` : ''}
1149
+ ${res.curlExample ? `
1150
+ <div style="margin-top: 6px; border-top: 1px solid rgba(16, 185, 129, 0.2); padding-top: 8px;">
1151
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
1152
+ <span style="font-size: 10.5px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; color: var(--text-muted);">Equivalent cURL Request</span>
1153
+ <button type="button" class="btn btn-secondary btn-xs" onclick="copyTesterCurl()" style="padding: 2px 8px; font-size: 11px;">Copy cURL</button>
1154
+ </div>
1155
+ <pre id="tester-curl-code" style="margin: 0; padding: 0.6rem 0.8rem; border-radius: 6px; background: var(--bg-input); border: 1px solid var(--border-subtle); font-size: 11px; font-family: monospace; overflow-x: auto; white-space: pre-wrap;">${escapeHtml(res.curlExample)}</pre>
1156
+ </div>
1157
+ ` : ''}
1158
+ </div>
1159
+ `;
1160
+ } else {
1161
+ resultContainer.innerHTML = `
1162
+ <div class="tester-result-card forbidden" style="padding: 1rem; border-radius: 8px; background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.35); display: flex; flex-direction: column; gap: 8px;">
1163
+ <div style="display: flex; align-items: center; justify-content: space-between;">
1164
+ <span style="display: inline-flex; align-items: center; gap: 6px; font-weight: 700; color: #ef4444; font-size: 13.5px;">
1165
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
1166
+ ACCESS DENIED (HTTP 403)
1167
+ </span>
1168
+ <span class="badge badge-danger" style="font-size: 11px;">Blocked</span>
1169
+ </div>
1170
+ <div style="font-size: 12.5px; color: var(--text-heading); font-weight: 500;">
1171
+ ${escapeHtml(res.reason)}
1172
+ </div>
1173
+ ${res.requiredScope ? `
1174
+ <div style="font-size: 11.5px; color: var(--text-muted);">
1175
+ Required Scope: <code style="font-size: 11px; background: var(--bg-input); padding: 2px 6px; border-radius: 4px; border: 1px solid var(--border-subtle);">${escapeHtml(res.requiredScope)}</code>
1176
+ </div>
1177
+ ` : ''}
1178
+ ${res.ipCheck && res.ipCheck.enforced && !res.ipCheck.allowed ? `
1179
+ <div style="font-size: 11.5px; color: #ef4444;">
1180
+ Client IP blocked: <code>${escapeHtml(res.ipCheck.clientIp)}</code> is not in this key's allowed IP range.
1181
+ </div>
1182
+ ` : ''}
1183
+ </div>
1184
+ `;
1185
+ }
1186
+ } catch (err) {
1187
+ resultContainer.innerHTML = `
1188
+ <div style="padding: 1rem; border-radius: 8px; background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.35); color: #ef4444; font-size: 12.5px;">
1189
+ Simulation failed: ${escapeHtml(err.message || String(err))}
1190
+ </div>
1191
+ `;
1192
+ }
1193
+ }
1194
+
1195
+ async function runApiKeyFullAudit(keyId) {
1196
+ const resultContainer = document.getElementById('api-key-tester-result');
1197
+ if (!resultContainer) return;
1198
+
1199
+ const collections = (typeof state !== 'undefined' && Array.isArray(state.collections) ? state.collections : [])
1200
+ .filter(c => c && c.name && !c.system && !String(c.name).startsWith('_'));
1201
+ const functions = apiKeysState.functions || [];
1202
+ const flows = apiKeysState.flows || [];
1203
+ const queues = apiKeysState.queues || [];
1204
+
1205
+ const targets = [];
1206
+ for (const c of collections) {
1207
+ targets.push({ subsystem: 'collections', resource: c.name, action: 'list', label: `${c.name}:read` });
1208
+ targets.push({ subsystem: 'collections', resource: c.name, action: 'create', label: `${c.name}:write` });
1209
+ }
1210
+ for (const fn of functions) {
1211
+ targets.push({ subsystem: 'functions', resource: fn.name, action: 'invoke', label: `functions:${fn.name}` });
1212
+ }
1213
+ for (const fl of flows) {
1214
+ targets.push({ subsystem: 'flows', resource: fl.name, action: 'execute', label: `flows:${fl.name}` });
1215
+ }
1216
+ for (const q of queues) {
1217
+ targets.push({ subsystem: 'queues', resource: q.name, action: 'send', label: `queues:${q.name}:send` });
1218
+ targets.push({ subsystem: 'queues', resource: q.name, action: 'read', label: `queues:${q.name}:read` });
1219
+ }
1220
+
1221
+ if (targets.length === 0) {
1222
+ resultContainer.innerHTML = `
1223
+ <div style="padding: 1rem; text-align: center; color: var(--text-muted); font-size: 12.5px;">
1224
+ No collections, functions, flows, or queues are currently configured in this app to audit.
1225
+ </div>
1226
+ `;
1227
+ return;
1228
+ }
1229
+
1230
+ resultContainer.innerHTML = `
1231
+ <div style="padding: 1rem; text-align: center; color: var(--text-muted); font-size: 12.5px;">
1232
+ <span class="spinner" style="margin-right: 6px;"></span> Auditing ${targets.length} target permissions across the app...
1233
+ </div>
1234
+ `;
1235
+
1236
+ try {
1237
+ const prefix = getApiKeysApiPrefix();
1238
+ const results = await Promise.all(targets.map(async (t) => {
1239
+ try {
1240
+ const res = await api(`${prefix}/${encodeURIComponent(keyId)}/simulate`, {
1241
+ method: 'POST',
1242
+ body: JSON.stringify({
1243
+ subsystem: t.subsystem,
1244
+ resource: t.resource,
1245
+ action: t.action,
1246
+ }),
1247
+ });
1248
+ return { ...t, allowed: res.allowed, reason: res.reason, matchedScope: res.matchedScope };
1249
+ } catch (err) {
1250
+ return { ...t, allowed: false, reason: err.message || 'Error', matchedScope: null };
1251
+ }
1252
+ }));
1253
+
1254
+ const allowedCount = results.filter(r => r.allowed).length;
1255
+ const deniedCount = results.length - allowedCount;
1256
+
1257
+ resultContainer.innerHTML = `
1258
+ <div style="display: flex; flex-direction: column; gap: 8px;">
1259
+ <div style="display: flex; align-items: center; justify-content: space-between; padding: 4px 0;">
1260
+ <span style="font-weight: 700; font-size: 12.5px; color: var(--text-heading);">Permissions Audit Summary</span>
1261
+ <div style="display: flex; gap: 6px;">
1262
+ <span class="badge badge-success" style="font-size: 11px;">${allowedCount} Allowed</span>
1263
+ <span class="badge badge-danger" style="font-size: 11px;">${deniedCount} Blocked</span>
1264
+ </div>
1265
+ </div>
1266
+ <div style="max-height: 220px; overflow-y: auto; border: 1px solid var(--border-subtle); border-radius: 6px; background: var(--bg-card);">
1267
+ <table style="width: 100%; border-collapse: collapse; font-size: 11.5px;">
1268
+ <thead>
1269
+ <tr style="border-bottom: 1px solid var(--border-subtle); background: var(--bg-card-hover); color: var(--text-muted); text-align: left;">
1270
+ <th style="padding: 6px 10px;">Subsystem</th>
1271
+ <th style="padding: 6px 10px;">Resource &amp; Action</th>
1272
+ <th style="padding: 6px 10px;">Permission</th>
1273
+ <th style="padding: 6px 10px; text-align: right;">Status</th>
1274
+ </tr>
1275
+ </thead>
1276
+ <tbody>
1277
+ ${results.map(r => `
1278
+ <tr style="border-bottom: 1px solid var(--border-subtle);">
1279
+ <td style="padding: 5px 10px; text-transform: capitalize; color: var(--text-muted);">${escapeHtml(r.subsystem)}</td>
1280
+ <td style="padding: 5px 10px; font-weight: 600; color: var(--text-heading);">${escapeHtml(r.resource)} <span style="font-weight: 400; color: var(--text-muted);">(${escapeHtml(r.action)})</span></td>
1281
+ <td style="padding: 5px 10px;"><code>${escapeHtml(r.label)}</code></td>
1282
+ <td style="padding: 5px 10px; text-align: right;">
1283
+ ${r.allowed
1284
+ ? `<span class="badge badge-success" style="font-size: 10px; padding: 2px 6px;">Allowed</span>`
1285
+ : `<span class="badge badge-danger" style="font-size: 10px; padding: 2px 6px;">Blocked</span>`}
1286
+ </td>
1287
+ </tr>
1288
+ `).join('')}
1289
+ </tbody>
1290
+ </table>
1291
+ </div>
1292
+ </div>
1293
+ `;
1294
+ } catch (err) {
1295
+ resultContainer.innerHTML = `
1296
+ <div style="padding: 1rem; border-radius: 8px; background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.35); color: #ef4444; font-size: 12.5px;">
1297
+ Audit failed: ${escapeHtml(err.message || String(err))}
1298
+ </div>
1299
+ `;
1300
+ }
1301
+ }
1302
+
1303
+ function copyTesterCurl() {
1304
+ const pre = document.getElementById('tester-curl-code');
1305
+ if (!pre) return;
1306
+ if (typeof navigator !== 'undefined' && navigator.clipboard && navigator.clipboard.writeText) {
1307
+ navigator.clipboard.writeText(pre.textContent);
1308
+ }
1309
+ if (typeof toast === 'function') toast('cURL command copied to clipboard', 'success');
1310
+ }
1311
+
1312
+ async function handleRotateApiKey(id, name) {
1313
+ try {
1314
+ const keyObj = (apiKeysState.keys || []).find(k => k.id === id);
1315
+ const displayName = name || keyObj?.name || id;
1316
+ const prefix = getApiKeysApiPrefix();
1317
+ const rotated = await api(`${prefix}/${encodeURIComponent(id)}/rotate`, {
1318
+ method: 'POST',
1319
+ body: JSON.stringify({}),
1320
+ });
1321
+ if (typeof toast === 'function') toast(`Rotated secret for '${displayName}'`, 'success');
1322
+ await loadApiKeys();
1323
+ showApiKeySecretModal(rotated);
1324
+ } catch (err) {
1325
+ if (typeof toast === 'function') toast('Failed to rotate key: ' + (err.message || err), 'error');
1326
+ }
1327
+ }
1328
+
1329
+ async function handleToggleApiKeyStatus(id, nextStatus) {
1330
+ try {
1331
+ const prefix = getApiKeysApiPrefix();
1332
+ await api(`${prefix}/${encodeURIComponent(id)}`, {
1333
+ method: 'PATCH',
1334
+ body: JSON.stringify({ status: nextStatus }),
1335
+ });
1336
+ if (typeof toast === 'function') toast(`API key ${nextStatus === 'active' ? 'restored' : 'revoked'}`, 'success');
1337
+ await loadApiKeys();
1338
+ } catch (err) {
1339
+ if (typeof toast === 'function') toast('Failed to update status: ' + (err.message || err), 'error');
1340
+ }
1341
+ }
1342
+
1343
+ async function handleDeleteApiKey(id, name) {
1344
+ try {
1345
+ const keyObj = (apiKeysState.keys || []).find(k => k.id === id);
1346
+ const displayName = name || keyObj?.name || id;
1347
+ const prefix = getApiKeysApiPrefix();
1348
+ await api(`${prefix}/${encodeURIComponent(id)}`, { method: 'DELETE' });
1349
+ if (typeof toast === 'function') toast(`Deleted API key '${displayName}'`, 'success');
1350
+ await loadApiKeys();
1351
+ } catch (err) {
1352
+ if (typeof toast === 'function') toast('Failed to delete API key: ' + (err.message || err), 'error');
1353
+ }
1354
+ }
1355
+
1356
+ if (typeof window !== 'undefined') {
1357
+ window.apiKeysState = apiKeysState;
1358
+ window.getApiKeysApiPrefix = getApiKeysApiPrefix;
1359
+ window.loadApiKeys = loadApiKeys;
1360
+ window.renderApiKeysView = renderApiKeysView;
1361
+ window.updateSidebarApiKeysBadge = updateSidebarApiKeysBadge;
1362
+ window.openApiKeyDrawer = openApiKeyDrawer;
1363
+ window.closeApiKeyDrawer = closeApiKeyDrawer;
1364
+ window.toggleApiKeyTier = toggleApiKeyTier;
1365
+ window.syncApiKeyScopeExclusions = syncApiKeyScopeExclusions;
1366
+ window.handleSaveApiKey = handleSaveApiKey;
1367
+ window.showApiKeySecretModal = showApiKeySecretModal;
1368
+ window.copyGeneratedApiKeySecret = copyGeneratedApiKeySecret;
1369
+ window.closeApiKeySecretModal = closeApiKeySecretModal;
1370
+ window.handleRotateApiKey = handleRotateApiKey;
1371
+ window.handleToggleApiKeyStatus = handleToggleApiKeyStatus;
1372
+ window.handleDeleteApiKey = handleDeleteApiKey;
1373
+ window.openApiKeyTesterModal = openApiKeyTesterModal;
1374
+ window.closeApiKeyTesterModal = closeApiKeyTesterModal;
1375
+ window.toggleTesterSubsystemMenu = toggleTesterSubsystemMenu;
1376
+ window.selectTesterSubsystem = selectTesterSubsystem;
1377
+ window.handleTesterSubsystemChange = handleTesterSubsystemChange;
1378
+ window.runApiKeySimulation = runApiKeySimulation;
1379
+ window.runApiKeyFullAudit = runApiKeyFullAudit;
1380
+ window.copyTesterCurl = copyTesterCurl;
1381
+ }