sh3-core 0.8.0 → 0.8.2

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 (78) hide show
  1. package/dist/Shell.svelte +19 -0
  2. package/dist/api.d.ts +5 -1
  3. package/dist/api.js +6 -1
  4. package/dist/app/admin/ApiKeysView.svelte +16 -27
  5. package/dist/app/admin/SystemView.svelte +149 -11
  6. package/dist/documents/backends.d.ts +8 -0
  7. package/dist/documents/backends.js +87 -0
  8. package/dist/documents/backends.test.d.ts +1 -0
  9. package/dist/documents/backends.test.js +33 -0
  10. package/dist/documents/browse.d.ts +12 -0
  11. package/dist/documents/browse.js +19 -0
  12. package/dist/documents/browse.test.d.ts +1 -0
  13. package/dist/documents/browse.test.js +41 -0
  14. package/dist/documents/http-backend.d.ts +4 -0
  15. package/dist/documents/http-backend.js +14 -0
  16. package/dist/documents/sync/index.d.ts +1 -2
  17. package/dist/documents/sync/index.js +0 -2
  18. package/dist/documents/sync/observer.d.ts +3 -0
  19. package/dist/documents/sync/observer.js +45 -0
  20. package/dist/documents/sync/registry.d.ts +3 -0
  21. package/dist/documents/sync/registry.js +8 -1
  22. package/dist/documents/sync/registry.test.js +11 -0
  23. package/dist/documents/types.d.ts +18 -0
  24. package/dist/documents/types.js +6 -1
  25. package/dist/keys/ConsentDialog.svelte +176 -0
  26. package/dist/keys/ConsentDialog.svelte.d.ts +3 -0
  27. package/dist/keys/client.d.ts +13 -0
  28. package/dist/keys/client.js +65 -0
  29. package/dist/keys/client.test.d.ts +1 -0
  30. package/dist/keys/client.test.js +44 -0
  31. package/dist/keys/consent.svelte.d.ts +16 -0
  32. package/dist/keys/consent.svelte.js +29 -0
  33. package/dist/keys/consent.test.d.ts +1 -0
  34. package/dist/keys/consent.test.js +53 -0
  35. package/dist/keys/revocation-bus.svelte.d.ts +35 -0
  36. package/dist/keys/revocation-bus.svelte.js +92 -0
  37. package/dist/keys/revocation-bus.test.d.ts +1 -0
  38. package/dist/keys/revocation-bus.test.js +95 -0
  39. package/dist/keys/types.d.ts +32 -0
  40. package/dist/keys/types.js +13 -0
  41. package/dist/layout/inspection.d.ts +17 -0
  42. package/dist/layout/inspection.js +53 -0
  43. package/dist/server-shard/types.d.ts +21 -2
  44. package/dist/server-sync.d.ts +6 -0
  45. package/dist/server-sync.js +634 -0
  46. package/dist/server-sync.js.map +7 -0
  47. package/dist/sh3core-shard/ShellHome.svelte +140 -63
  48. package/dist/sh3core-shard/sh3coreShard.svelte.js +12 -1
  49. package/dist/shards/activate-browse.test.d.ts +1 -0
  50. package/dist/shards/activate-browse.test.js +36 -0
  51. package/dist/shards/activate-on-key-revoked.test.d.ts +1 -0
  52. package/dist/shards/activate-on-key-revoked.test.js +60 -0
  53. package/dist/shards/activate-sync-registry.test.d.ts +1 -0
  54. package/dist/shards/activate-sync-registry.test.js +42 -0
  55. package/dist/shards/activate-tenantid.test.d.ts +1 -0
  56. package/dist/shards/activate-tenantid.test.js +21 -0
  57. package/dist/shards/activate.svelte.d.ts +12 -0
  58. package/dist/shards/activate.svelte.js +55 -3
  59. package/dist/shards/types.d.ts +42 -0
  60. package/dist/shards/types.js +1 -1
  61. package/dist/shell/views/KeysAndPeers.svelte +110 -0
  62. package/dist/shell/views/KeysAndPeers.svelte.d.ts +3 -0
  63. package/dist/shell-shard/Terminal.svelte +0 -11
  64. package/dist/shell-shard/manifest.js +1 -1
  65. package/dist/shell-shard/shellShard.svelte.js +52 -4
  66. package/dist/shell-shard/toolbar/Toolbar.svelte +11 -32
  67. package/dist/shell-shard/toolbar/Toolbar.svelte.d.ts +0 -2
  68. package/dist/shell-shard/toolbar/slots/ModeSlot.svelte +29 -62
  69. package/dist/shell-shard/verbs/index.js +3 -1
  70. package/dist/shell-shard/verbs/views.d.ts +2 -0
  71. package/dist/shell-shard/verbs/views.js +103 -2
  72. package/dist/testing.d.ts +3 -0
  73. package/dist/testing.js +77 -0
  74. package/dist/testing.js.map +7 -0
  75. package/dist/verbs/types.d.ts +19 -0
  76. package/dist/version.d.ts +1 -1
  77. package/dist/version.js +1 -1
  78. package/package.json +10 -2
@@ -1,6 +1,5 @@
1
1
  export type { SyncScope, SyncHandle, ManifestEntry, ApplyEntry, ApplyOpts, ApplyOutcome, ApplyBatchResult, ConflictPolicy, ConflictResolution, ConflictContext, JournalEntry, ChangePage, GrantRecord, } from './types';
2
2
  export { PERMISSION_DOCUMENTS_SYNC, SYNC_RESERVED_SHARD_ID, ScopeNotGrantedError, ScopeRevokedError, TenantMismatchError, } from './types';
3
- export { createSyncRegistry, type SyncRegistry } from './registry';
4
- export { getSyncBundle } from './singleton';
3
+ export type { SyncRegistry } from './registry';
5
4
  export { default as SyncGrantPicker } from './components/SyncGrantPicker.svelte';
6
5
  export { default as DocumentSyncExplorer } from './components/DocumentSyncExplorer.svelte';
@@ -6,7 +6,5 @@
6
6
  * it is imported directly by SyncGrantPicker.svelte only.
7
7
  */
8
8
  export { PERMISSION_DOCUMENTS_SYNC, SYNC_RESERVED_SHARD_ID, ScopeNotGrantedError, ScopeRevokedError, TenantMismatchError, } from './types';
9
- export { createSyncRegistry } from './registry';
10
- export { getSyncBundle } from './singleton';
11
9
  export { default as SyncGrantPicker } from './components/SyncGrantPicker.svelte';
12
10
  export { default as DocumentSyncExplorer } from './components/DocumentSyncExplorer.svelte';
@@ -0,0 +1,3 @@
1
+ import type { DocumentBackend } from '../types';
2
+ import type { SyncRegistry } from './registry';
3
+ export declare function createSyncRegistryAccessor(backend: DocumentBackend, tenantId: string): () => SyncRegistry;
@@ -0,0 +1,45 @@
1
+ /*
2
+ * Observer factory for ctx.syncRegistry.
3
+ *
4
+ * Returns a lazy accessor that resolves to the same SyncRegistry instance
5
+ * backed by the per-tenant sync bundle. Observer-class shards (e.g. the
6
+ * file-explorer) and connector shards share one view of grants and
7
+ * conflicts.
8
+ *
9
+ * Gated upstream on the 'documents:browse' permission — granting remains
10
+ * exclusive to <SyncGrantPicker />.
11
+ */
12
+ import { getSyncBundle } from './singleton';
13
+ export function createSyncRegistryAccessor(backend, tenantId) {
14
+ let cached = null;
15
+ let initPromise = null;
16
+ function resolve() {
17
+ if (cached)
18
+ return Promise.resolve(cached);
19
+ if (!initPromise) {
20
+ initPromise = getSyncBundle(backend, tenantId).then(({ registry }) => {
21
+ cached = registry;
22
+ return registry;
23
+ });
24
+ }
25
+ return initPromise;
26
+ }
27
+ return () => {
28
+ const proxy = {
29
+ async list(connectorId) {
30
+ return (await resolve()).list(connectorId);
31
+ },
32
+ async revoke(connectorId, scope) {
33
+ return (await resolve()).revoke(connectorId, scope);
34
+ },
35
+ listConflicts: (async (shardId) => {
36
+ const r = await resolve();
37
+ return shardId === undefined ? r.listConflicts() : r.listConflicts(shardId);
38
+ }),
39
+ async listAllConnectorIds() {
40
+ return (await resolve()).listAllConnectorIds();
41
+ },
42
+ };
43
+ return proxy;
44
+ };
45
+ }
@@ -4,7 +4,10 @@ export declare function __grantInternal(backend: DocumentBackend, tenantId: stri
4
4
  export interface SyncRegistry {
5
5
  list(connectorId?: string): Promise<GrantRecord[]>;
6
6
  revoke(connectorId: string, scope: SyncScope): Promise<void>;
7
+ /** Per-shard conflict enumeration. */
7
8
  listConflicts(shardId: string): Promise<ConflictResolution[]>;
9
+ /** Tenant-wide conflict enumeration (fans out over every shard). */
10
+ listConflicts(): Promise<ConflictResolution[]>;
8
11
  listAllConnectorIds(): Promise<string[]>;
9
12
  }
10
13
  export declare function createSyncRegistry(backend: DocumentBackend, tenantId: string): SyncRegistry;
@@ -56,7 +56,14 @@ export function createSyncRegistry(backend, tenantId) {
56
56
  await writeJson(backend, tenantId, grantPath(connectorId), next);
57
57
  },
58
58
  async listConflicts(shardId) {
59
- return conflicts.listConflicts(shardId);
59
+ if (shardId !== undefined)
60
+ return conflicts.listConflicts(shardId);
61
+ const shards = await backend.listAllShards(tenantId);
62
+ const out = [];
63
+ for (const s of shards) {
64
+ out.push(...(await conflicts.listConflicts(s)));
65
+ }
66
+ return out;
60
67
  },
61
68
  async listAllConnectorIds() {
62
69
  const paths = await listJsonPaths(backend, tenantId, GRANTS_PREFIX);
@@ -39,4 +39,15 @@ describe('syncRegistry', () => {
39
39
  await __grantInternal(backend, 'tenant-a', 'conn-A', { kind: 'tenant' });
40
40
  expect((await reg.list('conn-A')).length).toBe(1);
41
41
  });
42
+ it('listConflicts() with no args returns conflicts across all shards', async () => {
43
+ var _a, _b;
44
+ // Seed conflict artifacts directly via the backend (matches
45
+ // ConflictManager's artifact naming).
46
+ await backend.write('tenant-a', 'shard-a', 'doc.md.sync-conflict-connA-111', 'remote-a');
47
+ await backend.write('tenant-a', 'shard-b', 'other.md.sync-conflict-connB-222', 'remote-b');
48
+ const all = await reg.listConflicts();
49
+ expect(all.map((c) => c.shardId).sort()).toEqual(['shard-a', 'shard-b']);
50
+ expect((_a = all.find((c) => c.shardId === 'shard-a')) === null || _a === void 0 ? void 0 : _a.path).toBe('doc.md');
51
+ expect((_b = all.find((c) => c.shardId === 'shard-b')) === null || _b === void 0 ? void 0 : _b.path).toBe('other.md');
52
+ });
42
53
  });
@@ -1,3 +1,9 @@
1
+ /**
2
+ * Manifest permission string: grants tenant-wide document observation
3
+ * (`ctx.browse`) and sync registry visibility (`ctx.syncRegistry`).
4
+ * Read-only; writes still flow through the shard's own `ctx.documents()`.
5
+ */
6
+ export declare const PERMISSION_DOCUMENTS_BROWSE = "documents:browse";
1
7
  /**
2
8
  * Format hint for document content. Determines whether reads return a string
3
9
  * (`text`) or an `ArrayBuffer` (`binary`).
@@ -50,6 +56,18 @@ export interface DocumentBackend {
50
56
  list(tenantId: string, shardId: string): Promise<DocumentMeta[]>;
51
57
  /** Return true if the document at `path` exists. */
52
58
  exists(tenantId: string, shardId: string, path: string): Promise<boolean>;
59
+ /**
60
+ * List every shard id that currently has at least one document stored
61
+ * for this tenant. Tenant-wide observation primitive.
62
+ */
63
+ listAllShards(tenantId: string): Promise<string[]>;
64
+ /**
65
+ * List every document in the tenant across all shards. Each entry
66
+ * carries the owning `shardId`. Tenant-wide observation primitive.
67
+ */
68
+ listAllDocuments(tenantId: string): Promise<Array<DocumentMeta & {
69
+ shardId: string;
70
+ }>>;
53
71
  }
54
72
  /**
55
73
  * Shard-facing document handle returned by `ctx.documents()`. Binds
@@ -9,4 +9,9 @@
9
9
  * The document zone is a parallel subsystem — it does not extend
10
10
  * ZoneName or ZoneSchema. Shards access it via `ctx.documents()`.
11
11
  */
12
- export {};
12
+ /**
13
+ * Manifest permission string: grants tenant-wide document observation
14
+ * (`ctx.browse`) and sync registry visibility (`ctx.syncRegistry`).
15
+ * Read-only; writes still flow through the shard's own `ctx.documents()`.
16
+ */
17
+ export const PERMISSION_DOCUMENTS_BROWSE = 'documents:browse';
@@ -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, connectorId)
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.connectorId}
49
+ <dt>Connector</dt>
50
+ <dd>{current.connectorId}</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 @@
1
+ export {};
@@ -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 @@
1
+ export {};
@@ -0,0 +1,53 @@
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: ['documents:sync'], connectorId: '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(['documents:sync']);
23
+ expect(req.connectorId).toBe('peer-x');
24
+ expect(typeof req.requestId).toBe('string');
25
+ });
26
+ it('resolves true when approved', async () => {
27
+ const off = registerConsentListener((req) => {
28
+ queueMicrotask(() => resolveConsent(req.requestId, true));
29
+ });
30
+ cleanups.push(off);
31
+ const result = await requestConsent('shard-b', { label: 'l', scopes: ['state:manage'] });
32
+ expect(result).toBe(true);
33
+ });
34
+ it('resolves false when denied', async () => {
35
+ const off = registerConsentListener((req) => {
36
+ queueMicrotask(() => resolveConsent(req.requestId, false));
37
+ });
38
+ cleanups.push(off);
39
+ const result = await requestConsent('shard-c', { label: 'l', scopes: ['state:manage'] });
40
+ expect(result).toBe(false);
41
+ });
42
+ it('ignores resolveConsent calls with unknown requestId', () => {
43
+ // Should not throw — just a no-op.
44
+ expect(() => resolveConsent('does-not-exist', true)).not.toThrow();
45
+ });
46
+ it('the deregistration returned by registerConsentListener removes the listener', async () => {
47
+ const off = registerConsentListener(() => {
48
+ throw new Error('Should not be called');
49
+ });
50
+ off(); // deregister immediately
51
+ await expect(requestConsent('shard-d', { label: 'l', scopes: ['state:manage'] })).rejects.toThrow('No consent listener registered');
52
+ });
53
+ });
@@ -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 {};