sh3-core 0.8.1 → 0.9.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 (98) hide show
  1. package/dist/Shell.svelte +19 -0
  2. package/dist/api.d.ts +6 -6
  3. package/dist/api.js +6 -3
  4. package/dist/app/admin/ApiKeysView.svelte +16 -27
  5. package/dist/apps/types.d.ts +3 -5
  6. package/dist/documents/backends.d.ts +2 -0
  7. package/dist/documents/backends.js +6 -0
  8. package/dist/documents/handle.js +13 -5
  9. package/dist/documents/handle.test.js +55 -0
  10. package/dist/documents/http-backend.d.ts +11 -4
  11. package/dist/documents/http-backend.js +37 -11
  12. package/dist/documents/index.d.ts +2 -1
  13. package/dist/documents/index.js +1 -1
  14. package/dist/documents/sync-types.d.ts +45 -0
  15. package/dist/documents/sync-types.js +11 -0
  16. package/dist/documents/types.d.ts +40 -2
  17. package/dist/documents/types.js +3 -2
  18. package/dist/keys/ConsentDialog.svelte +176 -0
  19. package/dist/keys/ConsentDialog.svelte.d.ts +3 -0
  20. package/dist/keys/client.d.ts +13 -0
  21. package/dist/keys/client.js +65 -0
  22. package/dist/keys/client.test.js +44 -0
  23. package/dist/keys/consent.svelte.d.ts +16 -0
  24. package/dist/keys/consent.svelte.js +29 -0
  25. package/dist/keys/consent.test.js +54 -0
  26. package/dist/keys/revocation-bus.svelte.d.ts +35 -0
  27. package/dist/keys/revocation-bus.svelte.js +92 -0
  28. package/dist/keys/revocation-bus.test.js +95 -0
  29. package/dist/keys/types.d.ts +34 -0
  30. package/dist/keys/types.js +13 -0
  31. package/dist/server-shard/types.d.ts +68 -2
  32. package/dist/sh3core-shard/ShellHome.svelte +140 -63
  33. package/dist/sh3core-shard/sh3coreShard.svelte.js +12 -1
  34. package/dist/shards/activate-on-key-revoked.test.js +60 -0
  35. package/dist/shards/activate.svelte.js +21 -24
  36. package/dist/shards/types.d.ts +7 -13
  37. package/dist/shards/types.js +1 -1
  38. package/dist/shell/views/KeysAndPeers.svelte +110 -0
  39. package/dist/shell/views/KeysAndPeers.svelte.d.ts +3 -0
  40. package/dist/shell-shard/Terminal.svelte +0 -11
  41. package/dist/shell-shard/toolbar/Toolbar.svelte +11 -32
  42. package/dist/shell-shard/toolbar/Toolbar.svelte.d.ts +0 -2
  43. package/dist/shell-shard/toolbar/slots/ModeSlot.svelte +29 -62
  44. package/dist/version.d.ts +1 -1
  45. package/dist/version.js +1 -1
  46. package/package.json +1 -1
  47. package/dist/documents/journal-hook.d.ts +0 -6
  48. package/dist/documents/journal-hook.js +0 -16
  49. package/dist/documents/sync/activate-integration.test.js +0 -37
  50. package/dist/documents/sync/components/DocumentSyncExplorer.svelte +0 -99
  51. package/dist/documents/sync/components/DocumentSyncExplorer.svelte.d.ts +0 -15
  52. package/dist/documents/sync/components/SyncGrantPicker.svelte +0 -70
  53. package/dist/documents/sync/components/SyncGrantPicker.svelte.d.ts +0 -12
  54. package/dist/documents/sync/conflicts.d.ts +0 -30
  55. package/dist/documents/sync/conflicts.js +0 -77
  56. package/dist/documents/sync/conflicts.test.js +0 -71
  57. package/dist/documents/sync/engine.d.ts +0 -19
  58. package/dist/documents/sync/engine.js +0 -188
  59. package/dist/documents/sync/engine.test.js +0 -169
  60. package/dist/documents/sync/handle.d.ts +0 -11
  61. package/dist/documents/sync/handle.js +0 -79
  62. package/dist/documents/sync/handle.test.js +0 -56
  63. package/dist/documents/sync/hash.d.ts +0 -1
  64. package/dist/documents/sync/hash.js +0 -13
  65. package/dist/documents/sync/hash.test.js +0 -20
  66. package/dist/documents/sync/index.d.ts +0 -5
  67. package/dist/documents/sync/index.js +0 -10
  68. package/dist/documents/sync/journal.d.ts +0 -30
  69. package/dist/documents/sync/journal.js +0 -179
  70. package/dist/documents/sync/journal.test.d.ts +0 -1
  71. package/dist/documents/sync/journal.test.js +0 -87
  72. package/dist/documents/sync/observer.d.ts +0 -3
  73. package/dist/documents/sync/observer.js +0 -45
  74. package/dist/documents/sync/registry.d.ts +0 -13
  75. package/dist/documents/sync/registry.js +0 -73
  76. package/dist/documents/sync/registry.test.d.ts +0 -1
  77. package/dist/documents/sync/registry.test.js +0 -53
  78. package/dist/documents/sync/serialization.d.ts +0 -5
  79. package/dist/documents/sync/serialization.js +0 -24
  80. package/dist/documents/sync/serialization.test.d.ts +0 -1
  81. package/dist/documents/sync/serialization.test.js +0 -26
  82. package/dist/documents/sync/singleton.d.ts +0 -11
  83. package/dist/documents/sync/singleton.js +0 -26
  84. package/dist/documents/sync/tombstones.d.ts +0 -19
  85. package/dist/documents/sync/tombstones.js +0 -58
  86. package/dist/documents/sync/tombstones.test.d.ts +0 -1
  87. package/dist/documents/sync/tombstones.test.js +0 -37
  88. package/dist/documents/sync/types.d.ts +0 -116
  89. package/dist/documents/sync/types.js +0 -27
  90. package/dist/documents/sync/write-hook.test.d.ts +0 -1
  91. package/dist/documents/sync/write-hook.test.js +0 -36
  92. package/dist/shards/activate-sync-registry.test.d.ts +0 -1
  93. package/dist/shards/activate-sync-registry.test.js +0 -42
  94. /package/dist/documents/{sync/handle.test.d.ts → handle.test.d.ts} +0 -0
  95. /package/dist/{documents/sync/activate-integration.test.d.ts → keys/client.test.d.ts} +0 -0
  96. /package/dist/{documents/sync/conflicts.test.d.ts → keys/consent.test.d.ts} +0 -0
  97. /package/dist/{documents/sync/engine.test.d.ts → keys/revocation-bus.test.d.ts} +0 -0
  98. /package/dist/{documents/sync/hash.test.d.ts → shards/activate-on-key-revoked.test.d.ts} +0 -0
@@ -0,0 +1,176 @@
1
+ <!--
2
+ Shell-owned consent dialog. Listens for consent requests and routes the
3
+ user's Approve/Deny back into the runtime via resolveConsent().
4
+
5
+ Mounted once by the shell at boot; never by shards.
6
+
7
+ Security: all shard-provided strings (shardId, label, scope, peerId)
8
+ are rendered as plain text via Svelte's default interpolation — no @html.
9
+ -->
10
+ <script lang="ts">
11
+ import { registerConsentListener, resolveConsent, type ConsentRequest } from './consent.svelte';
12
+
13
+ let current = $state<ConsentRequest | null>(null);
14
+
15
+ $effect(() => {
16
+ const off = registerConsentListener((req) => { current = req; });
17
+ return off;
18
+ });
19
+
20
+ function approve(): void {
21
+ if (!current) return;
22
+ resolveConsent(current.requestId, true);
23
+ current = null;
24
+ }
25
+
26
+ function deny(): void {
27
+ if (!current) return;
28
+ resolveConsent(current.requestId, false);
29
+ current = null;
30
+ }
31
+ </script>
32
+
33
+ {#if current}
34
+ <div class="sh3-consent-backdrop" role="dialog" aria-modal="true" aria-label="Key creation consent">
35
+ <div class="sh3-consent-card">
36
+ <h2 class="sh3-consent-title">
37
+ <span>{current.shardId}</span> wants to create a key
38
+ </h2>
39
+ <dl class="sh3-consent-fields">
40
+ <dt>Label</dt>
41
+ <dd>{current.label}</dd>
42
+ <dt>Scopes</dt>
43
+ <dd class="sh3-consent-scopes">
44
+ {#each current.scopes as s (s)}
45
+ <code class="sh3-consent-scope">{s}</code>
46
+ {/each}
47
+ </dd>
48
+ {#if current.peerRole || current.peerId}
49
+ <dt>Peer</dt>
50
+ <dd>{current.peerRole ?? '—'}{current.peerId ? ` · ${current.peerId}` : ''}</dd>
51
+ {/if}
52
+ {#if current.expiresIn}
53
+ <dt>Expires in</dt>
54
+ <dd>{Math.round(current.expiresIn / 1000)}s</dd>
55
+ {/if}
56
+ </dl>
57
+ <div class="sh3-consent-actions">
58
+ <!-- Deny has autofocus — safe default per spec -->
59
+ <button type="button" class="sh3-consent-deny" onclick={deny} autofocus>Deny</button>
60
+ <button type="button" class="sh3-consent-approve" onclick={approve}>Approve</button>
61
+ </div>
62
+ </div>
63
+ </div>
64
+ {/if}
65
+
66
+ <style>
67
+ .sh3-consent-backdrop {
68
+ position: fixed;
69
+ inset: 0;
70
+ background: rgba(0, 0, 0, 0.55);
71
+ display: flex;
72
+ align-items: center;
73
+ justify-content: center;
74
+ z-index: 9999;
75
+ }
76
+
77
+ .sh3-consent-card {
78
+ background: var(--shell-bg-elevated, #222);
79
+ color: var(--shell-fg, #eee);
80
+ border: 1px solid var(--shell-border, #444);
81
+ padding: 1.5rem;
82
+ border-radius: 8px;
83
+ min-width: 360px;
84
+ max-width: 520px;
85
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
86
+ }
87
+
88
+ .sh3-consent-title {
89
+ margin: 0 0 1rem;
90
+ font-size: 1rem;
91
+ font-weight: 600;
92
+ color: var(--shell-fg, #eee);
93
+ }
94
+
95
+ .sh3-consent-title span {
96
+ color: var(--shell-accent, #7eb8f7);
97
+ }
98
+
99
+ .sh3-consent-fields {
100
+ margin: 0 0 1rem;
101
+ display: grid;
102
+ grid-template-columns: auto 1fr;
103
+ column-gap: 0.75rem;
104
+ row-gap: 0.25rem;
105
+ align-items: baseline;
106
+ }
107
+
108
+ .sh3-consent-fields dt {
109
+ font-weight: 600;
110
+ color: var(--shell-fg-muted, #aaa);
111
+ font-size: 0.8rem;
112
+ text-transform: uppercase;
113
+ letter-spacing: 0.05em;
114
+ padding-top: 0.35rem;
115
+ }
116
+
117
+ .sh3-consent-fields dd {
118
+ margin: 0;
119
+ padding-top: 0.35rem;
120
+ word-break: break-word;
121
+ }
122
+
123
+ .sh3-consent-scopes {
124
+ display: flex;
125
+ flex-wrap: wrap;
126
+ gap: 0.25rem;
127
+ }
128
+
129
+ .sh3-consent-scope {
130
+ display: inline-block;
131
+ padding: 0.1rem 0.35rem;
132
+ background: rgba(255, 255, 255, 0.08);
133
+ border: 1px solid rgba(255, 255, 255, 0.12);
134
+ border-radius: 3px;
135
+ font-size: 0.82em;
136
+ font-family: var(--shell-font-mono, monospace);
137
+ }
138
+
139
+ .sh3-consent-actions {
140
+ display: flex;
141
+ justify-content: flex-end;
142
+ gap: 0.5rem;
143
+ margin-top: 1.25rem;
144
+ }
145
+
146
+ .sh3-consent-deny,
147
+ .sh3-consent-approve {
148
+ padding: 0.4rem 1rem;
149
+ border-radius: 4px;
150
+ font-size: 0.875rem;
151
+ cursor: pointer;
152
+ border: 1px solid transparent;
153
+ transition: opacity 0.1s;
154
+ }
155
+
156
+ .sh3-consent-deny {
157
+ background: transparent;
158
+ color: var(--shell-fg-muted, #aaa);
159
+ border-color: var(--shell-border, #444);
160
+ }
161
+
162
+ .sh3-consent-deny:hover {
163
+ color: var(--shell-fg, #eee);
164
+ border-color: var(--shell-fg-muted, #aaa);
165
+ }
166
+
167
+ .sh3-consent-approve {
168
+ background: var(--shell-accent, #7eb8f7);
169
+ color: #000;
170
+ border-color: var(--shell-accent, #7eb8f7);
171
+ }
172
+
173
+ .sh3-consent-approve:hover {
174
+ opacity: 0.85;
175
+ }
176
+ </style>
@@ -0,0 +1,3 @@
1
+ declare const ConsentDialog: import("svelte").Component<Record<string, never>, {}, "">;
2
+ type ConsentDialog = ReturnType<typeof ConsentDialog>;
3
+ export default ConsentDialog;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Client-side ctx.keys factory. Calls /api/keys endpoints with the current
3
+ * session cookie (no bearer token — session auth is the only supported
4
+ * principal for this API).
5
+ *
6
+ * The shard's manifest permissions are enforced here (scope subset check)
7
+ * before the consent dialog is even shown.
8
+ */
9
+ import type { ShardContextKeys } from './types';
10
+ export declare function createShardKeysApi(params: {
11
+ shardId: string;
12
+ shardPermissions: string[];
13
+ }): ShardContextKeys;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Client-side ctx.keys factory. Calls /api/keys endpoints with the current
3
+ * session cookie (no bearer token — session auth is the only supported
4
+ * principal for this API).
5
+ *
6
+ * The shard's manifest permissions are enforced here (scope subset check)
7
+ * before the consent dialog is even shown.
8
+ */
9
+ import { ConsentDeniedError, ScopeEscalationError } from './types';
10
+ import { requestConsent } from './consent.svelte';
11
+ import { emit } from './revocation-bus.svelte';
12
+ export function createShardKeysApi(params) {
13
+ const { shardId, shardPermissions } = params;
14
+ const assertScopesSubset = (scopes) => {
15
+ for (const s of scopes) {
16
+ if (!shardPermissions.includes(s) && !shardPermissions.includes('admin:*')) {
17
+ throw new ScopeEscalationError(s);
18
+ }
19
+ }
20
+ };
21
+ return {
22
+ async mint(opts) {
23
+ assertScopesSubset(opts.scopes);
24
+ const approved = await requestConsent(shardId, opts);
25
+ if (!approved)
26
+ throw new ConsentDeniedError();
27
+ const ticketRes = await fetch('/api/keys/consent', {
28
+ method: 'POST',
29
+ credentials: 'include',
30
+ headers: { 'content-type': 'application/json' },
31
+ body: JSON.stringify(Object.assign({ shardId }, opts)),
32
+ });
33
+ if (!ticketRes.ok)
34
+ throw new Error(`Consent ticket failed: ${ticketRes.status}`);
35
+ const { ticket } = await ticketRes.json();
36
+ const mintRes = await fetch('/api/keys', {
37
+ method: 'POST',
38
+ credentials: 'include',
39
+ headers: { 'content-type': 'application/json' },
40
+ body: JSON.stringify({ ticket }),
41
+ });
42
+ if (!mintRes.ok)
43
+ throw new Error(`Mint failed: ${mintRes.status}`);
44
+ return mintRes.json();
45
+ },
46
+ async list() {
47
+ const res = await fetch('/api/keys', { credentials: 'include' });
48
+ if (!res.ok)
49
+ throw new Error(`List failed: ${res.status}`);
50
+ const all = (await res.json());
51
+ return all.filter((k) => k.mintedByShardId === shardId);
52
+ },
53
+ async revoke(id) {
54
+ const res = await fetch(`/api/keys/${encodeURIComponent(id)}`, {
55
+ method: 'DELETE',
56
+ credentials: 'include',
57
+ });
58
+ if (!res.ok && res.status !== 404)
59
+ throw new Error(`Revoke failed: ${res.status}`);
60
+ // Notify local bus immediately so the owning shard's onKeyRevoked fires
61
+ // even if the SSE stream hasn't delivered the server-side echo yet.
62
+ emit(shardId, id);
63
+ },
64
+ };
65
+ }
@@ -0,0 +1,44 @@
1
+ import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
2
+ import { createShardKeysApi } from './client';
3
+ import { ScopeEscalationError, ConsentDeniedError } from './types';
4
+ import { registerConsentListener, resolveConsent } from './consent.svelte';
5
+ describe('createShardKeysApi', () => {
6
+ beforeEach(() => {
7
+ vi.stubGlobal('fetch', vi.fn());
8
+ });
9
+ afterEach(() => {
10
+ vi.restoreAllMocks();
11
+ });
12
+ it('throws ScopeEscalationError when minting outside declared scopes', async () => {
13
+ const api = createShardKeysApi({ shardId: 'x', shardPermissions: ['state:manage'] });
14
+ await expect(api.mint({ label: 'l', scopes: ['documents:sync'] })).rejects.toBeInstanceOf(ScopeEscalationError);
15
+ });
16
+ it('throws ConsentDeniedError when the user denies', async () => {
17
+ const off = registerConsentListener((req) => {
18
+ queueMicrotask(() => resolveConsent(req.requestId, false));
19
+ });
20
+ try {
21
+ const api = createShardKeysApi({ shardId: 'x', shardPermissions: ['documents:sync'] });
22
+ await expect(api.mint({ label: 'l', scopes: ['documents:sync'] })).rejects.toBeInstanceOf(ConsentDeniedError);
23
+ }
24
+ finally {
25
+ off();
26
+ }
27
+ });
28
+ it('mints when consent approves and server responds', async () => {
29
+ const off = registerConsentListener((req) => {
30
+ queueMicrotask(() => resolveConsent(req.requestId, true));
31
+ });
32
+ const fetchMock = vi.mocked(fetch);
33
+ fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ ticket: 'tk_1' }), { status: 200 }));
34
+ fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ id: 'abc', key: 'sh3_xyz' }), { status: 200 }));
35
+ try {
36
+ const api = createShardKeysApi({ shardId: 'sh', shardPermissions: ['documents:sync'] });
37
+ const out = await api.mint({ label: 'l', scopes: ['documents:sync'] });
38
+ expect(out.key).toBe('sh3_xyz');
39
+ }
40
+ finally {
41
+ off();
42
+ }
43
+ });
44
+ });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Shell-owned consent runtime — only place that can approve or deny a mint.
3
+ *
4
+ * The client shard calls requestConsent(); the shell shows ConsentDialog.svelte
5
+ * and calls resolveConsent(...) on user action.
6
+ */
7
+ import type { MintOpts } from './types';
8
+ export interface ConsentRequest extends MintOpts {
9
+ requestId: string;
10
+ shardId: string;
11
+ }
12
+ type Listener = (req: ConsentRequest) => void;
13
+ export declare function registerConsentListener(fn: Listener): () => void;
14
+ export declare function requestConsent(shardId: string, opts: MintOpts): Promise<boolean>;
15
+ export declare function resolveConsent(requestId: string, approved: boolean): void;
16
+ export {};
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Shell-owned consent runtime — only place that can approve or deny a mint.
3
+ *
4
+ * The client shard calls requestConsent(); the shell shows ConsentDialog.svelte
5
+ * and calls resolveConsent(...) on user action.
6
+ */
7
+ const pending = new Map();
8
+ let listener = null;
9
+ export function registerConsentListener(fn) {
10
+ listener = fn;
11
+ return () => { if (listener === fn)
12
+ listener = null; };
13
+ }
14
+ export async function requestConsent(shardId, opts) {
15
+ if (!listener)
16
+ throw new Error('No consent listener registered — the shell must mount ConsentDialog.');
17
+ const requestId = `c_${Math.random().toString(36).slice(2)}${Date.now()}`;
18
+ return new Promise((resolve) => {
19
+ pending.set(requestId, { resolve });
20
+ listener(Object.assign(Object.assign({}, opts), { shardId, requestId }));
21
+ });
22
+ }
23
+ export function resolveConsent(requestId, approved) {
24
+ const entry = pending.get(requestId);
25
+ if (!entry)
26
+ return;
27
+ pending.delete(requestId);
28
+ entry.resolve(approved);
29
+ }
@@ -0,0 +1,54 @@
1
+ import { describe, it, expect, afterEach } from 'vitest';
2
+ import { registerConsentListener, requestConsent, resolveConsent, } from './consent.svelte';
3
+ describe('consent runtime', () => {
4
+ // Always clean up the listener after each test to avoid cross-test leakage.
5
+ const cleanups = [];
6
+ afterEach(() => { cleanups.forEach((fn) => fn()); cleanups.length = 0; });
7
+ it('throws when no listener is registered', async () => {
8
+ await expect(requestConsent('my-shard', { label: 'test', scopes: ['state:manage'] })).rejects.toThrow('No consent listener registered');
9
+ });
10
+ it('delivers the request to the listener with correct shape', async () => {
11
+ const received = [];
12
+ const off = registerConsentListener((req) => {
13
+ received.push(req);
14
+ queueMicrotask(() => resolveConsent(req.requestId, true));
15
+ });
16
+ cleanups.push(off);
17
+ await requestConsent('shard-a', { label: 'My key', scopes: ['sync:peer'], peerRole: 'replica', peerId: 'peer-x' });
18
+ expect(received).toHaveLength(1);
19
+ const req = received[0];
20
+ expect(req.shardId).toBe('shard-a');
21
+ expect(req.label).toBe('My key');
22
+ expect(req.scopes).toEqual(['sync:peer']);
23
+ expect(req.peerRole).toBe('replica');
24
+ expect(req.peerId).toBe('peer-x');
25
+ expect(typeof req.requestId).toBe('string');
26
+ });
27
+ it('resolves true when approved', async () => {
28
+ const off = registerConsentListener((req) => {
29
+ queueMicrotask(() => resolveConsent(req.requestId, true));
30
+ });
31
+ cleanups.push(off);
32
+ const result = await requestConsent('shard-b', { label: 'l', scopes: ['state:manage'] });
33
+ expect(result).toBe(true);
34
+ });
35
+ it('resolves false when denied', async () => {
36
+ const off = registerConsentListener((req) => {
37
+ queueMicrotask(() => resolveConsent(req.requestId, false));
38
+ });
39
+ cleanups.push(off);
40
+ const result = await requestConsent('shard-c', { label: 'l', scopes: ['state:manage'] });
41
+ expect(result).toBe(false);
42
+ });
43
+ it('ignores resolveConsent calls with unknown requestId', () => {
44
+ // Should not throw — just a no-op.
45
+ expect(() => resolveConsent('does-not-exist', true)).not.toThrow();
46
+ });
47
+ it('the deregistration returned by registerConsentListener removes the listener', async () => {
48
+ const off = registerConsentListener(() => {
49
+ throw new Error('Should not be called');
50
+ });
51
+ off(); // deregister immediately
52
+ await expect(requestConsent('shard-d', { label: 'l', scopes: ['state:manage'] })).rejects.toThrow('No consent listener registered');
53
+ });
54
+ });
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Notifies active shards when one of their minted keys is revoked —
3
+ * regardless of whether the revocation was initiated by the shell UI,
4
+ * the shard itself, or another tab.
5
+ *
6
+ * The bus is populated by a server-sent events stream on /api/keys/events
7
+ * (wired by the shell runtime at boot) and/or by local revoke() calls.
8
+ */
9
+ type Handler = (keyId: string) => void;
10
+ /**
11
+ * Subscribe to revocation events for a specific shard, or for all shards
12
+ * by passing `'*'` as the shardId.
13
+ * Returns an unsubscribe function.
14
+ */
15
+ export declare function subscribe(shardId: string | '*', handler: Handler): () => void;
16
+ /**
17
+ * Emit a revocation event for the given shardId.
18
+ * No-op if shardId is null or has no subscribers.
19
+ * Deduplicates events: if the same (shardId, keyId) pair was already emitted
20
+ * within the last 5 s it is silently dropped (covers local-then-SSE and
21
+ * SSE-then-local orderings).
22
+ * Internal use only — called by client.ts and the SSE stream bootstrap.
23
+ */
24
+ export declare function emit(shardId: string | null, keyId: string): void;
25
+ /**
26
+ * Open a server-sent events stream at /api/keys/events and forward
27
+ * revocation events into the local bus.
28
+ *
29
+ * Should be called once at shell boot. Returns a cleanup function that
30
+ * closes the EventSource.
31
+ *
32
+ * No-op in environments without EventSource (e.g. Node test runner).
33
+ */
34
+ export declare function startServerSideStream(): () => void;
35
+ export {};
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Notifies active shards when one of their minted keys is revoked —
3
+ * regardless of whether the revocation was initiated by the shell UI,
4
+ * the shard itself, or another tab.
5
+ *
6
+ * The bus is populated by a server-sent events stream on /api/keys/events
7
+ * (wired by the shell runtime at boot) and/or by local revoke() calls.
8
+ */
9
+ const handlersByShard = new Map();
10
+ /**
11
+ * Recently-emitted (shardId → Set<keyId>) with per-entry TTL timers.
12
+ * Prevents double-firing when a local emit() is followed by the same
13
+ * event arriving via SSE (or vice-versa) within the dedup window.
14
+ */
15
+ const recentByShard = new Map();
16
+ const DEDUP_TTL_MS = 5000;
17
+ function markRecent(shardId, keyId) {
18
+ let set = recentByShard.get(shardId);
19
+ if (!set) {
20
+ set = new Set();
21
+ recentByShard.set(shardId, set);
22
+ }
23
+ set.add(keyId);
24
+ setTimeout(() => {
25
+ set.delete(keyId);
26
+ if (set.size === 0)
27
+ recentByShard.delete(shardId);
28
+ }, DEDUP_TTL_MS);
29
+ }
30
+ function isRecent(shardId, keyId) {
31
+ var _a, _b;
32
+ return (_b = (_a = recentByShard.get(shardId)) === null || _a === void 0 ? void 0 : _a.has(keyId)) !== null && _b !== void 0 ? _b : false;
33
+ }
34
+ /**
35
+ * Subscribe to revocation events for a specific shard, or for all shards
36
+ * by passing `'*'` as the shardId.
37
+ * Returns an unsubscribe function.
38
+ */
39
+ export function subscribe(shardId, handler) {
40
+ var _a;
41
+ const set = (_a = handlersByShard.get(shardId)) !== null && _a !== void 0 ? _a : new Set();
42
+ set.add(handler);
43
+ handlersByShard.set(shardId, set);
44
+ return () => { set.delete(handler); };
45
+ }
46
+ /**
47
+ * Emit a revocation event for the given shardId.
48
+ * No-op if shardId is null or has no subscribers.
49
+ * Deduplicates events: if the same (shardId, keyId) pair was already emitted
50
+ * within the last 5 s it is silently dropped (covers local-then-SSE and
51
+ * SSE-then-local orderings).
52
+ * Internal use only — called by client.ts and the SSE stream bootstrap.
53
+ */
54
+ export function emit(shardId, keyId) {
55
+ if (!shardId)
56
+ return;
57
+ if (isRecent(shardId, keyId))
58
+ return;
59
+ markRecent(shardId, keyId);
60
+ const set = handlersByShard.get(shardId);
61
+ if (set)
62
+ for (const h of set)
63
+ h(keyId);
64
+ const star = handlersByShard.get('*');
65
+ if (star)
66
+ for (const h of star)
67
+ h(keyId);
68
+ }
69
+ /**
70
+ * Open a server-sent events stream at /api/keys/events and forward
71
+ * revocation events into the local bus.
72
+ *
73
+ * Should be called once at shell boot. Returns a cleanup function that
74
+ * closes the EventSource.
75
+ *
76
+ * No-op in environments without EventSource (e.g. Node test runner).
77
+ */
78
+ export function startServerSideStream() {
79
+ if (typeof EventSource === 'undefined')
80
+ return () => { };
81
+ const es = new EventSource('/api/keys/events', { withCredentials: true });
82
+ es.onmessage = (msg) => {
83
+ try {
84
+ const ev = JSON.parse(msg.data);
85
+ emit(ev.shardId, ev.id);
86
+ }
87
+ catch (_a) {
88
+ // Ignore malformed messages.
89
+ }
90
+ };
91
+ return () => es.close();
92
+ }
@@ -0,0 +1,95 @@
1
+ import { describe, it, expect, vi, afterEach } from 'vitest';
2
+ import { subscribe, emit } from './revocation-bus.svelte';
3
+ // Use fake timers so dedup TTL tests don't wait 5 s.
4
+ // Individual tests that need it call vi.useFakeTimers(); others rely on real timers.
5
+ afterEach(() => {
6
+ vi.restoreAllMocks();
7
+ });
8
+ describe('revocation-bus', () => {
9
+ it('fires the handler for the correct shardId', () => {
10
+ const received = [];
11
+ const off = subscribe('my-shard', (id) => received.push(id));
12
+ try {
13
+ emit('my-shard', 'key-1');
14
+ expect(received).toEqual(['key-1']);
15
+ }
16
+ finally {
17
+ off();
18
+ }
19
+ });
20
+ it('does not fire for a different shardId', () => {
21
+ const received = [];
22
+ const off = subscribe('shard-a', (id) => received.push(id));
23
+ try {
24
+ emit('shard-b', 'key-1');
25
+ expect(received).toHaveLength(0);
26
+ }
27
+ finally {
28
+ off();
29
+ }
30
+ });
31
+ it('does not fire after unsubscribe', () => {
32
+ const received = [];
33
+ const off = subscribe('my-shard', (id) => received.push(id));
34
+ off();
35
+ emit('my-shard', 'key-1');
36
+ expect(received).toHaveLength(0);
37
+ });
38
+ it('is a no-op when shardId is null', () => {
39
+ // Should not throw.
40
+ expect(() => emit(null, 'key-1')).not.toThrow();
41
+ });
42
+ it('supports multiple subscribers for the same shard', () => {
43
+ const a = [];
44
+ const b = [];
45
+ const offA = subscribe('shared', (id) => a.push(id));
46
+ const offB = subscribe('shared', (id) => b.push(id));
47
+ try {
48
+ emit('shared', 'k');
49
+ expect(a).toEqual(['k']);
50
+ expect(b).toEqual(['k']);
51
+ }
52
+ finally {
53
+ offA();
54
+ offB();
55
+ }
56
+ });
57
+ it('deduplicates back-to-back emits for the same (shard, key) pair', () => {
58
+ vi.useFakeTimers();
59
+ try {
60
+ const received = [];
61
+ const off = subscribe('dedup-shard', (id) => received.push(id));
62
+ try {
63
+ emit('dedup-shard', 'key-dup');
64
+ emit('dedup-shard', 'key-dup'); // duplicate within TTL window
65
+ expect(received).toHaveLength(1);
66
+ expect(received[0]).toBe('key-dup');
67
+ }
68
+ finally {
69
+ off();
70
+ }
71
+ }
72
+ finally {
73
+ vi.useRealTimers();
74
+ }
75
+ });
76
+ it('re-fires after the dedup TTL has elapsed', () => {
77
+ vi.useFakeTimers();
78
+ try {
79
+ const received = [];
80
+ const off = subscribe('dedup-ttl-shard', (id) => received.push(id));
81
+ try {
82
+ emit('dedup-ttl-shard', 'key-x');
83
+ vi.advanceTimersByTime(6000); // past the 5 s TTL
84
+ emit('dedup-ttl-shard', 'key-x');
85
+ expect(received).toHaveLength(2);
86
+ }
87
+ finally {
88
+ off();
89
+ }
90
+ }
91
+ finally {
92
+ vi.useRealTimers();
93
+ }
94
+ });
95
+ });
@@ -0,0 +1,34 @@
1
+ export declare const PERMISSION_KEYS_MINT = "keys:mint";
2
+ export interface ApiKeyPublic {
3
+ id: string;
4
+ label: string;
5
+ tenantId: string | null;
6
+ ownerUserId: string | null;
7
+ mintedByShardId: string | null;
8
+ scopes: string[];
9
+ peerRole?: 'primary' | 'replica';
10
+ peerId?: string;
11
+ createdAt: string;
12
+ expiresAt?: string;
13
+ }
14
+ export interface MintOpts {
15
+ label: string;
16
+ scopes: string[];
17
+ peerRole?: 'primary' | 'replica';
18
+ peerId?: string;
19
+ expiresIn?: number;
20
+ }
21
+ export interface ShardContextKeys {
22
+ mint(opts: MintOpts): Promise<{
23
+ id: string;
24
+ key: string;
25
+ }>;
26
+ list(): Promise<ApiKeyPublic[]>;
27
+ revoke(id: string): Promise<void>;
28
+ }
29
+ export declare class ScopeEscalationError extends Error {
30
+ constructor(scope: string);
31
+ }
32
+ export declare class ConsentDeniedError extends Error {
33
+ constructor();
34
+ }
@@ -0,0 +1,13 @@
1
+ export const PERMISSION_KEYS_MINT = 'keys:mint';
2
+ export class ScopeEscalationError extends Error {
3
+ constructor(scope) {
4
+ super(`Shard may not mint a key with scope '${scope}' — not declared in manifest.`);
5
+ this.name = 'ScopeEscalationError';
6
+ }
7
+ }
8
+ export class ConsentDeniedError extends Error {
9
+ constructor() {
10
+ super('User denied key creation.');
11
+ this.name = 'ConsentDeniedError';
12
+ }
13
+ }