@sixb/app 0.1.16 → 0.1.18

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 (106) hide show
  1. package/README.md +8 -0
  2. package/dist/agent/agent-chat.d.ts.map +1 -1
  3. package/dist/agent/bash/interpret.d.ts +6 -2
  4. package/dist/agent/bash/interpret.d.ts.map +1 -1
  5. package/dist/agent/components/approval-mode-icons.d.ts +5 -0
  6. package/dist/agent/components/approval-mode-icons.d.ts.map +1 -0
  7. package/dist/agent/components/composer-add-menu.d.ts +15 -0
  8. package/dist/agent/components/composer-add-menu.d.ts.map +1 -0
  9. package/dist/agent/components/composer-commands.d.ts +37 -0
  10. package/dist/agent/components/composer-commands.d.ts.map +1 -0
  11. package/dist/agent/components/composer-menu.d.ts +18 -15
  12. package/dist/agent/components/composer-menu.d.ts.map +1 -1
  13. package/dist/agent/components/composer-settings.d.ts +34 -0
  14. package/dist/agent/components/composer-settings.d.ts.map +1 -0
  15. package/dist/agent/components/composer.d.ts +10 -3
  16. package/dist/agent/components/composer.d.ts.map +1 -1
  17. package/dist/agent/components/context-chips.d.ts +5 -0
  18. package/dist/agent/components/context-chips.d.ts.map +1 -1
  19. package/dist/agent/components/conversation-panel.d.ts +3 -1
  20. package/dist/agent/components/conversation-panel.d.ts.map +1 -1
  21. package/dist/agent/components/dictation-bar.d.ts +7 -3
  22. package/dist/agent/components/dictation-bar.d.ts.map +1 -1
  23. package/dist/agent/components/model-picker-row.d.ts +1 -3
  24. package/dist/agent/components/model-picker-row.d.ts.map +1 -1
  25. package/dist/agent/components/reasoning-effort-slider.d.ts.map +1 -1
  26. package/dist/agent/components/shared-thread-notice.d.ts +4 -2
  27. package/dist/agent/components/shared-thread-notice.d.ts.map +1 -1
  28. package/dist/agent/delegation/use-children.d.ts.map +1 -1
  29. package/dist/agent/hooks/use-agent-conversation.d.ts +2 -0
  30. package/dist/agent/hooks/use-agent-conversation.d.ts.map +1 -1
  31. package/dist/agent/hooks/use-thread-lists.d.ts +8 -0
  32. package/dist/agent/hooks/use-thread-lists.d.ts.map +1 -1
  33. package/dist/agent/i18n/en.d.ts +69 -8
  34. package/dist/agent/i18n/en.d.ts.map +1 -1
  35. package/dist/agent/i18n/fr.d.ts.map +1 -1
  36. package/dist/agent/i18n/index.d.ts +126 -12
  37. package/dist/agent/i18n/index.d.ts.map +1 -1
  38. package/dist/agent/model-selection.d.ts +1 -0
  39. package/dist/agent/model-selection.d.ts.map +1 -1
  40. package/dist/agent/run-sounds.d.ts +18 -0
  41. package/dist/agent/run-sounds.d.ts.map +1 -0
  42. package/dist/chunk-6n5pdqp0.js.map +1 -1
  43. package/dist/{chunk-12v6y89k.js → chunk-btky7c9w.js} +11678 -11190
  44. package/dist/{chunk-12v6y89k.js.map → chunk-btky7c9w.js.map} +59 -57
  45. package/dist/{chunk-bpj9mg5c.js → chunk-gq6xek89.js} +1 -1
  46. package/dist/{chunk-bpj9mg5c.js.map → chunk-gq6xek89.js.map} +1 -1
  47. package/dist/{chunk-hzy2g13h.js → chunk-hdbmj6f0.js} +1 -1
  48. package/dist/{chunk-hzy2g13h.js.map → chunk-hdbmj6f0.js.map} +1 -1
  49. package/dist/chunk-md3p7qdt.js.map +1 -1
  50. package/dist/{chunk-2a69ge8h.js → chunk-pkcm8rn8.js} +1 -1
  51. package/dist/{chunk-2a69ge8h.js.map → chunk-pkcm8rn8.js.map} +1 -1
  52. package/dist/chunk-yvhzn4ye.js.map +1 -1
  53. package/dist/codegen.d.ts.map +1 -1
  54. package/dist/createCustomApp.d.ts.map +1 -1
  55. package/dist/frame-origins.d.ts +10 -0
  56. package/dist/frame-origins.d.ts.map +1 -0
  57. package/dist/index.d.ts +2 -1
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +6 -6
  60. package/dist/index.js.map +3 -3
  61. package/dist/pages/settings/messages.d.ts +16 -0
  62. package/dist/pages/settings/messages.d.ts.map +1 -1
  63. package/dist/pages/settings/personal.d.ts +2 -2
  64. package/dist/pages/settings/personal.d.ts.map +1 -1
  65. package/dist/pages.js +49 -3
  66. package/dist/pages.js.map +4 -4
  67. package/dist/server.js +97 -22
  68. package/dist/server.js.map +6 -5
  69. package/package.json +3 -3
  70. package/src/agent/agent-chat.tsx +6 -1
  71. package/src/agent/agent.css +145 -14
  72. package/src/agent/bash/interpret.ts +41 -5
  73. package/src/agent/components/approval-mode-icons.ts +9 -0
  74. package/src/agent/components/composer-add-menu.tsx +126 -0
  75. package/src/agent/components/composer-commands.tsx +165 -0
  76. package/src/agent/components/composer-menu.tsx +33 -46
  77. package/src/agent/components/composer-settings.tsx +437 -0
  78. package/src/agent/components/composer.tsx +312 -153
  79. package/src/agent/components/context-chips.tsx +21 -8
  80. package/src/agent/components/conversation-panel.tsx +16 -9
  81. package/src/agent/components/dictation-bar.tsx +28 -23
  82. package/src/agent/components/model-picker-row.tsx +14 -24
  83. package/src/agent/components/reasoning-effort-slider.tsx +14 -10
  84. package/src/agent/components/shared-thread-notice.tsx +7 -2
  85. package/src/agent/components/transcript.tsx +2 -1
  86. package/src/agent/hooks/use-agent-conversation.ts +18 -6
  87. package/src/agent/i18n/en.ts +58 -15
  88. package/src/agent/i18n/fr.ts +77 -13
  89. package/src/agent/model-selection.ts +4 -0
  90. package/src/agent/publish-artifact/publish-artifact-tool-view.tsx +3 -2
  91. package/src/agent/run-sounds.ts +171 -0
  92. package/src/codegen.ts +44 -0
  93. package/src/createCustomApp.ts +53 -26
  94. package/src/frame-origins.ts +61 -0
  95. package/src/index.ts +5 -1
  96. package/src/pages/settings/messages.ts +8 -0
  97. package/src/pages/settings/personal.tsx +60 -3
  98. package/dist/agent/components/approval-mode-chip.d.ts +0 -15
  99. package/dist/agent/components/approval-mode-chip.d.ts.map +0 -1
  100. package/dist/agent/components/auto-model-chip.d.ts +0 -23
  101. package/dist/agent/components/auto-model-chip.d.ts.map +0 -1
  102. package/dist/agent/components/model-controls.d.ts +0 -41
  103. package/dist/agent/components/model-controls.d.ts.map +0 -1
  104. package/src/agent/components/approval-mode-chip.tsx +0 -120
  105. package/src/agent/components/auto-model-chip.tsx +0 -219
  106. package/src/agent/components/model-controls.tsx +0 -238
@@ -70,6 +70,24 @@ export const fr: Translation<AgentMessages> = {
70
70
  dictationTranscribing: "Transcription…",
71
71
  cancelDictation: "Annuler la dictée",
72
72
  finishDictation: "Terminer",
73
+ add: "Ajouter des fichiers et plus",
74
+ mention: "Mentionner un enregistrement",
75
+ commands: "Commandes",
76
+ },
77
+ commands: {
78
+ list: "Commandes",
79
+ auto: "Laisser Auto choisir le modèle",
80
+ model: (name) => `Utiliser ${name}`,
81
+ modes: {
82
+ manual: "Demander avant chaque action",
83
+ "accept-edits": "Autoriser les modifications sans demander",
84
+ auto: "Tout lancer sans demander",
85
+ },
86
+ },
87
+ settings: {
88
+ title: "Modèle et autorisations",
89
+ chip: (summary) => `${summary}. Changer le modèle et les autorisations`,
90
+ permissions: "Autorisations",
73
91
  },
74
92
  files: {
75
93
  spreadsheet: "Feuille de calcul",
@@ -100,15 +118,11 @@ export const fr: Translation<AgentMessages> = {
100
118
  unnamed: "Contexte",
101
119
  },
102
120
  models: {
103
- choose: "Choisir le modèle et l’effort de raisonnement",
104
121
  unavailable: "Modèles indisponibles",
105
122
  defaultModel: "Modèle par défaut",
106
- popover: "Modèle et effort de raisonnement",
107
123
  search: "Rechercher un modèle",
108
124
  list: "Modèles",
109
125
  empty: "Aucun modèle correspondant.",
110
- default: "Par défaut",
111
- defaultSummary: (summary) => `Par défaut · ${summary}`,
112
126
  details: (name) => `Détails sur ${name}`,
113
127
  contextWindow: "Fenêtre de contexte",
114
128
  tokens: (tokens) => count(tokens, "jeton"),
@@ -120,9 +134,8 @@ export const fr: Translation<AgentMessages> = {
120
134
  reasoning: "Raisonnement",
121
135
  via: (name) => `Via ${name}`,
122
136
  title: "Modèle",
123
- chip: (name) => `Modèle : ${name}. Le changer`,
124
137
  auto: "Auto",
125
- autoRouting: "Choisit le bon modèle pour chaque message",
138
+ autoRouting: "Le meilleur modèle pour chaque message",
126
139
  autoStandard: (name) => `Sixb utilise ${name}`,
127
140
  },
128
141
  reasoning: {
@@ -573,6 +586,57 @@ export const fr: Translation<AgentMessages> = {
573
586
  title: "Exécution de workflow vérifiée",
574
587
  running: "Vérification d’une exécution de workflow",
575
588
  },
589
+ listDatasets: {
590
+ title: "Jeux de données listés",
591
+ running: "Récupération des jeux de données",
592
+ },
593
+ inspectDataset: {
594
+ title: (dataset) =>
595
+ dataset ? `Jeu de données ${quoted(dataset)} examiné` : "Jeu de données examiné",
596
+ running: (dataset) =>
597
+ dataset ? `Examen du jeu de données ${quoted(dataset)}` : "Examen d’un jeu de données",
598
+ },
599
+ datasetVersions: {
600
+ title: (dataset) =>
601
+ dataset ? `Versions de ${quoted(dataset)} listées` : "Versions d’un jeu de données listées",
602
+ running: (dataset) =>
603
+ dataset
604
+ ? `Récupération des versions de ${quoted(dataset)}`
605
+ : "Récupération des versions d’un jeu de données",
606
+ },
607
+ datasetRows: {
608
+ title: (dataset) =>
609
+ dataset ? `Lignes de ${quoted(dataset)} lues` : "Lignes d’un jeu de données lues",
610
+ running: (dataset) =>
611
+ dataset
612
+ ? `Lecture des lignes de ${quoted(dataset)}`
613
+ : "Lecture des lignes d’un jeu de données",
614
+ },
615
+ listSyncs: { title: "Synchronisations listées", running: "Récupération des synchronisations" },
616
+ inspectSync: {
617
+ title: (sync) =>
618
+ sync ? `Synchronisation ${quoted(sync)} examinée` : "Synchronisation examinée",
619
+ running: (sync) =>
620
+ sync ? `Examen de la synchronisation ${quoted(sync)}` : "Examen d’une synchronisation",
621
+ },
622
+ listSyncRuns: {
623
+ title: "Exécutions de synchronisations listées",
624
+ running: "Récupération des exécutions de synchronisations",
625
+ },
626
+ listPipelines: { title: "Pipelines listés", running: "Récupération des pipelines" },
627
+ inspectPipeline: {
628
+ title: (pipeline) => (pipeline ? `Pipeline ${quoted(pipeline)} examiné` : "Pipeline examiné"),
629
+ running: (pipeline) =>
630
+ pipeline ? `Examen du pipeline ${quoted(pipeline)}` : "Examen d’un pipeline",
631
+ },
632
+ listPipelineRuns: {
633
+ title: "Exécutions de pipelines listées",
634
+ running: "Récupération des exécutions de pipelines",
635
+ },
636
+ pipelineRun: {
637
+ title: "Exécution de pipeline vérifiée",
638
+ running: "Vérification d’une exécution de pipeline",
639
+ },
576
640
  upload: { title: "Fichier téléversé", running: "Téléversement d’un fichier" },
577
641
  download: { title: "Fichier téléchargé", running: "Téléchargement d’un fichier" },
578
642
  models: {
@@ -765,6 +829,7 @@ export const fr: Translation<AgentMessages> = {
765
829
  cancel: "Annuler",
766
830
  close: "Fermer",
767
831
  sharedBy: (owner) => `Fil de ${owner}`,
832
+ onComputer: (owner) => `Tourne sur l’ordinateur de ${owner} : vous pouvez le suivre ici`,
768
833
  answering: (name) => `L’agent répond à ${name}…`,
769
834
  continueMine: "Continuer dans mon propre fil",
770
835
  continuing: "Copie…",
@@ -782,22 +847,21 @@ export const fr: Translation<AgentMessages> = {
782
847
  },
783
848
  approvalModes: {
784
849
  title: "Que peut faire l’agent sans demander ?",
785
- chip: (mode) => `Autorisations : ${mode}. Les changer`,
786
850
  changed: (mode) => `Autorisations : ${mode}`,
787
851
  shortcut: "Maj+Tab dans un message vide passe au mode suivant",
788
852
  modes: {
789
853
  manual: {
790
- label: "Manuel",
791
- description: "Demande avant chaque action ou workflow que l’agent lance",
854
+ label: "Demander d’abord",
855
+ description: "Vous demande avant chaque action ou workflow.",
792
856
  },
793
857
  "accept-edits": {
794
- label: "Modifications acceptées",
858
+ label: "Modifications permises",
795
859
  description:
796
- "Modifie vos données sans demander. Demande avant de contacter d’autres systèmes ou de lancer un workflow",
860
+ "Modifie vos données de lui-même. Demande avant de contacter d’autres systèmes ou de lancer un workflow.",
797
861
  },
798
862
  auto: {
799
- label: "Auto",
800
- description: "Lance toutes les actions et tous les workflows sans demander",
863
+ label: "Accès complet",
864
+ description: "Lance toutes les actions et tous les workflows sans demander.",
801
865
  },
802
866
  },
803
867
  saveFailed: "Impossible de changer ce que l’agent peut faire. Réessayez.",
@@ -101,3 +101,7 @@ export function preferenceWithoutReasoning(
101
101
  const model = selection.request?.model
102
102
  return model ? { model } : null
103
103
  }
104
+
105
+ export function sameModel(left: LanguageModel, right: LanguageModel | undefined): boolean {
106
+ return left.provider === right?.provider && left.modelId === right.modelId
107
+ }
@@ -56,7 +56,8 @@ export function PublishArtifactToolView({ tool }: { tool: NormalizedTool }) {
56
56
  )
57
57
  }
58
58
 
59
- /** The refusal the Agent received, without the worker's prefix. */
59
+ /** The refusal the Agent received, without the harness's prefix. */
60
60
  function refusal(errorText: string): string {
61
- return errorText.replace(/^\[SixbAgentWorker\] publish_artifact(_version)? refused: /, "")
61
+ // [SixbAgentWorker] on refusals recorded before the harness had a package of its own.
62
+ return errorText.replace(/^\[SixbAgent(?:Worker)?\] publish_artifact(_version)? refused: /, "")
62
63
  }
@@ -0,0 +1,171 @@
1
+ import { createAgentRunSocket, type ReconnectingSocket } from "@sixb/client"
2
+ import { isActiveAgentRunStatus } from "./run-presentation"
3
+
4
+ /**
5
+ * A sound when a turn the reader started ends while they are away from it: in another tab or app,
6
+ * on another page, or in another conversation. Each run is followed on a socket of its own from the
7
+ * moment this tab starts it, so leaving the conversation does not stop the listening; a reload
8
+ * does.
9
+ */
10
+
11
+ const SOUND_KEY = "sixb:agent-sounds"
12
+
13
+ export const RUN_SOUND_CHOICES = ["off", "chime", "bell", "pop"] as const
14
+ export type RunSoundChoice = (typeof RUN_SOUND_CHOICES)[number]
15
+ export type RunSound = Exclude<RunSoundChoice, "off">
16
+
17
+ /** The sound this browser plays when a turn ends: chime unless the reader chose another. */
18
+ export function readRunSound(): RunSoundChoice {
19
+ try {
20
+ const value = globalThis.localStorage?.getItem(SOUND_KEY)
21
+ return RUN_SOUND_CHOICES.find((choice) => choice === value) ?? "chime"
22
+ } catch {
23
+ return "chime"
24
+ }
25
+ }
26
+
27
+ export function writeRunSound(choice: RunSoundChoice) {
28
+ try {
29
+ globalThis.localStorage?.setItem(SOUND_KEY, choice)
30
+ } catch {
31
+ // Ignore storage errors.
32
+ }
33
+ }
34
+
35
+ /** The turn is over, or one of its calls waits for the reader's decision. */
36
+ export type RunTone = "done" | "waiting"
37
+
38
+ /** One note: when it starts and how long it rings, in seconds, and its pitch in Hz. */
39
+ interface Note {
40
+ readonly frequency: number
41
+ readonly at: number
42
+ readonly length: number
43
+ readonly gain?: number
44
+ /** The pitch it slides to as it fades. */
45
+ readonly glideTo?: number
46
+ }
47
+
48
+ const PEAK_GAIN = 0.12
49
+
50
+ const chime = (frequency: number, at: number): Note => ({ frequency, at, length: 0.35 })
51
+
52
+ // A struck bell: its note, and two quieter overtones that fade sooner.
53
+ const strike = (frequency: number, at: number): readonly Note[] => [
54
+ { frequency, at, length: 1.4, gain: 0.1 },
55
+ { frequency: frequency * 2, at, length: 0.7, gain: 0.035 },
56
+ { frequency: frequency * 3, at, length: 0.4, gain: 0.015 },
57
+ ]
58
+
59
+ const pop = (at: number): Note => ({ frequency: 600, at, length: 0.1, gain: 0.2, glideTo: 300 })
60
+
61
+ // Each sound says the two apart the same way: waiting repeats itself.
62
+ const SOUNDS: Record<RunSound, Record<RunTone, readonly Note[]>> = {
63
+ chime: {
64
+ done: [chime(659.25, 0), chime(987.77, 0.12)],
65
+ waiting: [chime(880, 0), chime(880, 0.12)],
66
+ },
67
+ bell: {
68
+ done: strike(1046.5, 0),
69
+ waiting: [...strike(783.99, 0), ...strike(783.99, 0.28)],
70
+ },
71
+ pop: {
72
+ done: [pop(0)],
73
+ waiting: [pop(0), pop(0.13)],
74
+ },
75
+ }
76
+
77
+ let audio: AudioContext | null = null
78
+
79
+ // A browser lets a page start audio only once the reader has interacted with it, so the context is
80
+ // made as the reader starts a turn, and kept.
81
+ function audioContext(): AudioContext | null {
82
+ if (typeof AudioContext === "undefined") return null
83
+ audio ??= new AudioContext()
84
+ // A page the browser does not let play stays silent.
85
+ if (audio.state === "suspended") audio.resume().catch(() => {})
86
+ return audio
87
+ }
88
+
89
+ export function playRunSound(sound: RunSound, tone: RunTone) {
90
+ const context = audioContext()
91
+ if (!context) return
92
+
93
+ const start = context.currentTime + 0.02
94
+ for (const note of SOUNDS[sound][tone]) {
95
+ const at = start + note.at
96
+ const end = at + note.length
97
+ const oscillator = context.createOscillator()
98
+ const gain = context.createGain()
99
+ oscillator.frequency.setValueAtTime(note.frequency, at)
100
+ if (note.glideTo) oscillator.frequency.exponentialRampToValueAtTime(note.glideTo, end)
101
+ gain.gain.setValueAtTime(0, at)
102
+ gain.gain.linearRampToValueAtTime(note.gain ?? PEAK_GAIN, at + 0.01)
103
+ gain.gain.exponentialRampToValueAtTime(0.0001, end)
104
+ oscillator.connect(gain).connect(context.destination)
105
+ oscillator.start(at)
106
+ oscillator.stop(end)
107
+ }
108
+ }
109
+
110
+ const followed = new Map<string, ReconnectingSocket>()
111
+
112
+ /**
113
+ * Follow a run this tab just started until it ends, and play its tone unless the reader watched it
114
+ * end. Call it where the turn starts, close to the reader's click or key.
115
+ */
116
+ export function watchRun(run: { readonly id: string; readonly threadId: string }) {
117
+ if (typeof window === "undefined" || followed.has(run.id) || readRunSound() === "off") return
118
+ audioContext()
119
+
120
+ // Closing the socket drops what it still receives, so a run ends once.
121
+ const end = (ended: { readonly status: string; readonly finishReason?: string }) => {
122
+ followed.get(run.id)?.close()
123
+ followed.delete(run.id)
124
+
125
+ // The sound chosen now, though the reader may have changed it while the turn ran.
126
+ const sound = readRunSound()
127
+ const tone = runTone(ended)
128
+ if (tone && sound !== "off" && !watching(run.threadId)) playRunSound(sound, tone)
129
+ }
130
+
131
+ followed.set(
132
+ run.id,
133
+ createAgentRunSocket({
134
+ runId: run.id,
135
+ onEvent: (event) => {
136
+ if (event.type === "agent.run.finished") end(event)
137
+ },
138
+ // A run that ended before the socket subscribed shows it in its snapshot.
139
+ onRunSnapshot: (snapshot) => {
140
+ if (!isActiveAgentRunStatus(snapshot.status)) end(snapshot)
141
+ },
142
+ })
143
+ )
144
+ }
145
+
146
+ // A stopped turn makes no sound: whoever stopped it knows. A failed one is over all the same.
147
+ function runTone(ended: {
148
+ readonly status: string
149
+ readonly finishReason?: string
150
+ }): RunTone | null {
151
+ if (ended.status === "cancelled") return null
152
+ return ended.status === "succeeded" && ended.finishReason === "awaiting_approval"
153
+ ? "waiting"
154
+ : "done"
155
+ }
156
+
157
+ /**
158
+ * Whether the reader sees the conversation now: this tab in front and focused, and a transcript of
159
+ * it on screen. Its middle is hit-tested, so a collapsed panel, an inert one or one covered by
160
+ * another view does not count.
161
+ */
162
+ function watching(threadId: string): boolean {
163
+ if (document.visibilityState !== "visible" || !document.hasFocus()) return false
164
+ for (const element of document.querySelectorAll<HTMLElement>("[data-agent-thread]")) {
165
+ if (element.dataset.agentThread !== threadId) continue
166
+ const rect = element.getBoundingClientRect()
167
+ const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2)
168
+ if (hit && element.contains(hit)) return true
169
+ }
170
+ return false
171
+ }
package/src/codegen.ts CHANGED
@@ -717,6 +717,49 @@ function InternalLinkInterceptor({ basename }: { readonly basename?: string }) {
717
717
  return null
718
718
  }
719
719
 
720
+ // The page frames only the API and the sites SIXB_APP_FRAME_ORIGINS lists. The browser logs a
721
+ // refused <iframe> without saying where that list lives: name it, once per site. A site counts
722
+ // only when an <iframe> asked for it: an artifact frame that navigates elsewhere keeps the API's
723
+ // address as its src, and the list is no place for wherever its code tried to go.
724
+ function RefusedFrameReporter() {
725
+ // Subscribed before the browser can report a frame rendered in the same commit.
726
+ React.useLayoutEffect(() => {
727
+ const reported = new Set<string>()
728
+
729
+ function onViolation(event: SecurityPolicyViolationEvent) {
730
+ if (event.effectiveDirective !== "frame-src") return
731
+
732
+ const origin = originOf(event.blockedURI)
733
+ if (!origin || reported.has(origin)) return
734
+
735
+ const frames = Array.from(document.querySelectorAll("iframe"))
736
+ if (!frames.some((frame) => originOf(frame.src) === origin)) return
737
+
738
+ reported.add(origin)
739
+ console.warn(
740
+ "[SixbApp] The app refused to frame " +
741
+ origin +
742
+ ". Add each site a frame loads, redirects included, to SIXB_APP_FRAME_ORIGINS on the " +
743
+ "app server."
744
+ )
745
+ }
746
+
747
+ document.addEventListener("securitypolicyviolation", onViolation)
748
+ return () => document.removeEventListener("securitypolicyviolation", onViolation)
749
+ }, [])
750
+
751
+ return null
752
+ }
753
+
754
+ function originOf(url: string): string | null {
755
+ try {
756
+ const { origin } = new URL(url)
757
+ return origin === "null" ? null : origin
758
+ } catch {
759
+ return null
760
+ }
761
+ }
762
+
720
763
  function pathInsideApp(pathname: string, basename: string | undefined): string {
721
764
  if (
722
765
  basename &&
@@ -987,6 +1030,7 @@ function App({ basename }: StartAppOptions) {
987
1030
  ${sectionsStart}
988
1031
  <BrowserRouter basename={basename}>
989
1032
  <ActivityPageView />
1033
+ <RefusedFrameReporter />
990
1034
  <SharedDocumentLinkInterceptor basename={basename} />
991
1035
  <InternalLinkInterceptor basename={basename} />
992
1036
  {basename ? (
@@ -20,6 +20,7 @@ import {
20
20
  generateRouteManifest,
21
21
  } from "./codegen"
22
22
  import { devReloadResponse } from "./dev-reload"
23
+ import { readAppFrameOrigins } from "./frame-origins"
23
24
  import { collectPublicEnv, renderCustomAppRuntimeScript } from "./runtime"
24
25
  import { type PageRoute, routePatternKey, scanAppRoutes } from "./scanner"
25
26
  import { sectionCatalog } from "./sections/catalog"
@@ -354,6 +355,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
354
355
 
355
356
  async dev(devOptions: CustomAppDevOptions = {}) {
356
357
  const publicEnv = collectPublicEnv()
358
+ const frameOrigins = readAppFrameOrigins(process.env)
357
359
  const withRuntime = (html: string) =>
358
360
  injectRuntimeConfig(html, { apiBaseUrl, authEnabled, publicEnv })
359
361
  const host = devOptions.host ?? "0.0.0.0"
@@ -397,17 +399,20 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
397
399
  authEnabled: false,
398
400
  publicEnv,
399
401
  }),
400
- apiBaseUrl
402
+ apiBaseUrl,
403
+ frameOrigins
401
404
  ),
402
405
  "/": spaHtmlRoute(() => internalOrigin, {
403
406
  shellRoute: privateAppShellRoute,
404
407
  transformHtml: withRuntime,
405
408
  apiBaseUrl,
409
+ frameOrigins,
406
410
  }),
407
411
  "/*": spaHtmlRoute(() => internalOrigin, {
408
412
  shellRoute: privateAppShellRoute,
409
413
  transformHtml: withRuntime,
410
414
  apiBaseUrl,
415
+ frameOrigins,
411
416
  }),
412
417
  },
413
418
  }) as Parameters<typeof Bun.serve>[0]
@@ -577,6 +582,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
577
582
 
578
583
  async start(startOptions: CustomAppStartOptions = {}) {
579
584
  const publicEnv = collectPublicEnv()
585
+ const frameOrigins = readAppFrameOrigins(process.env)
580
586
  const host = startOptions.host ?? "0.0.0.0"
581
587
  const port = startOptions.port ?? 3000
582
588
  const outdir = resolve(rootDir, startOptions.outdir ?? join(".sixb", "dist", "app"))
@@ -629,7 +635,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
629
635
  if (isAssetRequest(url.pathname)) {
630
636
  return notFoundResponse()
631
637
  }
632
- return sharedHtmlResponse(req, sharedIndexHtml, runtimeApiBaseUrl)
638
+ return sharedHtmlResponse(req, sharedIndexHtml, runtimeApiBaseUrl, frameOrigins)
633
639
  }
634
640
 
635
641
  if (isSharedNamespace(url.pathname)) {
@@ -637,7 +643,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
637
643
  }
638
644
 
639
645
  if (url.pathname === "/" || url.pathname === "") {
640
- return htmlResponse(req, indexHtml, runtimeApiBaseUrl)
646
+ return htmlResponse(req, indexHtml, runtimeApiBaseUrl, frameOrigins)
641
647
  }
642
648
 
643
649
  const resolvedPath = resolveStaticPath(outdir, url.pathname)
@@ -648,7 +654,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
648
654
  const directFile = Bun.file(resolvedPath)
649
655
  if (await directFile.exists()) {
650
656
  if (resolvedPath === indexPath) {
651
- return htmlResponse(req, indexHtml, runtimeApiBaseUrl)
657
+ return htmlResponse(req, indexHtml, runtimeApiBaseUrl, frameOrigins)
652
658
  }
653
659
  return staticFileResponse(req, resolvedPath, staticAssetHeaders(url.pathname))
654
660
  }
@@ -660,7 +666,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
660
666
  const htmlFile = Bun.file(`${resolvedPath}.html`)
661
667
  if (await htmlFile.exists()) {
662
668
  if (`${resolvedPath}.html` === indexPath) {
663
- return htmlResponse(req, indexHtml, runtimeApiBaseUrl)
669
+ return htmlResponse(req, indexHtml, runtimeApiBaseUrl, frameOrigins)
664
670
  }
665
671
  return fileResponse(req, htmlFile)
666
672
  }
@@ -670,7 +676,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
670
676
  return fileResponse(req, nestedIndexFile)
671
677
  }
672
678
 
673
- return htmlResponse(req, indexHtml, runtimeApiBaseUrl)
679
+ return htmlResponse(req, indexHtml, runtimeApiBaseUrl, frameOrigins)
674
680
  },
675
681
  })
676
682
 
@@ -885,7 +891,8 @@ function reservedSixbRoutes(): BunServeRoutes {
885
891
 
886
892
  function sharedAppDevRoutes(
887
893
  html: () => string | Promise<string>,
888
- apiBaseUrl: string | undefined
894
+ apiBaseUrl: string | undefined,
895
+ frameOrigins: readonly string[]
889
896
  ): BunServeRoutes {
890
897
  const reject = () => notFoundResponse()
891
898
  const guardedHandler = async (request: Request) => {
@@ -893,7 +900,7 @@ function sharedAppDevRoutes(
893
900
  if (!isSharedAppRoute(pathname) || isAssetRequest(pathname)) {
894
901
  return notFoundResponse()
895
902
  }
896
- return sharedHtmlResponse(request, await html(), apiBaseUrl)
903
+ return sharedHtmlResponse(request, await html(), apiBaseUrl, frameOrigins)
897
904
  }
898
905
 
899
906
  return {
@@ -1061,33 +1068,51 @@ function injectRuntimeConfig(
1061
1068
  return `${script}\n${html}`
1062
1069
  }
1063
1070
 
1064
- function htmlResponse(request: Request, html: string, apiBaseUrl: string | undefined): Response {
1071
+ function htmlResponse(
1072
+ request: Request,
1073
+ html: string,
1074
+ apiBaseUrl: string | undefined,
1075
+ frameOrigins: readonly string[]
1076
+ ): Response {
1065
1077
  return new Response(request.method === "HEAD" ? null : html, {
1066
1078
  headers: {
1067
1079
  "content-type": "text/html; charset=utf-8",
1068
1080
  "cache-control": "no-store",
1069
- "content-security-policy": appContentSecurityPolicy(request, apiBaseUrl),
1081
+ "content-security-policy": appContentSecurityPolicy(request, apiBaseUrl, frameOrigins),
1070
1082
  },
1071
1083
  })
1072
1084
  }
1073
1085
 
1074
1086
  /**
1075
- * The policy of the app's own page: it frames only what the API serves, its artifacts' frames.
1076
- * A page in one reads its queries' rows as the reader; its frame opens no window, and the frame's
1077
- * policy keeps what it loads to its files and a few CDNs. This keeps the frame's navigations on the
1078
- * API's origin too, so a page's code cannot send what it reads to another site in an address.
1087
+ * The policy of the app's own page: it frames what the API serves, its artifacts' frames, and the
1088
+ * sites `SIXB_APP_FRAME_ORIGINS` lists. A page in an artifact frame reads its queries' rows as the
1089
+ * reader; its frame opens no window, and the frame's policy keeps what it loads to its files and a
1090
+ * few CDNs. This keeps the frame's navigations on those origins too, so a page's code cannot send
1091
+ * what it reads to any other site in an address.
1079
1092
  *
1080
1093
  * It is the only directive: what a project's own pages load is theirs, but a frame they embed from
1081
- * another site is refused too.
1094
+ * a site the list leaves out is refused too.
1082
1095
  */
1083
- function appContentSecurityPolicy(request: Request, apiBaseUrl: string | undefined): string {
1084
- return `frame-src ${frameSource(request, apiBaseUrl)}`
1096
+ function appContentSecurityPolicy(
1097
+ request: Request,
1098
+ apiBaseUrl: string | undefined,
1099
+ frameOrigins: readonly string[]
1100
+ ): string {
1101
+ return `frame-src ${frameSources(request, apiBaseUrl, frameOrigins)}`
1085
1102
  }
1086
1103
 
1087
- /** Where an artifact frame comes from: the API's origin, `'self'` when it is the page's own. */
1088
- function frameSource(request: Request, apiBaseUrl: string | undefined): string {
1104
+ /**
1105
+ * Where the page's frames may come from: the API's origin, `'self'` when it is the page's own, then
1106
+ * the listed sites.
1107
+ */
1108
+ function frameSources(
1109
+ request: Request,
1110
+ apiBaseUrl: string | undefined,
1111
+ frameOrigins: readonly string[]
1112
+ ): string {
1089
1113
  const { requestOrigin, apiOrigin } = resolveOrigins(request, apiBaseUrl)
1090
- return apiOrigin === requestOrigin ? "'self'" : apiOrigin
1114
+ const api = apiOrigin === requestOrigin ? "'self'" : apiOrigin
1115
+ return [api, ...frameOrigins.filter((origin) => origin !== apiOrigin)].join(" ")
1091
1116
  }
1092
1117
 
1093
1118
  function resolveOrigins(
@@ -1106,9 +1131,10 @@ function resolveOrigins(
1106
1131
  function sharedHtmlResponse(
1107
1132
  request: Request,
1108
1133
  html: string,
1109
- apiBaseUrl: string | undefined
1134
+ apiBaseUrl: string | undefined,
1135
+ frameOrigins: readonly string[]
1110
1136
  ): Response {
1111
- const secured = secureSharedHtml(html, request, { apiBaseUrl })
1137
+ const secured = secureSharedHtml(html, request, { apiBaseUrl, frameOrigins })
1112
1138
  return new Response(request.method === "HEAD" ? null : secured.html, {
1113
1139
  headers: {
1114
1140
  "content-type": "text/html; charset=utf-8",
@@ -1120,7 +1146,7 @@ function sharedHtmlResponse(
1120
1146
  function secureSharedHtml(
1121
1147
  html: string,
1122
1148
  request: Request,
1123
- options: { readonly apiBaseUrl?: string }
1149
+ options: { readonly apiBaseUrl?: string; readonly frameOrigins: readonly string[] }
1124
1150
  ): { readonly html: string; readonly headers: Record<string, string> } {
1125
1151
  const nonce = randomBytes(18).toString("base64url")
1126
1152
  const { requestOrigin, apiOrigin } = resolveOrigins(request, options.apiBaseUrl)
@@ -1143,7 +1169,7 @@ function secureSharedHtml(
1143
1169
  `media-src ${fileSources.join(" ")}`,
1144
1170
  "font-src 'self' data: https:",
1145
1171
  `connect-src ${connectSources.join(" ")}`,
1146
- `frame-src ${frameSource(request, options.apiBaseUrl)}`,
1172
+ `frame-src ${frameSources(request, options.apiBaseUrl, options.frameOrigins)}`,
1147
1173
  "manifest-src 'none'",
1148
1174
  ].join("; ")
1149
1175
 
@@ -1324,7 +1350,8 @@ function spaHtmlRoute(
1324
1350
  readonly shellRoute?: string
1325
1351
  readonly transformHtml?: (html: string) => string
1326
1352
  readonly apiBaseUrl?: string
1327
- } = {}
1353
+ readonly frameOrigins: readonly string[]
1354
+ }
1328
1355
  ): BunServeRoute {
1329
1356
  return getHeadRoute(async (request) => {
1330
1357
  const publicUrl = new URL(request.url)
@@ -1359,7 +1386,7 @@ function spaHtmlRoute(
1359
1386
  responseHeaders.delete("etag")
1360
1387
  responseHeaders.set(
1361
1388
  "content-security-policy",
1362
- appContentSecurityPolicy(request, options.apiBaseUrl)
1389
+ appContentSecurityPolicy(request, options.apiBaseUrl, options.frameOrigins)
1363
1390
  )
1364
1391
  if (request.method === "HEAD") {
1365
1392
  return new Response(null, {
@@ -0,0 +1,61 @@
1
+ const APP_FRAME_ORIGINS_ENV = "SIXB_APP_FRAME_ORIGINS"
2
+
3
+ // A CSP host: labels of letters, digits and hyphens. `URL` keeps `*`, `;` and quotes in a host, and
4
+ // any of them would rewrite the policy instead of naming a site.
5
+ const CSP_HOST = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/
6
+
7
+ /**
8
+ * The sites besides the API that the app's pages may show in an `<iframe>`, from a comma-separated
9
+ * list such as `https://www.youtube-nocookie.com,https://contoso.sharepoint.com`.
10
+ *
11
+ * They join the `frame-src` that keeps artifact frames on the API's origin, and a frame may navigate
12
+ * itself to any site the policy allows: an artifact page could send what it reads to a site listed
13
+ * here. Each entry is therefore one exact origin, never a wildcard, a scheme, or a keyword.
14
+ */
15
+ export function readAppFrameOrigins(
16
+ env: Readonly<Record<string, string | undefined>>
17
+ ): readonly string[] {
18
+ const entries = (env[APP_FRAME_ORIGINS_ENV] ?? "")
19
+ .split(",")
20
+ .map((entry) => entry.trim())
21
+ .filter((entry) => entry !== "")
22
+
23
+ return [...new Set(entries.map(frameOrigin))]
24
+ }
25
+
26
+ function frameOrigin(entry: string): string {
27
+ if (entry.includes("*")) {
28
+ throw new Error(
29
+ `[SixbCustomApp] ${APP_FRAME_ORIGINS_ENV}: '${entry}' is a wildcard. List each site, such as ` +
30
+ "https://contoso.sharepoint.com: an artifact's frame can navigate to any site this " +
31
+ "variable allows."
32
+ )
33
+ }
34
+
35
+ let url: URL
36
+ try {
37
+ url = new URL(entry)
38
+ } catch {
39
+ throw notAnOrigin(entry)
40
+ }
41
+
42
+ const exact =
43
+ (url.protocol === "https:" || url.protocol === "http:") &&
44
+ CSP_HOST.test(url.hostname) &&
45
+ !url.username &&
46
+ !url.password &&
47
+ url.pathname === "/" &&
48
+ !url.search &&
49
+ !url.hash
50
+
51
+ if (!exact) throw notAnOrigin(entry)
52
+
53
+ return url.origin
54
+ }
55
+
56
+ function notAnOrigin(entry: string): Error {
57
+ return new Error(
58
+ `[SixbCustomApp] ${APP_FRAME_ORIGINS_ENV}: '${entry}' is not an origin. Give the scheme, host ` +
59
+ "and optional port of each site, such as https://contoso.sharepoint.com."
60
+ )
61
+ }