@immediately-run/sdk 0.36.0 → 0.38.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.
package/dist/index.d.cts CHANGED
@@ -15,7 +15,7 @@ export { getRegion, useRegion } from './region.cjs';
15
15
  export { GrantRecord, Invite, Member, MountQuery, MountRemoveReason, MountRule, RemovedMount, ResolvedUser, Role, SandboxMount, SessionMount, SpaceError, SpaceInfo, acceptInvite, awaitMatchingMount, createSpace, declineInvite, findMount, getAppMountPath, getInvites, getMounts, getSessionMounts, getSpaceMembers, importSettingsFromParent, inviteToSpace, listAllSpaces, listGrants, listMyInvites, listPendingInvites, listSettingsApps, listSpaces, lookupUser, makeContentRef, mount, mountSpace, onInvitesChange, onMountsChange, onSessionMountsChange, openSettings, openSettingsOf, requestMount, requestSpace, resolveContentRef, resolveContentRefs, revokeGrant, revokeInvite, setSpaceRole, unmountSpace, unshareSpace, useInvites, useMounts, useSessionMounts, waitForMount } from './mounts.cjs';
16
16
  export { ContributeMode, ContributeOptions, ContributionEvent, ContributionResult, contribute } from './contribute.cjs';
17
17
  export { ApiMethod, getCatalog, invoke, invokeStream, onCatalogChange, useCatalog } from './catalog.cjs';
18
- export { RegionMessage, onRegionMessage, postToRegion, useRegionMessage } from './ipc.cjs';
18
+ export { RegionMessage, onRegionMessage, postToRegion, revealRegion, useRegionMessage } from './ipc.cjs';
19
19
  export { DraggableItem, DroppedItem, ItemDragError, cancelItemDrag, onItemDrop, startItemDrag, useDroppedItem } from './dnd.cjs';
20
20
  export { HostFetchInit, HostFetchResponse, HostFetchStreamEvent, HostFetchStreamResult, hostFetch, hostFetchStream } from './netFetch.cjs';
21
21
  export { SecretError, SecretGrant, SecretHints, SecretQuery, SecretType, SecretView, getSecrets, onSecretsChange, requestAddSecret, requestSecret, revokeSecret, useSecrets } from './secrets.cjs';
package/dist/index.d.ts CHANGED
@@ -15,7 +15,7 @@ export { getRegion, useRegion } from './region.js';
15
15
  export { GrantRecord, Invite, Member, MountQuery, MountRemoveReason, MountRule, RemovedMount, ResolvedUser, Role, SandboxMount, SessionMount, SpaceError, SpaceInfo, acceptInvite, awaitMatchingMount, createSpace, declineInvite, findMount, getAppMountPath, getInvites, getMounts, getSessionMounts, getSpaceMembers, importSettingsFromParent, inviteToSpace, listAllSpaces, listGrants, listMyInvites, listPendingInvites, listSettingsApps, listSpaces, lookupUser, makeContentRef, mount, mountSpace, onInvitesChange, onMountsChange, onSessionMountsChange, openSettings, openSettingsOf, requestMount, requestSpace, resolveContentRef, resolveContentRefs, revokeGrant, revokeInvite, setSpaceRole, unmountSpace, unshareSpace, useInvites, useMounts, useSessionMounts, waitForMount } from './mounts.js';
16
16
  export { ContributeMode, ContributeOptions, ContributionEvent, ContributionResult, contribute } from './contribute.js';
17
17
  export { ApiMethod, getCatalog, invoke, invokeStream, onCatalogChange, useCatalog } from './catalog.js';
18
- export { RegionMessage, onRegionMessage, postToRegion, useRegionMessage } from './ipc.js';
18
+ export { RegionMessage, onRegionMessage, postToRegion, revealRegion, useRegionMessage } from './ipc.js';
19
19
  export { DraggableItem, DroppedItem, ItemDragError, cancelItemDrag, onItemDrop, startItemDrag, useDroppedItem } from './dnd.js';
20
20
  export { HostFetchInit, HostFetchResponse, HostFetchStreamEvent, HostFetchStreamResult, hostFetch, hostFetchStream } from './netFetch.js';
21
21
  export { SecretError, SecretGrant, SecretHints, SecretQuery, SecretType, SecretView, getSecrets, onSecretsChange, requestAddSecret, requestSecret, revokeSecret, useSecrets } from './secrets.js';
package/dist/ipc.cjs CHANGED
@@ -20,6 +20,7 @@ var ipc_exports = {};
20
20
  __export(ipc_exports, {
21
21
  onRegionMessage: () => onRegionMessage,
22
22
  postToRegion: () => postToRegion,
23
+ revealRegion: () => revealRegion,
23
24
  useRegionMessage: () => useRegionMessage
24
25
  });
25
26
  module.exports = __toCommonJS(ipc_exports);
@@ -33,6 +34,14 @@ const postToRegion = async (region, data) => {
33
34
  throw err;
34
35
  }
35
36
  };
37
+ const revealRegion = async (region) => {
38
+ const res = await (0, import_sandboxUtils.protocolRequest)("ipc", "reveal", [{ to: region }]);
39
+ if (!res || res.ok !== true) {
40
+ const err = new Error(res?.message ?? "ipc reveal failed");
41
+ err.code = res?.code ?? "unknown";
42
+ throw err;
43
+ }
44
+ };
36
45
  const onRegionMessage = (listener) => (0, import_sandboxUtils.addListener)(
37
46
  "region-message",
38
47
  (m) => listener({ from: m.from, data: m.data })
@@ -46,6 +55,7 @@ const useRegionMessage = () => {
46
55
  0 && (module.exports = {
47
56
  onRegionMessage,
48
57
  postToRegion,
58
+ revealRegion,
49
59
  useRegionMessage
50
60
  });
51
61
  //# sourceMappingURL=ipc.cjs.map
package/dist/ipc.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ipc.ts"],"sourcesContent":["// Inter-app messaging (UI_AS_APPS_SPEC §5.6) — L2: chrome panels/regions talk to\n// each other across an edge BOTH sides declared in their bindings (sender `ipc.to`\n// + the `ipc` capability; receiver `ipc.accepts`). The host enforces both halves\n// and attaches an unspoofable `from`; you still treat the payload as untrusted.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, addListener } from './sandboxUtils';\n\n/** A message delivered to this region. `from` is the SENDER's region, attached by\n * the host (unspoofable, T19); `data` is the sender-provided payload. */\nexport interface RegionMessage {\n from: string;\n data: unknown;\n}\n\n/**\n * Send a message to another region. Resolves when delivered; rejects (`forbidden`)\n * if the edge isn't two-sided-consented, the target isn't mounted, or this app\n * lacks the `ipc` capability.\n */\nexport const postToRegion = async (region: string, data: unknown): Promise<void> => {\n const res = (await protocolRequest('ipc', 'post', [{ to: region, msg: data }])) as\n | { ok: true }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'ipc post failed') as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n};\n\n/** Subscribe to inbound region messages. Returns an unsubscribe fn. */\nexport const onRegionMessage = (listener: (msg: RegionMessage) => void): (() => void) =>\n addListener('region-message', (m: { from: string; data: unknown }) =>\n listener({ from: m.from, data: m.data }),\n );\n\n/** React hook: the most recent inbound region message (or `null`). */\nexport const useRegionMessage = (): RegionMessage | null => {\n const [msg, setMsg] = useState<RegionMessage | null>(null);\n useEffect(() => onRegionMessage(setMsg), []);\n return msg;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,mBAAoC;AACpC,0BAA6C;AActC,MAAM,eAAe,OAAO,QAAgB,SAAiC;AAClF,QAAM,MAAO,UAAM,qCAAgB,OAAO,QAAQ,CAAC,EAAE,IAAI,QAAQ,KAAK,KAAK,CAAC,CAAC;AAI7E,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,iBAAiB;AACvD,QAAI,OAAO,KAAK,QAAQ;AACxB,UAAM;AAAA,EACR;AACF;AAGO,MAAM,kBAAkB,CAAC,iBAC9B;AAAA,EAAY;AAAA,EAAkB,CAAC,MAC7B,SAAS,EAAE,MAAM,EAAE,MAAM,MAAM,EAAE,KAAK,CAAC;AACzC;AAGK,MAAM,mBAAmB,MAA4B;AAC1D,QAAM,CAAC,KAAK,MAAM,QAAI,uBAA+B,IAAI;AACzD,8BAAU,MAAM,gBAAgB,MAAM,GAAG,CAAC,CAAC;AAC3C,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/ipc.ts"],"sourcesContent":["// Inter-app messaging (UI_AS_APPS_SPEC §5.6) — L2: chrome panels/regions talk to\n// each other across an edge BOTH sides declared in their bindings (sender `ipc.to`\n// + the `ipc` capability; receiver `ipc.accepts`). The host enforces both halves\n// and attaches an unspoofable `from`; you still treat the payload as untrusted.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, addListener } from './sandboxUtils';\n\n/** A message delivered to this region. `from` is the SENDER's region, attached by\n * the host (unspoofable, T19); `data` is the sender-provided payload. */\nexport interface RegionMessage {\n from: string;\n data: unknown;\n}\n\n/**\n * Send a message to another region. Resolves when delivered; rejects (`forbidden`)\n * if the edge isn't two-sided-consented, the target isn't mounted, or this app\n * lacks the `ipc` capability.\n */\nexport const postToRegion = async (region: string, data: unknown): Promise<void> => {\n const res = (await protocolRequest('ipc', 'post', [{ to: region, msg: data }])) as\n | { ok: true }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'ipc post failed') as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n};\n\n/**\n * Ask the host to bring the user to `region` — the `reveal`-class method of\n * UI_AS_APPS_SPEC §4.1's focus model (R3-243). On mobile that is the column\n * transition (the panel's carousel advances to the main pane); on desktop a focus\n * move. Use it when a tap in your panel produces something to look at in another\n * column, right after the `postToRegion` that sends it there:\n *\n * ```ts\n * onClick={() => { // a REAL user gesture\n * void postToRegion('stage.conversation', { type: 'select-conversation', id });\n * void revealRegion('stage.conversation');\n * }}\n * ```\n *\n * **Call it synchronously inside a user-gesture handler.** The host reads its own\n * transient user activation and refuses without one — an app flipping columns on a\n * timer is the attention-steal primitive §4.1 is written against. It reaches only\n * regions you already have a two-sided IPC edge to, and only within the active\n * activity, so it can neither jump the user into an unrelated surface nor pull\n * focus back to the caller's own column.\n *\n * Resolves once the host has *considered* the request — deliberately NOT reporting\n * whether focus actually moved. Whether the user is moved is the host's call\n * (activation, rate limit, already-there), and an app that could observe the\n * refusal would be tempted to retry, which is the behaviour the gate exists to\n * stop. Rejects only on a genuine authorization failure (`forbidden`): no `ipc`\n * capability, or no declared edge to `region`.\n */\nexport const revealRegion = async (region: string): Promise<void> => {\n const res = (await protocolRequest('ipc', 'reveal', [{ to: region }])) as\n | { ok: true }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'ipc reveal failed') as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n};\n\n/** Subscribe to inbound region messages. Returns an unsubscribe fn. */\nexport const onRegionMessage = (listener: (msg: RegionMessage) => void): (() => void) =>\n addListener('region-message', (m: { from: string; data: unknown }) =>\n listener({ from: m.from, data: m.data }),\n );\n\n/** React hook: the most recent inbound region message (or `null`). */\nexport const useRegionMessage = (): RegionMessage | null => {\n const [msg, setMsg] = useState<RegionMessage | null>(null);\n useEffect(() => onRegionMessage(setMsg), []);\n return msg;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,mBAAoC;AACpC,0BAA6C;AActC,MAAM,eAAe,OAAO,QAAgB,SAAiC;AAClF,QAAM,MAAO,UAAM,qCAAgB,OAAO,QAAQ,CAAC,EAAE,IAAI,QAAQ,KAAK,KAAK,CAAC,CAAC;AAI7E,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,iBAAiB;AACvD,QAAI,OAAO,KAAK,QAAQ;AACxB,UAAM;AAAA,EACR;AACF;AA8BO,MAAM,eAAe,OAAO,WAAkC;AACnE,QAAM,MAAO,UAAM,qCAAgB,OAAO,UAAU,CAAC,EAAE,IAAI,OAAO,CAAC,CAAC;AAIpE,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,mBAAmB;AACzD,QAAI,OAAO,KAAK,QAAQ;AACxB,UAAM;AAAA,EACR;AACF;AAGO,MAAM,kBAAkB,CAAC,iBAC9B;AAAA,EAAY;AAAA,EAAkB,CAAC,MAC7B,SAAS,EAAE,MAAM,EAAE,MAAM,MAAM,EAAE,KAAK,CAAC;AACzC;AAGK,MAAM,mBAAmB,MAA4B;AAC1D,QAAM,CAAC,KAAK,MAAM,QAAI,uBAA+B,IAAI;AACzD,8BAAU,MAAM,gBAAgB,MAAM,GAAG,CAAC,CAAC;AAC3C,SAAO;AACT;","names":[]}
package/dist/ipc.d.cts CHANGED
@@ -10,9 +10,38 @@ interface RegionMessage {
10
10
  * lacks the `ipc` capability.
11
11
  */
12
12
  declare const postToRegion: (region: string, data: unknown) => Promise<void>;
13
+ /**
14
+ * Ask the host to bring the user to `region` — the `reveal`-class method of
15
+ * UI_AS_APPS_SPEC §4.1's focus model (R3-243). On mobile that is the column
16
+ * transition (the panel's carousel advances to the main pane); on desktop a focus
17
+ * move. Use it when a tap in your panel produces something to look at in another
18
+ * column, right after the `postToRegion` that sends it there:
19
+ *
20
+ * ```ts
21
+ * onClick={() => { // a REAL user gesture
22
+ * void postToRegion('stage.conversation', { type: 'select-conversation', id });
23
+ * void revealRegion('stage.conversation');
24
+ * }}
25
+ * ```
26
+ *
27
+ * **Call it synchronously inside a user-gesture handler.** The host reads its own
28
+ * transient user activation and refuses without one — an app flipping columns on a
29
+ * timer is the attention-steal primitive §4.1 is written against. It reaches only
30
+ * regions you already have a two-sided IPC edge to, and only within the active
31
+ * activity, so it can neither jump the user into an unrelated surface nor pull
32
+ * focus back to the caller's own column.
33
+ *
34
+ * Resolves once the host has *considered* the request — deliberately NOT reporting
35
+ * whether focus actually moved. Whether the user is moved is the host's call
36
+ * (activation, rate limit, already-there), and an app that could observe the
37
+ * refusal would be tempted to retry, which is the behaviour the gate exists to
38
+ * stop. Rejects only on a genuine authorization failure (`forbidden`): no `ipc`
39
+ * capability, or no declared edge to `region`.
40
+ */
41
+ declare const revealRegion: (region: string) => Promise<void>;
13
42
  /** Subscribe to inbound region messages. Returns an unsubscribe fn. */
14
43
  declare const onRegionMessage: (listener: (msg: RegionMessage) => void) => (() => void);
15
44
  /** React hook: the most recent inbound region message (or `null`). */
16
45
  declare const useRegionMessage: () => RegionMessage | null;
17
46
 
18
- export { type RegionMessage, onRegionMessage, postToRegion, useRegionMessage };
47
+ export { type RegionMessage, onRegionMessage, postToRegion, revealRegion, useRegionMessage };
package/dist/ipc.d.ts CHANGED
@@ -10,9 +10,38 @@ interface RegionMessage {
10
10
  * lacks the `ipc` capability.
11
11
  */
12
12
  declare const postToRegion: (region: string, data: unknown) => Promise<void>;
13
+ /**
14
+ * Ask the host to bring the user to `region` — the `reveal`-class method of
15
+ * UI_AS_APPS_SPEC §4.1's focus model (R3-243). On mobile that is the column
16
+ * transition (the panel's carousel advances to the main pane); on desktop a focus
17
+ * move. Use it when a tap in your panel produces something to look at in another
18
+ * column, right after the `postToRegion` that sends it there:
19
+ *
20
+ * ```ts
21
+ * onClick={() => { // a REAL user gesture
22
+ * void postToRegion('stage.conversation', { type: 'select-conversation', id });
23
+ * void revealRegion('stage.conversation');
24
+ * }}
25
+ * ```
26
+ *
27
+ * **Call it synchronously inside a user-gesture handler.** The host reads its own
28
+ * transient user activation and refuses without one — an app flipping columns on a
29
+ * timer is the attention-steal primitive §4.1 is written against. It reaches only
30
+ * regions you already have a two-sided IPC edge to, and only within the active
31
+ * activity, so it can neither jump the user into an unrelated surface nor pull
32
+ * focus back to the caller's own column.
33
+ *
34
+ * Resolves once the host has *considered* the request — deliberately NOT reporting
35
+ * whether focus actually moved. Whether the user is moved is the host's call
36
+ * (activation, rate limit, already-there), and an app that could observe the
37
+ * refusal would be tempted to retry, which is the behaviour the gate exists to
38
+ * stop. Rejects only on a genuine authorization failure (`forbidden`): no `ipc`
39
+ * capability, or no declared edge to `region`.
40
+ */
41
+ declare const revealRegion: (region: string) => Promise<void>;
13
42
  /** Subscribe to inbound region messages. Returns an unsubscribe fn. */
14
43
  declare const onRegionMessage: (listener: (msg: RegionMessage) => void) => (() => void);
15
44
  /** React hook: the most recent inbound region message (or `null`). */
16
45
  declare const useRegionMessage: () => RegionMessage | null;
17
46
 
18
- export { type RegionMessage, onRegionMessage, postToRegion, useRegionMessage };
47
+ export { type RegionMessage, onRegionMessage, postToRegion, revealRegion, useRegionMessage };
package/dist/ipc.js CHANGED
@@ -9,6 +9,14 @@ const postToRegion = async (region, data) => {
9
9
  throw err;
10
10
  }
11
11
  };
12
+ const revealRegion = async (region) => {
13
+ const res = await protocolRequest("ipc", "reveal", [{ to: region }]);
14
+ if (!res || res.ok !== true) {
15
+ const err = new Error(res?.message ?? "ipc reveal failed");
16
+ err.code = res?.code ?? "unknown";
17
+ throw err;
18
+ }
19
+ };
12
20
  const onRegionMessage = (listener) => addListener(
13
21
  "region-message",
14
22
  (m) => listener({ from: m.from, data: m.data })
@@ -21,6 +29,7 @@ const useRegionMessage = () => {
21
29
  export {
22
30
  onRegionMessage,
23
31
  postToRegion,
32
+ revealRegion,
24
33
  useRegionMessage
25
34
  };
26
35
  //# sourceMappingURL=ipc.js.map
package/dist/ipc.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ipc.ts"],"sourcesContent":["// Inter-app messaging (UI_AS_APPS_SPEC §5.6) — L2: chrome panels/regions talk to\n// each other across an edge BOTH sides declared in their bindings (sender `ipc.to`\n// + the `ipc` capability; receiver `ipc.accepts`). The host enforces both halves\n// and attaches an unspoofable `from`; you still treat the payload as untrusted.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, addListener } from './sandboxUtils';\n\n/** A message delivered to this region. `from` is the SENDER's region, attached by\n * the host (unspoofable, T19); `data` is the sender-provided payload. */\nexport interface RegionMessage {\n from: string;\n data: unknown;\n}\n\n/**\n * Send a message to another region. Resolves when delivered; rejects (`forbidden`)\n * if the edge isn't two-sided-consented, the target isn't mounted, or this app\n * lacks the `ipc` capability.\n */\nexport const postToRegion = async (region: string, data: unknown): Promise<void> => {\n const res = (await protocolRequest('ipc', 'post', [{ to: region, msg: data }])) as\n | { ok: true }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'ipc post failed') as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n};\n\n/** Subscribe to inbound region messages. Returns an unsubscribe fn. */\nexport const onRegionMessage = (listener: (msg: RegionMessage) => void): (() => void) =>\n addListener('region-message', (m: { from: string; data: unknown }) =>\n listener({ from: m.from, data: m.data }),\n );\n\n/** React hook: the most recent inbound region message (or `null`). */\nexport const useRegionMessage = (): RegionMessage | null => {\n const [msg, setMsg] = useState<RegionMessage | null>(null);\n useEffect(() => onRegionMessage(setMsg), []);\n return msg;\n};\n"],"mappings":";AAIA,SAAS,WAAW,gBAAgB;AACpC,SAAS,iBAAiB,mBAAmB;AActC,MAAM,eAAe,OAAO,QAAgB,SAAiC;AAClF,QAAM,MAAO,MAAM,gBAAgB,OAAO,QAAQ,CAAC,EAAE,IAAI,QAAQ,KAAK,KAAK,CAAC,CAAC;AAI7E,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,iBAAiB;AACvD,QAAI,OAAO,KAAK,QAAQ;AACxB,UAAM;AAAA,EACR;AACF;AAGO,MAAM,kBAAkB,CAAC,aAC9B;AAAA,EAAY;AAAA,EAAkB,CAAC,MAC7B,SAAS,EAAE,MAAM,EAAE,MAAM,MAAM,EAAE,KAAK,CAAC;AACzC;AAGK,MAAM,mBAAmB,MAA4B;AAC1D,QAAM,CAAC,KAAK,MAAM,IAAI,SAA+B,IAAI;AACzD,YAAU,MAAM,gBAAgB,MAAM,GAAG,CAAC,CAAC;AAC3C,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/ipc.ts"],"sourcesContent":["// Inter-app messaging (UI_AS_APPS_SPEC §5.6) — L2: chrome panels/regions talk to\n// each other across an edge BOTH sides declared in their bindings (sender `ipc.to`\n// + the `ipc` capability; receiver `ipc.accepts`). The host enforces both halves\n// and attaches an unspoofable `from`; you still treat the payload as untrusted.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, addListener } from './sandboxUtils';\n\n/** A message delivered to this region. `from` is the SENDER's region, attached by\n * the host (unspoofable, T19); `data` is the sender-provided payload. */\nexport interface RegionMessage {\n from: string;\n data: unknown;\n}\n\n/**\n * Send a message to another region. Resolves when delivered; rejects (`forbidden`)\n * if the edge isn't two-sided-consented, the target isn't mounted, or this app\n * lacks the `ipc` capability.\n */\nexport const postToRegion = async (region: string, data: unknown): Promise<void> => {\n const res = (await protocolRequest('ipc', 'post', [{ to: region, msg: data }])) as\n | { ok: true }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'ipc post failed') as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n};\n\n/**\n * Ask the host to bring the user to `region` — the `reveal`-class method of\n * UI_AS_APPS_SPEC §4.1's focus model (R3-243). On mobile that is the column\n * transition (the panel's carousel advances to the main pane); on desktop a focus\n * move. Use it when a tap in your panel produces something to look at in another\n * column, right after the `postToRegion` that sends it there:\n *\n * ```ts\n * onClick={() => { // a REAL user gesture\n * void postToRegion('stage.conversation', { type: 'select-conversation', id });\n * void revealRegion('stage.conversation');\n * }}\n * ```\n *\n * **Call it synchronously inside a user-gesture handler.** The host reads its own\n * transient user activation and refuses without one — an app flipping columns on a\n * timer is the attention-steal primitive §4.1 is written against. It reaches only\n * regions you already have a two-sided IPC edge to, and only within the active\n * activity, so it can neither jump the user into an unrelated surface nor pull\n * focus back to the caller's own column.\n *\n * Resolves once the host has *considered* the request — deliberately NOT reporting\n * whether focus actually moved. Whether the user is moved is the host's call\n * (activation, rate limit, already-there), and an app that could observe the\n * refusal would be tempted to retry, which is the behaviour the gate exists to\n * stop. Rejects only on a genuine authorization failure (`forbidden`): no `ipc`\n * capability, or no declared edge to `region`.\n */\nexport const revealRegion = async (region: string): Promise<void> => {\n const res = (await protocolRequest('ipc', 'reveal', [{ to: region }])) as\n | { ok: true }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'ipc reveal failed') as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n};\n\n/** Subscribe to inbound region messages. Returns an unsubscribe fn. */\nexport const onRegionMessage = (listener: (msg: RegionMessage) => void): (() => void) =>\n addListener('region-message', (m: { from: string; data: unknown }) =>\n listener({ from: m.from, data: m.data }),\n );\n\n/** React hook: the most recent inbound region message (or `null`). */\nexport const useRegionMessage = (): RegionMessage | null => {\n const [msg, setMsg] = useState<RegionMessage | null>(null);\n useEffect(() => onRegionMessage(setMsg), []);\n return msg;\n};\n"],"mappings":";AAIA,SAAS,WAAW,gBAAgB;AACpC,SAAS,iBAAiB,mBAAmB;AActC,MAAM,eAAe,OAAO,QAAgB,SAAiC;AAClF,QAAM,MAAO,MAAM,gBAAgB,OAAO,QAAQ,CAAC,EAAE,IAAI,QAAQ,KAAK,KAAK,CAAC,CAAC;AAI7E,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,iBAAiB;AACvD,QAAI,OAAO,KAAK,QAAQ;AACxB,UAAM;AAAA,EACR;AACF;AA8BO,MAAM,eAAe,OAAO,WAAkC;AACnE,QAAM,MAAO,MAAM,gBAAgB,OAAO,UAAU,CAAC,EAAE,IAAI,OAAO,CAAC,CAAC;AAIpE,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,mBAAmB;AACzD,QAAI,OAAO,KAAK,QAAQ;AACxB,UAAM;AAAA,EACR;AACF;AAGO,MAAM,kBAAkB,CAAC,aAC9B;AAAA,EAAY;AAAA,EAAkB,CAAC,MAC7B,SAAS,EAAE,MAAM,EAAE,MAAM,MAAM,EAAE,KAAK,CAAC;AACzC;AAGK,MAAM,mBAAmB,MAA4B;AAC1D,QAAM,CAAC,KAAK,MAAM,IAAI,SAA+B,IAAI;AACzD,YAAU,MAAM,gBAAgB,MAAM,GAAG,CAAC,CAAC;AAC3C,SAAO;AACT;","names":[]}
@@ -36,18 +36,25 @@ function literalProps(attributes) {
36
36
  }
37
37
  let keyCounter = 0;
38
38
  const nextKey = () => `sc-${keyCounter++}`;
39
- function renderWiki(token, resolve) {
39
+ function elementFor(tag, components) {
40
+ return components?.[tag] ?? tag;
41
+ }
42
+ function renderWiki(token, opts) {
40
43
  const label = token.label ?? token.target;
41
- const href = resolve?.(token.target);
44
+ const href = opts.resolveWikiLink?.(token.target);
42
45
  const safe = href !== void 0 ? (0, import_sanitizeUrl.sanitizeUrl)(href) : void 0;
43
46
  if (safe === void 0) return label;
44
- return (0, import_react.createElement)("a", { href: safe, "data-wikilink": token.target, key: nextKey() }, label);
47
+ return (0, import_react.createElement)(
48
+ elementFor("a", opts.components),
49
+ { href: safe, "data-wikilink": token.target, key: nextKey() },
50
+ label
51
+ );
45
52
  }
46
53
  function renderText(value, opts) {
47
54
  const parts = (0, import_wikilink.splitWikiLinks)(value);
48
55
  if (!parts) return value;
49
56
  return parts.map(
50
- (p, i) => "text" in p ? (0, import_react.createElement)(import_react.Fragment, { key: `t${i}` }, p.text) : (0, import_react.createElement)(import_react.Fragment, { key: `w${i}` }, renderWiki(p.wiki, opts.resolveWikiLink))
57
+ (p, i) => "text" in p ? (0, import_react.createElement)(import_react.Fragment, { key: `t${i}` }, p.text) : (0, import_react.createElement)(import_react.Fragment, { key: `w${i}` }, renderWiki(p.wiki, opts))
51
58
  );
52
59
  }
53
60
  function renderChildren(node, opts) {
@@ -94,12 +101,21 @@ function renderNode(node, opts, index = 0) {
94
101
  case "link": {
95
102
  const href = (0, import_sanitizeUrl.sanitizeUrl)(node.url);
96
103
  if (href === void 0) return (0, import_react.createElement)(import_react.Fragment, { key }, ...renderChildren(node, opts));
97
- return (0, import_react.createElement)("a", { key, href, title: node.title ?? void 0 }, ...renderChildren(node, opts));
104
+ return (0, import_react.createElement)(
105
+ elementFor("a", opts.components),
106
+ { key, href, title: node.title ?? void 0 },
107
+ ...renderChildren(node, opts)
108
+ );
98
109
  }
99
110
  case "image": {
100
111
  const src = (0, import_sanitizeUrl.sanitizeUrl)(node.url);
101
112
  if (src === void 0) return node.alt ? (0, import_react.createElement)(import_react.Fragment, { key }, node.alt) : null;
102
- return (0, import_react.createElement)("img", { key, src, alt: node.alt ?? "", title: node.title ?? void 0 });
113
+ return (0, import_react.createElement)(elementFor("img", opts.components), {
114
+ key,
115
+ src,
116
+ alt: node.alt ?? "",
117
+ title: node.title ?? void 0
118
+ });
103
119
  }
104
120
  // GFM tables.
105
121
  case "table":
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/safeContent/renderMdast.tsx"],"sourcesContent":["import { createElement, Fragment, type ReactNode } from 'react';\nimport { sanitizeUrl } from './sanitizeUrl';\nimport { splitWikiLinks, type WikiLinkToken } from './wikilink';\nimport type { SafeMdastNode, SafeMdxAttribute } from './parseSafeMdast';\n\n// The mdast→React renderer for the safe content path (TRUST_MODES_SPEC §5.1). PURE\n// and synchronous — it only reads `node.type` off an already-parsed tree, so it\n// carries no ESM dep and is exhaustively unit-testable. Every security property lives\n// here:\n//\n// - **JSX tags resolve ONLY to a component registry, by name.** A `<Component/>`\n// node becomes `registry[name]` with **literal string props only**; an unknown tag\n// renders its children inert (a Fragment, no element) — so author-written `<div\n// onclick=…>`, `<img onerror=…>`, `<script>` never become an intrinsic element with\n// attacker attributes. (Block-level raw HTML arrives as an `html` node, below.)\n// - **Expression attributes are dropped.** `f={fetch(\"/x\")}` / `{...spread}` are\n// `mdxJsxExpressionAttribute` or object-valued `mdxJsxAttribute`s — never passed to\n// a component, never evaluated. (There is also no evaluator to reach — parse used\n// no acorn.)\n// - **Raw HTML is inert text.** `html` nodes render as their literal string via a\n// text node — never `dangerouslySetInnerHTML` (no `rehype-raw`).\n// - **URL-scheme sanitizer** on every `link`/`image` URL (`sanitizeUrl`).\n// - **Wikilinks resolve in-mount only** via an injected resolver; the renderer never\n// fetches.\n\nexport interface SafeContentComponents {\n /** Safe components an app exposes to `<Component/>` syntax (host/app-provided).\n * Looked up by the JSX tag name; anything not here renders inert. */\n [tag: string]: React.ComponentType<Record<string, string>>;\n}\n\nexport interface RenderMdastOptions {\n /** The component registry for `<Component/>` syntax. Absent ⇒ all JSX tags inert. */\n components?: SafeContentComponents;\n /**\n * Resolve a wikilink target to an href, **within the granted mount only** — a pure,\n * synchronous, mount-scoped lookup that MUST NOT fetch or reach out of the mount.\n * Return `undefined` for an unresolvable/out-of-mount target (rendered as inert\n * text). Absent ⇒ every wikilink renders as inert text.\n */\n resolveWikiLink?: (target: string) => string | undefined;\n}\n\n/** Extract the literal string props of a JSX element — `mdxJsxAttribute`s whose value\n * is a plain string. Expression attributes (object value) and spreads are DROPPED. */\nfunction literalProps(attributes: SafeMdxAttribute[] | undefined): Record<string, string> {\n const props: Record<string, string> = {};\n for (const attr of attributes ?? []) {\n if (attr.type !== 'mdxJsxAttribute') continue; // drop `{...spread}`\n if (typeof attr.name !== 'string') continue;\n // A literal attribute's value is a string (or null → boolean-ish `true`). An\n // expression value is an object (`mdxJsxAttributeValueExpression`) — DROP it: it\n // is an inert raw string, never a real value, and must never reach a component.\n if (typeof attr.value === 'string') props[attr.name] = attr.value;\n else if (attr.value === null || attr.value === undefined) props[attr.name] = '';\n // object-valued (expression) → skipped\n }\n return props;\n}\n\nlet keyCounter = 0;\nconst nextKey = () => `sc-${keyCounter++}`;\n\n/** Render a wikilink token via the in-mount resolver, or inert text when it can't\n * resolve (never a network call — resolution is the injected mount-scoped callback). */\nfunction renderWiki(token: WikiLinkToken, resolve: RenderMdastOptions['resolveWikiLink']): ReactNode {\n const label = token.label ?? token.target;\n const href = resolve?.(token.target);\n const safe = href !== undefined ? sanitizeUrl(href) : undefined;\n if (safe === undefined) return label; // inert text — unresolved or out-of-mount\n return createElement('a', { href: safe, 'data-wikilink': token.target, key: nextKey() }, label);\n}\n\n/** Render a `text` node, splitting any `[[…]]` wikilinks out of it. */\nfunction renderText(value: string, opts: RenderMdastOptions): ReactNode {\n const parts = splitWikiLinks(value);\n if (!parts) return value;\n return parts.map((p, i) =>\n 'text' in p\n ? createElement(Fragment, { key: `t${i}` }, p.text)\n : createElement(Fragment, { key: `w${i}` }, renderWiki(p.wiki, opts.resolveWikiLink)),\n );\n}\n\nfunction renderChildren(node: SafeMdastNode, opts: RenderMdastOptions): ReactNode[] {\n return (node.children ?? []).map((c, i) => renderNode(c, opts, i));\n}\n\n// Standard mdast block/inline nodes → a FIXED, safe React element. We control every\n// attribute; author input only reaches text content and (sanitized) URLs.\nconst HEADING_TAGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as const;\n\nfunction renderNode(node: SafeMdastNode, opts: RenderMdastOptions, index = 0): ReactNode {\n const key = `n${index}`;\n switch (node.type) {\n case 'root':\n return createElement(Fragment, { key }, ...renderChildren(node, opts));\n case 'text':\n return renderText(node.value ?? '', opts);\n case 'paragraph':\n return createElement('p', { key }, ...renderChildren(node, opts));\n case 'heading': {\n const tag = HEADING_TAGS[Math.min(Math.max((node.depth ?? 1) - 1, 0), 5)];\n // R3-213: the no-acorn path has no hast stage, so the heading id the shared\n // `remarkHeadingAnchors` plugin sets via `data.hProperties.id` (+ the `data-slug`\n // fallback, R3-211) must be translated to React props HERE, or headings render\n // id-less and deep-linking (`#sec-8-9`) breaks in the safe path. These are\n // plugin-computed literal strings, not author input — safe to pass through.\n const hp = (node.data as { hProperties?: Record<string, unknown> } | undefined)?.hProperties;\n const headingProps: Record<string, string> = {};\n if (typeof hp?.id === 'string') headingProps.id = hp.id;\n if (typeof hp?.['data-slug'] === 'string') headingProps['data-slug'] = hp['data-slug'];\n return createElement(tag, { key, ...headingProps }, ...renderChildren(node, opts));\n }\n case 'strong':\n return createElement('strong', { key }, ...renderChildren(node, opts));\n case 'emphasis':\n return createElement('em', { key }, ...renderChildren(node, opts));\n case 'delete':\n return createElement('del', { key }, ...renderChildren(node, opts));\n case 'inlineCode':\n return createElement('code', { key }, node.value ?? '');\n case 'code':\n return createElement('pre', { key }, createElement('code', null, node.value ?? ''));\n case 'blockquote':\n return createElement('blockquote', { key }, ...renderChildren(node, opts));\n case 'list':\n return createElement(node.ordered ? 'ol' : 'ul', { key }, ...renderChildren(node, opts));\n case 'listItem':\n return createElement('li', { key }, ...renderChildren(node, opts));\n case 'thematicBreak':\n return createElement('hr', { key });\n case 'break':\n return createElement('br', { key });\n case 'link': {\n const href = sanitizeUrl(node.url);\n // A rejected scheme → render the link TEXT only (inert), never an <a href>.\n if (href === undefined) return createElement(Fragment, { key }, ...renderChildren(node, opts));\n return createElement('a', { key, href, title: node.title ?? undefined }, ...renderChildren(node, opts));\n }\n case 'image': {\n const src = sanitizeUrl(node.url);\n if (src === undefined) return node.alt ? createElement(Fragment, { key }, node.alt) : null;\n return createElement('img', { key, src, alt: node.alt ?? '', title: node.title ?? undefined });\n }\n // GFM tables.\n case 'table':\n return createElement('table', { key }, createElement('tbody', null, ...renderChildren(node, opts)));\n case 'tableRow':\n return createElement('tr', { key }, ...renderChildren(node, opts));\n case 'tableCell':\n return createElement('td', { key }, ...renderChildren(node, opts));\n // Raw HTML (`<script>`, `<div onclick>` at block level) → INERT TEXT. No\n // `rehype-raw`, never `dangerouslySetInnerHTML`. The literal markup is shown, not run.\n case 'html':\n return createElement(Fragment, { key }, node.value ?? '');\n // JSX `<Component/>` syntax → registry lookup by NAME, literal props only.\n case 'mdxJsxFlowElement':\n case 'mdxJsxTextElement': {\n const name = typeof node.name === 'string' ? node.name : '';\n const Component = name ? opts.components?.[name] : undefined;\n const children = renderChildren(node, opts);\n // Unknown tag (not in the registry) OR a fragment `<>` → render children inert,\n // NO element, NO author attributes. This is what neutralizes `<script>`/`<div\n // onclick>`/`<img onerror>` written as JSX.\n if (!Component) return createElement(Fragment, { key }, ...children);\n return createElement(Component, { key, ...literalProps(node.attributes) }, ...children);\n }\n // Inert expression nodes (should not occur — expression extension is off — but be\n // defensive if a tree from elsewhere carries them): render nothing.\n case 'mdxFlowExpression':\n case 'mdxTextExpression':\n case 'mdxjsEsm':\n return null;\n default:\n // Unknown node → render its children (never its raw value as markup).\n return node.children ? createElement(Fragment, { key }, ...renderChildren(node, opts)) : null;\n }\n}\n\n/**\n * Render a safe-parsed mdast tree to React. Pure and synchronous; carries every §5.1\n * security property (registry-only JSX, dropped expressions, inert raw HTML, URL\n * sanitizing, in-mount wikilinks). Feed it a tree from {@link parseSafeMdast}.\n */\nexport function renderMdast(tree: SafeMdastNode, options: RenderMdastOptions = {}): ReactNode {\n keyCounter = 0;\n return renderNode(tree, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAwD;AACxD,yBAA4B;AAC5B,sBAAmD;AA2CnD,SAAS,aAAa,YAAoE;AACxF,QAAM,QAAgC,CAAC;AACvC,aAAW,QAAQ,cAAc,CAAC,GAAG;AACnC,QAAI,KAAK,SAAS,kBAAmB;AACrC,QAAI,OAAO,KAAK,SAAS,SAAU;AAInC,QAAI,OAAO,KAAK,UAAU,SAAU,OAAM,KAAK,IAAI,IAAI,KAAK;AAAA,aACnD,KAAK,UAAU,QAAQ,KAAK,UAAU,OAAW,OAAM,KAAK,IAAI,IAAI;AAAA,EAE/E;AACA,SAAO;AACT;AAEA,IAAI,aAAa;AACjB,MAAM,UAAU,MAAM,MAAM,YAAY;AAIxC,SAAS,WAAW,OAAsB,SAA2D;AACnG,QAAM,QAAQ,MAAM,SAAS,MAAM;AACnC,QAAM,OAAO,UAAU,MAAM,MAAM;AACnC,QAAM,OAAO,SAAS,aAAY,gCAAY,IAAI,IAAI;AACtD,MAAI,SAAS,OAAW,QAAO;AAC/B,aAAO,4BAAc,KAAK,EAAE,MAAM,MAAM,iBAAiB,MAAM,QAAQ,KAAK,QAAQ,EAAE,GAAG,KAAK;AAChG;AAGA,SAAS,WAAW,OAAe,MAAqC;AACtE,QAAM,YAAQ,gCAAe,KAAK;AAClC,MAAI,CAAC,MAAO,QAAO;AACnB,SAAO,MAAM;AAAA,IAAI,CAAC,GAAG,MACnB,UAAU,QACN,4BAAc,uBAAU,EAAE,KAAK,IAAI,CAAC,GAAG,GAAG,EAAE,IAAI,QAChD,4BAAc,uBAAU,EAAE,KAAK,IAAI,CAAC,GAAG,GAAG,WAAW,EAAE,MAAM,KAAK,eAAe,CAAC;AAAA,EACxF;AACF;AAEA,SAAS,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AAAA,IACpG,KAAK;AACH,iBAAO,4BAAc,MAAM,EAAE,IAAI,GAAG,GAAG,eAAe,MAAM,IAAI,CAAC;AAAA,IACnE,KAAK;AACH,iBAAO,4BAAc,MAAM,EAAE,IAAI,GAAG,GAAG,eAAe,MAAM,IAAI,CAAC;AAAA;AAAA;AAAA,IAGnE,KAAK;AACH,iBAAO,4BAAc,uBAAU,EAAE,IAAI,GAAG,KAAK,SAAS,EAAE;AAAA;AAAA,IAE1D,KAAK;AAAA,IACL,KAAK,qBAAqB;AACxB,YAAM,OAAO,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO;AACzD,YAAM,YAAY,OAAO,KAAK,aAAa,IAAI,IAAI;AACnD,YAAM,WAAW,eAAe,MAAM,IAAI;AAI1C,UAAI,CAAC,UAAW,YAAO,4BAAc,uBAAU,EAAE,IAAI,GAAG,GAAG,QAAQ;AACnE,iBAAO,4BAAc,WAAW,EAAE,KAAK,GAAG,aAAa,KAAK,UAAU,EAAE,GAAG,GAAG,QAAQ;AAAA,IACxF;AAAA;AAAA;AAAA,IAGA,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT;AAEE,aAAO,KAAK,eAAW,4BAAc,uBAAU,EAAE,IAAI,GAAG,GAAG,eAAe,MAAM,IAAI,CAAC,IAAI;AAAA,EAC7F;AACF;AAOO,SAAS,YAAY,MAAqB,UAA8B,CAAC,GAAc;AAC5F,eAAa;AACb,SAAO,WAAW,MAAM,OAAO;AACjC;","names":[]}
1
+ {"version":3,"sources":["../../src/safeContent/renderMdast.tsx"],"sourcesContent":["import { createElement, Fragment, type ReactNode } from 'react';\nimport { sanitizeUrl } from './sanitizeUrl';\nimport { splitWikiLinks, type WikiLinkToken } from './wikilink';\nimport type { SafeMdastNode, SafeMdxAttribute } from './parseSafeMdast';\n\n// The mdast→React renderer for the safe content path (TRUST_MODES_SPEC §5.1). PURE\n// and synchronous — it only reads `node.type` off an already-parsed tree, so it\n// carries no ESM dep and is exhaustively unit-testable. Every security property lives\n// here:\n//\n// - **JSX tags resolve ONLY to a component registry, by name.** A `<Component/>`\n// node becomes `registry[name]` with **literal string props only**; an unknown tag\n// renders its children inert (a Fragment, no element) — so author-written `<div\n// onclick=…>`, `<img onerror=…>`, `<script>` never become an intrinsic element with\n// attacker attributes. (Block-level raw HTML arrives as an `html` node, below.)\n// - **Expression attributes are dropped.** `f={fetch(\"/x\")}` / `{...spread}` are\n// `mdxJsxExpressionAttribute` or object-valued `mdxJsxAttribute`s — never passed to\n// a component, never evaluated. (There is also no evaluator to reach — parse used\n// no acorn.)\n// - **Raw HTML is inert text.** `html` nodes render as their literal string via a\n// text node — never `dangerouslySetInnerHTML` (no `rehype-raw`).\n// - **URL-scheme sanitizer** on every `link`/`image` URL (`sanitizeUrl`).\n// - **Wikilinks resolve in-mount only** via an injected resolver; the renderer never\n// fetches.\n\nexport interface SafeContentComponents {\n /** Safe components an app exposes to `<Component/>` syntax (host/app-provided).\n * Looked up by the JSX tag name; anything not here renders inert. */\n [tag: string]: React.ComponentType<Record<string, string>>;\n}\n\nexport interface RenderMdastOptions {\n /** The component registry for `<Component/>` syntax. Absent ⇒ all JSX tags inert. */\n components?: SafeContentComponents;\n /**\n * Resolve a wikilink target to an href, **within the granted mount only** — a pure,\n * synchronous, mount-scoped lookup that MUST NOT fetch or reach out of the mount.\n * Return `undefined` for an unresolvable/out-of-mount target (rendered as inert\n * text). Absent ⇒ every wikilink renders as inert text.\n */\n resolveWikiLink?: (target: string) => string | undefined;\n}\n\n/** Extract the literal string props of a JSX element — `mdxJsxAttribute`s whose value\n * is a plain string. Expression attributes (object value) and spreads are DROPPED. */\nfunction literalProps(attributes: SafeMdxAttribute[] | undefined): Record<string, string> {\n const props: Record<string, string> = {};\n for (const attr of attributes ?? []) {\n if (attr.type !== 'mdxJsxAttribute') continue; // drop `{...spread}`\n if (typeof attr.name !== 'string') continue;\n // A literal attribute's value is a string (or null → boolean-ish `true`). An\n // expression value is an object (`mdxJsxAttributeValueExpression`) — DROP it: it\n // is an inert raw string, never a real value, and must never reach a component.\n if (typeof attr.value === 'string') props[attr.name] = attr.value;\n else if (attr.value === null || attr.value === undefined) props[attr.name] = '';\n // object-valued (expression) → skipped\n }\n return props;\n}\n\nlet keyCounter = 0;\nconst nextKey = () => `sc-${keyCounter++}`;\n\n/**\n * The element to build for a link/image: the host's registered override when it has one,\n * else the intrinsic tag.\n *\n * **Why this is safe.** `components` is the HOST's registry — the same one `<Component/>`\n * syntax resolves against — never author input. An author cannot add to it or choose one\n * here, because the lookup is by a FIXED key (`'a'`/`'img'`), not by anything read out of\n * the document. The URL is still `sanitizeUrl`'d before it is handed over, and only props\n * this renderer controls are passed. The trust boundary is unchanged: author text still\n * reaches nothing but children and a sanitized URL.\n *\n * **Why it is needed.** Without it, a safe-rendered document's links are raw `<a href>`,\n * so a click performs a REAL navigation. Inside an app's sandboxed iframe that is fatal —\n * the frame navigates away from the app, and in a routed host app it dies with\n * `Failed to construct 'URL': Invalid URL`. Hosts route links through a component for\n * exactly this reason, and the compiled-MDX path has always honoured that component; the\n * safe path silently ignored it, so one document behaved differently on the two renderers.\n */\nfunction elementFor(\n tag: 'a' | 'img',\n components: RenderMdastOptions['components'],\n): React.ElementType {\n return (components?.[tag] as React.ElementType) ?? tag;\n}\n\n/** Render a wikilink token via the in-mount resolver, or inert text when it can't\n * resolve (never a network call — resolution is the injected mount-scoped callback). */\nfunction renderWiki(token: WikiLinkToken, opts: RenderMdastOptions): ReactNode {\n const label = token.label ?? token.target;\n const href = opts.resolveWikiLink?.(token.target);\n const safe = href !== undefined ? sanitizeUrl(href) : undefined;\n if (safe === undefined) return label; // inert text — unresolved or out-of-mount\n return createElement(\n elementFor('a', opts.components),\n { href: safe, 'data-wikilink': token.target, key: nextKey() },\n label,\n );\n}\n\n/** Render a `text` node, splitting any `[[…]]` wikilinks out of it. */\nfunction renderText(value: string, opts: RenderMdastOptions): ReactNode {\n const parts = splitWikiLinks(value);\n if (!parts) return value;\n return parts.map((p, i) =>\n 'text' in p\n ? createElement(Fragment, { key: `t${i}` }, p.text)\n : createElement(Fragment, { key: `w${i}` }, renderWiki(p.wiki, opts)),\n );\n}\n\nfunction renderChildren(node: SafeMdastNode, opts: RenderMdastOptions): ReactNode[] {\n return (node.children ?? []).map((c, i) => renderNode(c, opts, i));\n}\n\n// Standard mdast block/inline nodes → a FIXED, safe React element. We control every\n// attribute; author input only reaches text content and (sanitized) URLs.\nconst HEADING_TAGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as const;\n\nfunction renderNode(node: SafeMdastNode, opts: RenderMdastOptions, index = 0): ReactNode {\n const key = `n${index}`;\n switch (node.type) {\n case 'root':\n return createElement(Fragment, { key }, ...renderChildren(node, opts));\n case 'text':\n return renderText(node.value ?? '', opts);\n case 'paragraph':\n return createElement('p', { key }, ...renderChildren(node, opts));\n case 'heading': {\n const tag = HEADING_TAGS[Math.min(Math.max((node.depth ?? 1) - 1, 0), 5)];\n // R3-213: the no-acorn path has no hast stage, so the heading id the shared\n // `remarkHeadingAnchors` plugin sets via `data.hProperties.id` (+ the `data-slug`\n // fallback, R3-211) must be translated to React props HERE, or headings render\n // id-less and deep-linking (`#sec-8-9`) breaks in the safe path. These are\n // plugin-computed literal strings, not author input — safe to pass through.\n const hp = (node.data as { hProperties?: Record<string, unknown> } | undefined)?.hProperties;\n const headingProps: Record<string, string> = {};\n if (typeof hp?.id === 'string') headingProps.id = hp.id;\n if (typeof hp?.['data-slug'] === 'string') headingProps['data-slug'] = hp['data-slug'];\n return createElement(tag, { key, ...headingProps }, ...renderChildren(node, opts));\n }\n case 'strong':\n return createElement('strong', { key }, ...renderChildren(node, opts));\n case 'emphasis':\n return createElement('em', { key }, ...renderChildren(node, opts));\n case 'delete':\n return createElement('del', { key }, ...renderChildren(node, opts));\n case 'inlineCode':\n return createElement('code', { key }, node.value ?? '');\n case 'code':\n return createElement('pre', { key }, createElement('code', null, node.value ?? ''));\n case 'blockquote':\n return createElement('blockquote', { key }, ...renderChildren(node, opts));\n case 'list':\n return createElement(node.ordered ? 'ol' : 'ul', { key }, ...renderChildren(node, opts));\n case 'listItem':\n return createElement('li', { key }, ...renderChildren(node, opts));\n case 'thematicBreak':\n return createElement('hr', { key });\n case 'break':\n return createElement('br', { key });\n case 'link': {\n const href = sanitizeUrl(node.url);\n // A rejected scheme → render the link TEXT only (inert), never an <a href>.\n if (href === undefined) return createElement(Fragment, { key }, ...renderChildren(node, opts));\n return createElement(\n elementFor('a', opts.components),\n { key, href, title: node.title ?? undefined },\n ...renderChildren(node, opts),\n );\n }\n case 'image': {\n const src = sanitizeUrl(node.url);\n if (src === undefined) return node.alt ? createElement(Fragment, { key }, node.alt) : null;\n return createElement(elementFor('img', opts.components), {\n key,\n src,\n alt: node.alt ?? '',\n title: node.title ?? undefined,\n });\n }\n // GFM tables.\n case 'table':\n return createElement('table', { key }, createElement('tbody', null, ...renderChildren(node, opts)));\n case 'tableRow':\n return createElement('tr', { key }, ...renderChildren(node, opts));\n case 'tableCell':\n return createElement('td', { key }, ...renderChildren(node, opts));\n // Raw HTML (`<script>`, `<div onclick>` at block level) → INERT TEXT. No\n // `rehype-raw`, never `dangerouslySetInnerHTML`. The literal markup is shown, not run.\n case 'html':\n return createElement(Fragment, { key }, node.value ?? '');\n // JSX `<Component/>` syntax → registry lookup by NAME, literal props only.\n case 'mdxJsxFlowElement':\n case 'mdxJsxTextElement': {\n const name = typeof node.name === 'string' ? node.name : '';\n const Component = name ? opts.components?.[name] : undefined;\n const children = renderChildren(node, opts);\n // Unknown tag (not in the registry) OR a fragment `<>` → render children inert,\n // NO element, NO author attributes. This is what neutralizes `<script>`/`<div\n // onclick>`/`<img onerror>` written as JSX.\n if (!Component) return createElement(Fragment, { key }, ...children);\n return createElement(Component, { key, ...literalProps(node.attributes) }, ...children);\n }\n // Inert expression nodes (should not occur — expression extension is off — but be\n // defensive if a tree from elsewhere carries them): render nothing.\n case 'mdxFlowExpression':\n case 'mdxTextExpression':\n case 'mdxjsEsm':\n return null;\n default:\n // Unknown node → render its children (never its raw value as markup).\n return node.children ? createElement(Fragment, { key }, ...renderChildren(node, opts)) : null;\n }\n}\n\n/**\n * Render a safe-parsed mdast tree to React. Pure and synchronous; carries every §5.1\n * security property (registry-only JSX, dropped expressions, inert raw HTML, URL\n * sanitizing, in-mount wikilinks). Feed it a tree from {@link parseSafeMdast}.\n */\nexport function renderMdast(tree: SafeMdastNode, options: RenderMdastOptions = {}): ReactNode {\n keyCounter = 0;\n return renderNode(tree, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAwD;AACxD,yBAA4B;AAC5B,sBAAmD;AA2CnD,SAAS,aAAa,YAAoE;AACxF,QAAM,QAAgC,CAAC;AACvC,aAAW,QAAQ,cAAc,CAAC,GAAG;AACnC,QAAI,KAAK,SAAS,kBAAmB;AACrC,QAAI,OAAO,KAAK,SAAS,SAAU;AAInC,QAAI,OAAO,KAAK,UAAU,SAAU,OAAM,KAAK,IAAI,IAAI,KAAK;AAAA,aACnD,KAAK,UAAU,QAAQ,KAAK,UAAU,OAAW,OAAM,KAAK,IAAI,IAAI;AAAA,EAE/E;AACA,SAAO;AACT;AAEA,IAAI,aAAa;AACjB,MAAM,UAAU,MAAM,MAAM,YAAY;AAoBxC,SAAS,WACP,KACA,YACmB;AACnB,SAAQ,aAAa,GAAG,KAA2B;AACrD;AAIA,SAAS,WAAW,OAAsB,MAAqC;AAC7E,QAAM,QAAQ,MAAM,SAAS,MAAM;AACnC,QAAM,OAAO,KAAK,kBAAkB,MAAM,MAAM;AAChD,QAAM,OAAO,SAAS,aAAY,gCAAY,IAAI,IAAI;AACtD,MAAI,SAAS,OAAW,QAAO;AAC/B,aAAO;AAAA,IACL,WAAW,KAAK,KAAK,UAAU;AAAA,IAC/B,EAAE,MAAM,MAAM,iBAAiB,MAAM,QAAQ,KAAK,QAAQ,EAAE;AAAA,IAC5D;AAAA,EACF;AACF;AAGA,S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AC,IAAI;AAAA,EAC7F;AACF;AAOO,SAAS,YAAY,MAAqB,UAA8B,CAAC,GAAc;AAC5F,eAAa;AACb,SAAO,WAAW,MAAM,OAAO;AACjC;","names":[]}
@@ -14,18 +14,25 @@ function literalProps(attributes) {
14
14
  }
15
15
  let keyCounter = 0;
16
16
  const nextKey = () => `sc-${keyCounter++}`;
17
- function renderWiki(token, resolve) {
17
+ function elementFor(tag, components) {
18
+ return components?.[tag] ?? tag;
19
+ }
20
+ function renderWiki(token, opts) {
18
21
  const label = token.label ?? token.target;
19
- const href = resolve?.(token.target);
22
+ const href = opts.resolveWikiLink?.(token.target);
20
23
  const safe = href !== void 0 ? sanitizeUrl(href) : void 0;
21
24
  if (safe === void 0) return label;
22
- return createElement("a", { href: safe, "data-wikilink": token.target, key: nextKey() }, label);
25
+ return createElement(
26
+ elementFor("a", opts.components),
27
+ { href: safe, "data-wikilink": token.target, key: nextKey() },
28
+ label
29
+ );
23
30
  }
24
31
  function renderText(value, opts) {
25
32
  const parts = splitWikiLinks(value);
26
33
  if (!parts) return value;
27
34
  return parts.map(
28
- (p, i) => "text" in p ? createElement(Fragment, { key: `t${i}` }, p.text) : createElement(Fragment, { key: `w${i}` }, renderWiki(p.wiki, opts.resolveWikiLink))
35
+ (p, i) => "text" in p ? createElement(Fragment, { key: `t${i}` }, p.text) : createElement(Fragment, { key: `w${i}` }, renderWiki(p.wiki, opts))
29
36
  );
30
37
  }
31
38
  function renderChildren(node, opts) {
@@ -72,12 +79,21 @@ function renderNode(node, opts, index = 0) {
72
79
  case "link": {
73
80
  const href = sanitizeUrl(node.url);
74
81
  if (href === void 0) return createElement(Fragment, { key }, ...renderChildren(node, opts));
75
- return createElement("a", { key, href, title: node.title ?? void 0 }, ...renderChildren(node, opts));
82
+ return createElement(
83
+ elementFor("a", opts.components),
84
+ { key, href, title: node.title ?? void 0 },
85
+ ...renderChildren(node, opts)
86
+ );
76
87
  }
77
88
  case "image": {
78
89
  const src = sanitizeUrl(node.url);
79
90
  if (src === void 0) return node.alt ? createElement(Fragment, { key }, node.alt) : null;
80
- return createElement("img", { key, src, alt: node.alt ?? "", title: node.title ?? void 0 });
91
+ return createElement(elementFor("img", opts.components), {
92
+ key,
93
+ src,
94
+ alt: node.alt ?? "",
95
+ title: node.title ?? void 0
96
+ });
81
97
  }
82
98
  // GFM tables.
83
99
  case "table":
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/safeContent/renderMdast.tsx"],"sourcesContent":["import { createElement, Fragment, type ReactNode } from 'react';\nimport { sanitizeUrl } from './sanitizeUrl';\nimport { splitWikiLinks, type WikiLinkToken } from './wikilink';\nimport type { SafeMdastNode, SafeMdxAttribute } from './parseSafeMdast';\n\n// The mdast→React renderer for the safe content path (TRUST_MODES_SPEC §5.1). PURE\n// and synchronous — it only reads `node.type` off an already-parsed tree, so it\n// carries no ESM dep and is exhaustively unit-testable. Every security property lives\n// here:\n//\n// - **JSX tags resolve ONLY to a component registry, by name.** A `<Component/>`\n// node becomes `registry[name]` with **literal string props only**; an unknown tag\n// renders its children inert (a Fragment, no element) — so author-written `<div\n// onclick=…>`, `<img onerror=…>`, `<script>` never become an intrinsic element with\n// attacker attributes. (Block-level raw HTML arrives as an `html` node, below.)\n// - **Expression attributes are dropped.** `f={fetch(\"/x\")}` / `{...spread}` are\n// `mdxJsxExpressionAttribute` or object-valued `mdxJsxAttribute`s — never passed to\n// a component, never evaluated. (There is also no evaluator to reach — parse used\n// no acorn.)\n// - **Raw HTML is inert text.** `html` nodes render as their literal string via a\n// text node — never `dangerouslySetInnerHTML` (no `rehype-raw`).\n// - **URL-scheme sanitizer** on every `link`/`image` URL (`sanitizeUrl`).\n// - **Wikilinks resolve in-mount only** via an injected resolver; the renderer never\n// fetches.\n\nexport interface SafeContentComponents {\n /** Safe components an app exposes to `<Component/>` syntax (host/app-provided).\n * Looked up by the JSX tag name; anything not here renders inert. */\n [tag: string]: React.ComponentType<Record<string, string>>;\n}\n\nexport interface RenderMdastOptions {\n /** The component registry for `<Component/>` syntax. Absent ⇒ all JSX tags inert. */\n components?: SafeContentComponents;\n /**\n * Resolve a wikilink target to an href, **within the granted mount only** — a pure,\n * synchronous, mount-scoped lookup that MUST NOT fetch or reach out of the mount.\n * Return `undefined` for an unresolvable/out-of-mount target (rendered as inert\n * text). Absent ⇒ every wikilink renders as inert text.\n */\n resolveWikiLink?: (target: string) => string | undefined;\n}\n\n/** Extract the literal string props of a JSX element — `mdxJsxAttribute`s whose value\n * is a plain string. Expression attributes (object value) and spreads are DROPPED. */\nfunction literalProps(attributes: SafeMdxAttribute[] | undefined): Record<string, string> {\n const props: Record<string, string> = {};\n for (const attr of attributes ?? []) {\n if (attr.type !== 'mdxJsxAttribute') continue; // drop `{...spread}`\n if (typeof attr.name !== 'string') continue;\n // A literal attribute's value is a string (or null → boolean-ish `true`). An\n // expression value is an object (`mdxJsxAttributeValueExpression`) — DROP it: it\n // is an inert raw string, never a real value, and must never reach a component.\n if (typeof attr.value === 'string') props[attr.name] = attr.value;\n else if (attr.value === null || attr.value === undefined) props[attr.name] = '';\n // object-valued (expression) → skipped\n }\n return props;\n}\n\nlet keyCounter = 0;\nconst nextKey = () => `sc-${keyCounter++}`;\n\n/** Render a wikilink token via the in-mount resolver, or inert text when it can't\n * resolve (never a network call — resolution is the injected mount-scoped callback). */\nfunction renderWiki(token: WikiLinkToken, resolve: RenderMdastOptions['resolveWikiLink']): ReactNode {\n const label = token.label ?? token.target;\n const href = resolve?.(token.target);\n const safe = href !== undefined ? sanitizeUrl(href) : undefined;\n if (safe === undefined) return label; // inert text — unresolved or out-of-mount\n return createElement('a', { href: safe, 'data-wikilink': token.target, key: nextKey() }, label);\n}\n\n/** Render a `text` node, splitting any `[[…]]` wikilinks out of it. */\nfunction renderText(value: string, opts: RenderMdastOptions): ReactNode {\n const parts = splitWikiLinks(value);\n if (!parts) return value;\n return parts.map((p, i) =>\n 'text' in p\n ? createElement(Fragment, { key: `t${i}` }, p.text)\n : createElement(Fragment, { key: `w${i}` }, renderWiki(p.wiki, opts.resolveWikiLink)),\n );\n}\n\nfunction renderChildren(node: SafeMdastNode, opts: RenderMdastOptions): ReactNode[] {\n return (node.children ?? []).map((c, i) => renderNode(c, opts, i));\n}\n\n// Standard mdast block/inline nodes → a FIXED, safe React element. We control every\n// attribute; author input only reaches text content and (sanitized) URLs.\nconst HEADING_TAGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as const;\n\nfunction renderNode(node: SafeMdastNode, opts: RenderMdastOptions, index = 0): ReactNode {\n const key = `n${index}`;\n switch (node.type) {\n case 'root':\n return createElement(Fragment, { key }, ...renderChildren(node, opts));\n case 'text':\n return renderText(node.value ?? '', opts);\n case 'paragraph':\n return createElement('p', { key }, ...renderChildren(node, opts));\n case 'heading': {\n const tag = HEADING_TAGS[Math.min(Math.max((node.depth ?? 1) - 1, 0), 5)];\n // R3-213: the no-acorn path has no hast stage, so the heading id the shared\n // `remarkHeadingAnchors` plugin sets via `data.hProperties.id` (+ the `data-slug`\n // fallback, R3-211) must be translated to React props HERE, or headings render\n // id-less and deep-linking (`#sec-8-9`) breaks in the safe path. These are\n // plugin-computed literal strings, not author input — safe to pass through.\n const hp = (node.data as { hProperties?: Record<string, unknown> } | undefined)?.hProperties;\n const headingProps: Record<string, string> = {};\n if (typeof hp?.id === 'string') headingProps.id = hp.id;\n if (typeof hp?.['data-slug'] === 'string') headingProps['data-slug'] = hp['data-slug'];\n return createElement(tag, { key, ...headingProps }, ...renderChildren(node, opts));\n }\n case 'strong':\n return createElement('strong', { key }, ...renderChildren(node, opts));\n case 'emphasis':\n return createElement('em', { key }, ...renderChildren(node, opts));\n case 'delete':\n return createElement('del', { key }, ...renderChildren(node, opts));\n case 'inlineCode':\n return createElement('code', { key }, node.value ?? '');\n case 'code':\n return createElement('pre', { key }, createElement('code', null, node.value ?? ''));\n case 'blockquote':\n return createElement('blockquote', { key }, ...renderChildren(node, opts));\n case 'list':\n return createElement(node.ordered ? 'ol' : 'ul', { key }, ...renderChildren(node, opts));\n case 'listItem':\n return createElement('li', { key }, ...renderChildren(node, opts));\n case 'thematicBreak':\n return createElement('hr', { key });\n case 'break':\n return createElement('br', { key });\n case 'link': {\n const href = sanitizeUrl(node.url);\n // A rejected scheme → render the link TEXT only (inert), never an <a href>.\n if (href === undefined) return createElement(Fragment, { key }, ...renderChildren(node, opts));\n return createElement('a', { key, href, title: node.title ?? undefined }, ...renderChildren(node, opts));\n }\n case 'image': {\n const src = sanitizeUrl(node.url);\n if (src === undefined) return node.alt ? createElement(Fragment, { key }, node.alt) : null;\n return createElement('img', { key, src, alt: node.alt ?? '', title: node.title ?? undefined });\n }\n // GFM tables.\n case 'table':\n return createElement('table', { key }, createElement('tbody', null, ...renderChildren(node, opts)));\n case 'tableRow':\n return createElement('tr', { key }, ...renderChildren(node, opts));\n case 'tableCell':\n return createElement('td', { key }, ...renderChildren(node, opts));\n // Raw HTML (`<script>`, `<div onclick>` at block level) → INERT TEXT. No\n // `rehype-raw`, never `dangerouslySetInnerHTML`. The literal markup is shown, not run.\n case 'html':\n return createElement(Fragment, { key }, node.value ?? '');\n // JSX `<Component/>` syntax → registry lookup by NAME, literal props only.\n case 'mdxJsxFlowElement':\n case 'mdxJsxTextElement': {\n const name = typeof node.name === 'string' ? node.name : '';\n const Component = name ? opts.components?.[name] : undefined;\n const children = renderChildren(node, opts);\n // Unknown tag (not in the registry) OR a fragment `<>` → render children inert,\n // NO element, NO author attributes. This is what neutralizes `<script>`/`<div\n // onclick>`/`<img onerror>` written as JSX.\n if (!Component) return createElement(Fragment, { key }, ...children);\n return createElement(Component, { key, ...literalProps(node.attributes) }, ...children);\n }\n // Inert expression nodes (should not occur — expression extension is off — but be\n // defensive if a tree from elsewhere carries them): render nothing.\n case 'mdxFlowExpression':\n case 'mdxTextExpression':\n case 'mdxjsEsm':\n return null;\n default:\n // Unknown node → render its children (never its raw value as markup).\n return node.children ? createElement(Fragment, { key }, ...renderChildren(node, opts)) : null;\n }\n}\n\n/**\n * Render a safe-parsed mdast tree to React. Pure and synchronous; carries every §5.1\n * security property (registry-only JSX, dropped expressions, inert raw HTML, URL\n * sanitizing, in-mount wikilinks). Feed it a tree from {@link parseSafeMdast}.\n */\nexport function renderMdast(tree: SafeMdastNode, options: RenderMdastOptions = {}): ReactNode {\n keyCounter = 0;\n return renderNode(tree, options);\n}\n"],"mappings":";AAAA,SAAS,eAAe,gBAAgC;AACxD,SAAS,mBAAmB;AAC5B,SAAS,sBAA0C;AA2CnD,SAAS,aAAa,YAAoE;AACxF,QAAM,QAAgC,CAAC;AACvC,aAAW,QAAQ,cAAc,CAAC,GAAG;AACnC,QAAI,KAAK,SAAS,kBAAmB;AACrC,QAAI,OAAO,KAAK,SAAS,SAAU;AAInC,QAAI,OAAO,KAAK,UAAU,SAAU,OAAM,KAAK,IAAI,IAAI,KAAK;AAAA,aACnD,KAAK,UAAU,QAAQ,KAAK,UAAU,OAAW,OAAM,KAAK,IAAI,IAAI;AAAA,EAE/E;AACA,SAAO;AACT;AAEA,IAAI,aAAa;AACjB,MAAM,UAAU,MAAM,MAAM,YAAY;AAIxC,SAAS,WAAW,OAAsB,SAA2D;AACnG,QAAM,QAAQ,MAAM,SAAS,MAAM;AACnC,QAAM,OAAO,UAAU,MAAM,MAAM;AACnC,QAAM,OAAO,SAAS,SAAY,YAAY,IAAI,IAAI;AACtD,MAAI,SAAS,OAAW,QAAO;AAC/B,SAAO,cAAc,KAAK,EAAE,MAAM,MAAM,iBAAiB,MAAM,QAAQ,KAAK,QAAQ,EAAE,GAAG,KAAK;AAChG;AAGA,SAAS,WAAW,OAAe,MAAqC;AACtE,QAAM,QAAQ,eAAe,KAAK;AAClC,MAAI,CAAC,MAAO,QAAO;AACnB,SAAO,MAAM;AAAA,IAAI,CAAC,GAAG,MACnB,UAAU,IACN,cAAc,UAAU,EAAE,KAAK,IAAI,CAAC,GAAG,GAAG,EAAE,IAAI,IAChD,cAAc,UAAU,EAAE,KAAK,IAAI,CAAC,GAAG,GAAG,WAAW,EAAE,MA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;AAAA,IACpG,KAAK;AACH,aAAO,cAAc,MAAM,EAAE,IAAI,GAAG,GAAG,eAAe,MAAM,IAAI,CAAC;AAAA,IACnE,KAAK;AACH,aAAO,cAAc,MAAM,EAAE,IAAI,GAAG,GAAG,eAAe,MAAM,IAAI,CAAC;AAAA;AAAA;AAAA,IAGnE,KAAK;AACH,aAAO,cAAc,UAAU,EAAE,IAAI,GAAG,KAAK,SAAS,EAAE;AAAA;AAAA,IAE1D,KAAK;AAAA,IACL,KAAK,qBAAqB;AACxB,YAAM,OAAO,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO;AACzD,YAAM,YAAY,OAAO,KAAK,aAAa,IAAI,IAAI;AACnD,YAAM,WAAW,eAAe,MAAM,IAAI;AAI1C,UAAI,CAAC,UAAW,QAAO,cAAc,UAAU,EAAE,IAAI,GAAG,GAAG,QAAQ;AACnE,aAAO,cAAc,WAAW,EAAE,KAAK,GAAG,aAAa,KAAK,UAAU,EAAE,GAAG,GAAG,QAAQ;AAAA,IACxF;AAAA;AAAA;AAAA,IAGA,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT;AAEE,aAAO,KAAK,WAAW,cAAc,UAAU,EAAE,IAAI,GAAG,GAAG,eAAe,MAAM,IAAI,CAAC,IAAI;AAAA,EAC7F;AACF;AAOO,SAAS,YAAY,MAAqB,UAA8B,CAAC,GAAc;AAC5F,eAAa;AACb,SAAO,WAAW,MAAM,OAAO;AACjC;","names":[]}
1
+ {"version":3,"sources":["../../src/safeContent/renderMdast.tsx"],"sourcesContent":["import { createElement, Fragment, type ReactNode } from 'react';\nimport { sanitizeUrl } from './sanitizeUrl';\nimport { splitWikiLinks, type WikiLinkToken } from './wikilink';\nimport type { SafeMdastNode, SafeMdxAttribute } from './parseSafeMdast';\n\n// The mdast→React renderer for the safe content path (TRUST_MODES_SPEC §5.1). PURE\n// and synchronous — it only reads `node.type` off an already-parsed tree, so it\n// carries no ESM dep and is exhaustively unit-testable. Every security property lives\n// here:\n//\n// - **JSX tags resolve ONLY to a component registry, by name.** A `<Component/>`\n// node becomes `registry[name]` with **literal string props only**; an unknown tag\n// renders its children inert (a Fragment, no element) — so author-written `<div\n// onclick=…>`, `<img onerror=…>`, `<script>` never become an intrinsic element with\n// attacker attributes. (Block-level raw HTML arrives as an `html` node, below.)\n// - **Expression attributes are dropped.** `f={fetch(\"/x\")}` / `{...spread}` are\n// `mdxJsxExpressionAttribute` or object-valued `mdxJsxAttribute`s — never passed to\n// a component, never evaluated. (There is also no evaluator to reach — parse used\n// no acorn.)\n// - **Raw HTML is inert text.** `html` nodes render as their literal string via a\n// text node — never `dangerouslySetInnerHTML` (no `rehype-raw`).\n// - **URL-scheme sanitizer** on every `link`/`image` URL (`sanitizeUrl`).\n// - **Wikilinks resolve in-mount only** via an injected resolver; the renderer never\n// fetches.\n\nexport interface SafeContentComponents {\n /** Safe components an app exposes to `<Component/>` syntax (host/app-provided).\n * Looked up by the JSX tag name; anything not here renders inert. */\n [tag: string]: React.ComponentType<Record<string, string>>;\n}\n\nexport interface RenderMdastOptions {\n /** The component registry for `<Component/>` syntax. Absent ⇒ all JSX tags inert. */\n components?: SafeContentComponents;\n /**\n * Resolve a wikilink target to an href, **within the granted mount only** — a pure,\n * synchronous, mount-scoped lookup that MUST NOT fetch or reach out of the mount.\n * Return `undefined` for an unresolvable/out-of-mount target (rendered as inert\n * text). Absent ⇒ every wikilink renders as inert text.\n */\n resolveWikiLink?: (target: string) => string | undefined;\n}\n\n/** Extract the literal string props of a JSX element — `mdxJsxAttribute`s whose value\n * is a plain string. Expression attributes (object value) and spreads are DROPPED. */\nfunction literalProps(attributes: SafeMdxAttribute[] | undefined): Record<string, string> {\n const props: Record<string, string> = {};\n for (const attr of attributes ?? []) {\n if (attr.type !== 'mdxJsxAttribute') continue; // drop `{...spread}`\n if (typeof attr.name !== 'string') continue;\n // A literal attribute's value is a string (or null → boolean-ish `true`). An\n // expression value is an object (`mdxJsxAttributeValueExpression`) — DROP it: it\n // is an inert raw string, never a real value, and must never reach a component.\n if (typeof attr.value === 'string') props[attr.name] = attr.value;\n else if (attr.value === null || attr.value === undefined) props[attr.name] = '';\n // object-valued (expression) → skipped\n }\n return props;\n}\n\nlet keyCounter = 0;\nconst nextKey = () => `sc-${keyCounter++}`;\n\n/**\n * The element to build for a link/image: the host's registered override when it has one,\n * else the intrinsic tag.\n *\n * **Why this is safe.** `components` is the HOST's registry — the same one `<Component/>`\n * syntax resolves against — never author input. An author cannot add to it or choose one\n * here, because the lookup is by a FIXED key (`'a'`/`'img'`), not by anything read out of\n * the document. The URL is still `sanitizeUrl`'d before it is handed over, and only props\n * this renderer controls are passed. The trust boundary is unchanged: author text still\n * reaches nothing but children and a sanitized URL.\n *\n * **Why it is needed.** Without it, a safe-rendered document's links are raw `<a href>`,\n * so a click performs a REAL navigation. Inside an app's sandboxed iframe that is fatal —\n * the frame navigates away from the app, and in a routed host app it dies with\n * `Failed to construct 'URL': Invalid URL`. Hosts route links through a component for\n * exactly this reason, and the compiled-MDX path has always honoured that component; the\n * safe path silently ignored it, so one document behaved differently on the two renderers.\n */\nfunction elementFor(\n tag: 'a' | 'img',\n components: RenderMdastOptions['components'],\n): React.ElementType {\n return (components?.[tag] as React.ElementType) ?? tag;\n}\n\n/** Render a wikilink token via the in-mount resolver, or inert text when it can't\n * resolve (never a network call — resolution is the injected mount-scoped callback). */\nfunction renderWiki(token: WikiLinkToken, opts: RenderMdastOptions): ReactNode {\n const label = token.label ?? token.target;\n const href = opts.resolveWikiLink?.(token.target);\n const safe = href !== undefined ? sanitizeUrl(href) : undefined;\n if (safe === undefined) return label; // inert text — unresolved or out-of-mount\n return createElement(\n elementFor('a', opts.components),\n { href: safe, 'data-wikilink': token.target, key: nextKey() },\n label,\n );\n}\n\n/** Render a `text` node, splitting any `[[…]]` wikilinks out of it. */\nfunction renderText(value: string, opts: RenderMdastOptions): ReactNode {\n const parts = splitWikiLinks(value);\n if (!parts) return value;\n return parts.map((p, i) =>\n 'text' in p\n ? createElement(Fragment, { key: `t${i}` }, p.text)\n : createElement(Fragment, { key: `w${i}` }, renderWiki(p.wiki, opts)),\n );\n}\n\nfunction renderChildren(node: SafeMdastNode, opts: RenderMdastOptions): ReactNode[] {\n return (node.children ?? []).map((c, i) => renderNode(c, opts, i));\n}\n\n// Standard mdast block/inline nodes → a FIXED, safe React element. We control every\n// attribute; author input only reaches text content and (sanitized) URLs.\nconst HEADING_TAGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as const;\n\nfunction renderNode(node: SafeMdastNode, opts: RenderMdastOptions, index = 0): ReactNode {\n const key = `n${index}`;\n switch (node.type) {\n case 'root':\n return createElement(Fragment, { key }, ...renderChildren(node, opts));\n case 'text':\n return renderText(node.value ?? '', opts);\n case 'paragraph':\n return createElement('p', { key }, ...renderChildren(node, opts));\n case 'heading': {\n const tag = HEADING_TAGS[Math.min(Math.max((node.depth ?? 1) - 1, 0), 5)];\n // R3-213: the no-acorn path has no hast stage, so the heading id the shared\n // `remarkHeadingAnchors` plugin sets via `data.hProperties.id` (+ the `data-slug`\n // fallback, R3-211) must be translated to React props HERE, or headings render\n // id-less and deep-linking (`#sec-8-9`) breaks in the safe path. These are\n // plugin-computed literal strings, not author input — safe to pass through.\n const hp = (node.data as { hProperties?: Record<string, unknown> } | undefined)?.hProperties;\n const headingProps: Record<string, string> = {};\n if (typeof hp?.id === 'string') headingProps.id = hp.id;\n if (typeof hp?.['data-slug'] === 'string') headingProps['data-slug'] = hp['data-slug'];\n return createElement(tag, { key, ...headingProps }, ...renderChildren(node, opts));\n }\n case 'strong':\n return createElement('strong', { key }, ...renderChildren(node, opts));\n case 'emphasis':\n return createElement('em', { key }, ...renderChildren(node, opts));\n case 'delete':\n return createElement('del', { key }, ...renderChildren(node, opts));\n case 'inlineCode':\n return createElement('code', { key }, node.value ?? '');\n case 'code':\n return createElement('pre', { key }, createElement('code', null, node.value ?? ''));\n case 'blockquote':\n return createElement('blockquote', { key }, ...renderChildren(node, opts));\n case 'list':\n return createElement(node.ordered ? 'ol' : 'ul', { key }, ...renderChildren(node, opts));\n case 'listItem':\n return createElement('li', { key }, ...renderChildren(node, opts));\n case 'thematicBreak':\n return createElement('hr', { key });\n case 'break':\n return createElement('br', { key });\n case 'link': {\n const href = sanitizeUrl(node.url);\n // A rejected scheme → render the link TEXT only (inert), never an <a href>.\n if (href === undefined) return createElement(Fragment, { key }, ...renderChildren(node, opts));\n return createElement(\n elementFor('a', opts.components),\n { key, href, title: node.title ?? undefined },\n ...renderChildren(node, opts),\n );\n }\n case 'image': {\n const src = sanitizeUrl(node.url);\n if (src === undefined) return node.alt ? createElement(Fragment, { key }, node.alt) : null;\n return createElement(elementFor('img', opts.components), {\n key,\n src,\n alt: node.alt ?? '',\n title: node.title ?? undefined,\n });\n }\n // GFM tables.\n case 'table':\n return createElement('table', { key }, createElement('tbody', null, ...renderChildren(node, opts)));\n case 'tableRow':\n return createElement('tr', { key }, ...renderChildren(node, opts));\n case 'tableCell':\n return createElement('td', { key }, ...renderChildren(node, opts));\n // Raw HTML (`<script>`, `<div onclick>` at block level) → INERT TEXT. No\n // `rehype-raw`, never `dangerouslySetInnerHTML`. The literal markup is shown, not run.\n case 'html':\n return createElement(Fragment, { key }, node.value ?? '');\n // JSX `<Component/>` syntax → registry lookup by NAME, literal props only.\n case 'mdxJsxFlowElement':\n case 'mdxJsxTextElement': {\n const name = typeof node.name === 'string' ? node.name : '';\n const Component = name ? opts.components?.[name] : undefined;\n const children = renderChildren(node, opts);\n // Unknown tag (not in the registry) OR a fragment `<>` → render children inert,\n // NO element, NO author attributes. This is what neutralizes `<script>`/`<div\n // onclick>`/`<img onerror>` written as JSX.\n if (!Component) return createElement(Fragment, { key }, ...children);\n return createElement(Component, { key, ...literalProps(node.attributes) }, ...children);\n }\n // Inert expression nodes (should not occur — expression extension is off — but be\n // defensive if a tree from elsewhere carries them): render nothing.\n case 'mdxFlowExpression':\n case 'mdxTextExpression':\n case 'mdxjsEsm':\n return null;\n default:\n // Unknown node → render its children (never its raw value as markup).\n return node.children ? createElement(Fragment, { key }, ...renderChildren(node, opts)) : null;\n }\n}\n\n/**\n * Render a safe-parsed mdast tree to React. Pure and synchronous; carries every §5.1\n * security property (registry-only JSX, dropped expressions, inert raw HTML, URL\n * sanitizing, in-mount wikilinks). Feed it a tree from {@link parseSafeMdast}.\n */\nexport function renderMdast(tree: SafeMdastNode, options: RenderMdastOptions = {}): ReactNode {\n keyCounter = 0;\n return renderNode(tree, options);\n}\n"],"mappings":";AAAA,SAAS,eAAe,gBAAgC;AACxD,SAAS,mBAAmB;AAC5B,SAAS,sBAA0C;AA2CnD,SAAS,aAAa,YAAoE;AACxF,QAAM,QAAgC,CAAC;AACvC,aAAW,QAAQ,cAAc,CAAC,GAAG;AACnC,QAAI,KAAK,SAAS,kBAAmB;AACrC,QAAI,OAAO,KAAK,SAAS,SAAU;AAInC,QAAI,OAAO,KAAK,UAAU,SAAU,OAAM,KAAK,IAAI,IAAI,KAAK;AAAA,aACnD,KAAK,UAAU,QAAQ,KAAK,UAAU,OAAW,OAAM,KAAK,IAAI,IAAI;AAAA,EAE/E;AACA,SAAO;AACT;AAEA,IAAI,aAAa;AACjB,MAAM,UAAU,MAAM,MAAM,YAAY;AAoBxC,SAAS,WACP,KACA,YACmB;AACnB,SAAQ,aAAa,GAAG,KAA2B;AACrD;AAIA,SAAS,WAAW,OAAsB,MAAqC;AAC7E,QAAM,QAAQ,MAAM,SAAS,MAAM;AACnC,QAAM,OAAO,KAAK,kBAAkB,MAAM,MAAM;AAChD,QAAM,OAAO,SAAS,SAAY,YAAY,IAAI,IAAI;AACtD,MAAI,SAAS,OAAW,QAAO;AAC/B,SAAO;AAAA,IACL,WAAW,KAAK,KAAK,UAAU;AAAA,IAC/B,EAAE,MAAM,MAAM,iBAAiB,MAAM,QAAQ,KAAK,QAAQ,EAAE;AAAA,IAC5D;AAAA,EACF;AACF;AAGA,SAAS,WAAW,OAAe,MAAqC;AACtE,QAAM,QAAQ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O;AACjC;","names":[]}
package/dist/version.cjs CHANGED
@@ -21,7 +21,7 @@ __export(version_exports, {
21
21
  SDK_VERSION: () => SDK_VERSION
22
22
  });
23
23
  module.exports = __toCommonJS(version_exports);
24
- const SDK_VERSION = "0.36.0";
24
+ const SDK_VERSION = "0.38.0";
25
25
  // Annotate the CommonJS export names for ESM import in node:
26
26
  0 && (module.exports = {
27
27
  SDK_VERSION
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.36.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIO,MAAM,cAAc;","names":[]}
1
+ {"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.38.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIO,MAAM,cAAc;","names":[]}
@@ -1,4 +1,4 @@
1
1
  /** This SDK's package version, baked from package.json at build (SP2-6). */
2
- declare const SDK_VERSION = "0.36.0";
2
+ declare const SDK_VERSION = "0.38.0";
3
3
 
4
4
  export { SDK_VERSION };
package/dist/version.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  /** This SDK's package version, baked from package.json at build (SP2-6). */
2
- declare const SDK_VERSION = "0.36.0";
2
+ declare const SDK_VERSION = "0.38.0";
3
3
 
4
4
  export { SDK_VERSION };
package/dist/version.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./chunk-VHAA22YE.js";
2
- const SDK_VERSION = "0.36.0";
2
+ const SDK_VERSION = "0.38.0";
3
3
  export {
4
4
  SDK_VERSION
5
5
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.36.0';\n"],"mappings":";AAIO,MAAM,cAAc;","names":[]}
1
+ {"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.38.0';\n"],"mappings":";AAIO,MAAM,cAAc;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@immediately-run/sdk",
3
- "version": "0.36.0",
3
+ "version": "0.38.0",
4
4
  "description": "Runtime SDK for code executing inside an immediately.run sandbox.",
5
5
  "license": "MIT",
6
6
  "repository": "github:immediately-run/immediately-run-sdk",