datasette-apps 0.1a0__tar.gz

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 (47) hide show
  1. datasette_apps-0.1a0/LICENSE +201 -0
  2. datasette_apps-0.1a0/PKG-INFO +139 -0
  3. datasette_apps-0.1a0/README.md +122 -0
  4. datasette_apps-0.1a0/datasette_apps/__init__.py +108 -0
  5. datasette_apps-0.1a0/datasette_apps/csp.py +72 -0
  6. datasette_apps-0.1a0/datasette_apps/data_access.py +109 -0
  7. datasette_apps-0.1a0/datasette_apps/db.py +357 -0
  8. datasette_apps-0.1a0/datasette_apps/ids.py +33 -0
  9. datasette_apps-0.1a0/datasette_apps/permissions.py +124 -0
  10. datasette_apps-0.1a0/datasette_apps/prompt.py +103 -0
  11. datasette_apps-0.1a0/datasette_apps/registry.py +1023 -0
  12. datasette_apps-0.1a0/datasette_apps/rendering.py +581 -0
  13. datasette_apps-0.1a0/datasette_apps/static/datasette-apps.css +860 -0
  14. datasette_apps-0.1a0/datasette_apps/templates/_app_crumbs.html +17 -0
  15. datasette_apps-0.1a0/datasette_apps/templates/_llm_prompt.html +259 -0
  16. datasette_apps-0.1a0/datasette_apps/templates/_stored_query_picker.html +192 -0
  17. datasette_apps-0.1a0/datasette_apps/templates/app_create.html +425 -0
  18. datasette_apps-0.1a0/datasette_apps/templates/app_delete.html +22 -0
  19. datasette_apps-0.1a0/datasette_apps/templates/app_edit.html +172 -0
  20. datasette_apps-0.1a0/datasette_apps/templates/app_list.html +50 -0
  21. datasette_apps-0.1a0/datasette_apps/templates/app_revision.html +107 -0
  22. datasette_apps-0.1a0/datasette_apps/templates/app_view.html +40 -0
  23. datasette_apps-0.1a0/datasette_apps/utils.py +2 -0
  24. datasette_apps-0.1a0/datasette_apps/views.py +645 -0
  25. datasette_apps-0.1a0/datasette_apps.egg-info/PKG-INFO +139 -0
  26. datasette_apps-0.1a0/datasette_apps.egg-info/SOURCES.txt +45 -0
  27. datasette_apps-0.1a0/datasette_apps.egg-info/dependency_links.txt +1 -0
  28. datasette_apps-0.1a0/datasette_apps.egg-info/entry_points.txt +2 -0
  29. datasette_apps-0.1a0/datasette_apps.egg-info/requires.txt +1 -0
  30. datasette_apps-0.1a0/datasette_apps.egg-info/top_level.txt +1 -0
  31. datasette_apps-0.1a0/pyproject.toml +45 -0
  32. datasette_apps-0.1a0/setup.cfg +4 -0
  33. datasette_apps-0.1a0/tests/test_apps.py +11 -0
  34. datasette_apps-0.1a0/tests/test_catalog_pagination.py +32 -0
  35. datasette_apps-0.1a0/tests/test_csp.py +138 -0
  36. datasette_apps-0.1a0/tests/test_data_access.py +292 -0
  37. datasette_apps-0.1a0/tests/test_edit_controls.py +286 -0
  38. datasette_apps-0.1a0/tests/test_jump.py +77 -0
  39. datasette_apps-0.1a0/tests/test_llm_prompt.py +165 -0
  40. datasette_apps-0.1a0/tests/test_menu_links.py +22 -0
  41. datasette_apps-0.1a0/tests/test_permissions.py +256 -0
  42. datasette_apps-0.1a0/tests/test_pins_homepage.py +114 -0
  43. datasette_apps-0.1a0/tests/test_playwright.py +619 -0
  44. datasette_apps-0.1a0/tests/test_registry.py +688 -0
  45. datasette_apps-0.1a0/tests/test_routes.py +343 -0
  46. datasette_apps-0.1a0/tests/test_srcdoc_injection.py +248 -0
  47. datasette_apps-0.1a0/tests/test_templates.py +155 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.4
2
+ Name: datasette-apps
3
+ Version: 0.1a0
4
+ Summary: Create apps that live inside Datasette
5
+ Author: Simon Willison
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/datasette/datasette-apps
8
+ Project-URL: Changelog, https://github.com/datasette/datasette-apps/releases
9
+ Project-URL: Issues, https://github.com/datasette/datasette-apps/issues
10
+ Project-URL: CI, https://github.com/datasette/datasette-apps/actions
11
+ Classifier: Framework :: Datasette
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: datasette>=1.0a31
16
+ Dynamic: license-file
17
+
18
+ # datasette-apps
19
+
20
+ [![PyPI](https://img.shields.io/pypi/v/datasette-apps.svg)](https://pypi.org/project/datasette-apps/)
21
+ [![Changelog](https://img.shields.io/github/v/release/datasette/datasette-apps?include_prereleases&label=changelog)](https://github.com/datasette/datasette-apps/releases)
22
+ [![Tests](https://github.com/datasette/datasette-apps/actions/workflows/test.yml/badge.svg)](https://github.com/datasette/datasette-apps/actions/workflows/test.yml)
23
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/datasette/datasette-apps/blob/main/LICENSE)
24
+
25
+ Create apps that live inside Datasette
26
+
27
+ ## Installation
28
+
29
+ Install this plugin in the same environment as Datasette.
30
+ ```bash
31
+ datasette install datasette-apps
32
+ ```
33
+ ## Usage
34
+
35
+ This plugin introduces a new interface at `/-/apps` for browsing and searching available apps.
36
+
37
+ There are two types of app:
38
+
39
+ - HTML and JavaScript apps managed by this plugin, which run in a sandbox that limits them to approved Datasette data access and blocks communication with external sites unless those hosts have been explicitly allowed.
40
+ - Apps provided by other plugins that are written in Python and HTML/JavaScript which are unrestricted but can do more things
41
+
42
+ This plugin allows you to create and modify HTML apps, and provides a plugin hook to enable other plugins to add their own Python apps to the system.
43
+
44
+ - `/-/apps` lets you browse available apps
45
+ - `/-/apps/ULID` to interact with a full screen HTML app
46
+ - `/-/apps/create` for creating a new app
47
+ - `/-/apps/ULID/edit` to edit an existing app
48
+
49
+ Signed-in users get an "Apps" link in Datasette's top-right menu.
50
+
51
+ HTML apps managed by this plugin use lowercase monotonic ULIDs as their IDs and track every edit as a new row in `app_revisions`.
52
+
53
+ ### Sandboxed apps
54
+
55
+ Stored apps are rendered inside a sandboxed iframe. The plugin injects a Content Security Policy into the iframe `srcdoc`.
56
+
57
+ Direct network access is blocked unless the app has exact `https://` origins configured. Those same origins are allowed for remote images, external script tags, and external stylesheet links/style elements. Localhost origins are never allowed. Local file previews using `data:` and `blob:` image URLs are allowed.
58
+
59
+ The iframe bridge reports JavaScript errors, unhandled promise rejections, CSP violations, failed resources, fetch failures, `console.error()` calls, and failed Datasette data queries back to the parent page. The app page shows these in a small expandable error panel above the iframe.
60
+
61
+ The bridge also replaces `history.replaceState()`, `history.pushState()`, `history.back()`, `history.forward()`, and `history.go()` with no-op functions inside the sandboxed iframe, avoiding browser errors from apps that try to manage URL state.
62
+
63
+ ### Data access
64
+
65
+ Stored apps can query Datasette data using the injected `datasette.query(database, sql, params)` helper.
66
+
67
+ They can also run allow-listed stored queries using `datasette.storedQuery(database, query, params)`. The iframe sends those requests to the parent page with `postMessage`, and the parent page forwards them to an app-scoped query endpoint.
68
+
69
+ Apps have allow-lists configured on the edit page. If the requested database or stored query is allowed, the request is forwarded to Datasette's own JSON APIs using the current actor, so Datasette's normal SQL and query permissions still apply.
70
+
71
+ Failed stored-query attempts, including attempts to call a query that is not allow-listed or that the current actor cannot run, are reported in the app page error panel.
72
+
73
+ Stored query access is configured using a picker on the create and edit pages. The picker searches Datasette's `/-/queries.json?q=search-term` API and stores selected queries as `database-name/query-name` strings. Removing a query uses the `x` button next to that selected query. Additions and removals are not applied until the page is saved.
74
+
75
+ ### Permissions
76
+
77
+ The plugin registers Datasette permissions for `create-app`, `view-app`, `edit-app`, `delete-app`, and `manage-app-access`. Stored app owners can always view, edit, delete, and manage their own apps. Apps marked private are visible only to their owner, even if other users have broad `view-app` permission grants.
78
+
79
+ Deleting a stored app hides it from the catalog and disables access to its pages and query API. Its `app_revisions` rows remain in the database so a database administrator can recover it if needed.
80
+
81
+ Apps that are not private can be viewed by actors with the `view-app` permission. To let all signed-in users view all non-private apps, configure:
82
+
83
+ ```yaml
84
+ permissions:
85
+ view-app:
86
+ id: "*"
87
+ ```
88
+
89
+ External apps registered by plugins are not private by default, so they also require `view-app` permission unless the registering plugin supplies its own permission rules.
90
+
91
+ Signed-in users can pin apps from the catalog and from individual stored app pages. Pinned apps appear first on `/-/apps`, and the three most recently used pinned apps are shown on the Datasette homepage using `top_homepage()`.
92
+
93
+ The `/-/apps` catalog is searchable and paginated.
94
+
95
+ ### App authoring
96
+
97
+ The create and edit pages include a copyable prompt for an LLM. The prompt is assembled in the browser from the current form state, so unsaved changes to selected databases, stored queries, and network origins are reflected immediately. It explains the sandbox, the `datasette.query()` and `datasette.storedQuery()` bridges, CSP restrictions, the current schema summary, and only the stored queries selected for that app.
98
+
99
+ The create and edit pages use Datasette's existing bundled CodeMirror editor for the HTML source textarea.
100
+
101
+ The edit page includes a private checkbox, SQL query database access, stored query access, and allowed network origins.
102
+
103
+ Plugins can add their own apps to the central catalog during startup:
104
+
105
+ ```python
106
+ from datasette import hookimpl
107
+ from datasette_apps import Registry
108
+
109
+
110
+ @hookimpl
111
+ async def startup(datasette):
112
+ await Registry(datasette).add_app(
113
+ id="myplugin:example",
114
+ name="Example plugin app",
115
+ description="A plugin-owned app that appears in /-/apps",
116
+ path="/-/myplugin-example",
117
+ source="myplugin",
118
+ )
119
+ ```
120
+
121
+ Plugins can remove a single external app from the catalog by ID:
122
+
123
+ ```python
124
+ await Registry(datasette).remove_app("myplugin:example")
125
+ ```
126
+
127
+ ## Development
128
+
129
+ To set up this plugin locally, first checkout the code. You can confirm it is available like this:
130
+ ```bash
131
+ cd datasette-apps
132
+ # Confirm the plugin is visible
133
+ uv run datasette plugins
134
+ ```
135
+
136
+ To run the tests:
137
+ ```bash
138
+ uv run pytest
139
+ ```
@@ -0,0 +1,122 @@
1
+ # datasette-apps
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/datasette-apps.svg)](https://pypi.org/project/datasette-apps/)
4
+ [![Changelog](https://img.shields.io/github/v/release/datasette/datasette-apps?include_prereleases&label=changelog)](https://github.com/datasette/datasette-apps/releases)
5
+ [![Tests](https://github.com/datasette/datasette-apps/actions/workflows/test.yml/badge.svg)](https://github.com/datasette/datasette-apps/actions/workflows/test.yml)
6
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/datasette/datasette-apps/blob/main/LICENSE)
7
+
8
+ Create apps that live inside Datasette
9
+
10
+ ## Installation
11
+
12
+ Install this plugin in the same environment as Datasette.
13
+ ```bash
14
+ datasette install datasette-apps
15
+ ```
16
+ ## Usage
17
+
18
+ This plugin introduces a new interface at `/-/apps` for browsing and searching available apps.
19
+
20
+ There are two types of app:
21
+
22
+ - HTML and JavaScript apps managed by this plugin, which run in a sandbox that limits them to approved Datasette data access and blocks communication with external sites unless those hosts have been explicitly allowed.
23
+ - Apps provided by other plugins that are written in Python and HTML/JavaScript which are unrestricted but can do more things
24
+
25
+ This plugin allows you to create and modify HTML apps, and provides a plugin hook to enable other plugins to add their own Python apps to the system.
26
+
27
+ - `/-/apps` lets you browse available apps
28
+ - `/-/apps/ULID` to interact with a full screen HTML app
29
+ - `/-/apps/create` for creating a new app
30
+ - `/-/apps/ULID/edit` to edit an existing app
31
+
32
+ Signed-in users get an "Apps" link in Datasette's top-right menu.
33
+
34
+ HTML apps managed by this plugin use lowercase monotonic ULIDs as their IDs and track every edit as a new row in `app_revisions`.
35
+
36
+ ### Sandboxed apps
37
+
38
+ Stored apps are rendered inside a sandboxed iframe. The plugin injects a Content Security Policy into the iframe `srcdoc`.
39
+
40
+ Direct network access is blocked unless the app has exact `https://` origins configured. Those same origins are allowed for remote images, external script tags, and external stylesheet links/style elements. Localhost origins are never allowed. Local file previews using `data:` and `blob:` image URLs are allowed.
41
+
42
+ The iframe bridge reports JavaScript errors, unhandled promise rejections, CSP violations, failed resources, fetch failures, `console.error()` calls, and failed Datasette data queries back to the parent page. The app page shows these in a small expandable error panel above the iframe.
43
+
44
+ The bridge also replaces `history.replaceState()`, `history.pushState()`, `history.back()`, `history.forward()`, and `history.go()` with no-op functions inside the sandboxed iframe, avoiding browser errors from apps that try to manage URL state.
45
+
46
+ ### Data access
47
+
48
+ Stored apps can query Datasette data using the injected `datasette.query(database, sql, params)` helper.
49
+
50
+ They can also run allow-listed stored queries using `datasette.storedQuery(database, query, params)`. The iframe sends those requests to the parent page with `postMessage`, and the parent page forwards them to an app-scoped query endpoint.
51
+
52
+ Apps have allow-lists configured on the edit page. If the requested database or stored query is allowed, the request is forwarded to Datasette's own JSON APIs using the current actor, so Datasette's normal SQL and query permissions still apply.
53
+
54
+ Failed stored-query attempts, including attempts to call a query that is not allow-listed or that the current actor cannot run, are reported in the app page error panel.
55
+
56
+ Stored query access is configured using a picker on the create and edit pages. The picker searches Datasette's `/-/queries.json?q=search-term` API and stores selected queries as `database-name/query-name` strings. Removing a query uses the `x` button next to that selected query. Additions and removals are not applied until the page is saved.
57
+
58
+ ### Permissions
59
+
60
+ The plugin registers Datasette permissions for `create-app`, `view-app`, `edit-app`, `delete-app`, and `manage-app-access`. Stored app owners can always view, edit, delete, and manage their own apps. Apps marked private are visible only to their owner, even if other users have broad `view-app` permission grants.
61
+
62
+ Deleting a stored app hides it from the catalog and disables access to its pages and query API. Its `app_revisions` rows remain in the database so a database administrator can recover it if needed.
63
+
64
+ Apps that are not private can be viewed by actors with the `view-app` permission. To let all signed-in users view all non-private apps, configure:
65
+
66
+ ```yaml
67
+ permissions:
68
+ view-app:
69
+ id: "*"
70
+ ```
71
+
72
+ External apps registered by plugins are not private by default, so they also require `view-app` permission unless the registering plugin supplies its own permission rules.
73
+
74
+ Signed-in users can pin apps from the catalog and from individual stored app pages. Pinned apps appear first on `/-/apps`, and the three most recently used pinned apps are shown on the Datasette homepage using `top_homepage()`.
75
+
76
+ The `/-/apps` catalog is searchable and paginated.
77
+
78
+ ### App authoring
79
+
80
+ The create and edit pages include a copyable prompt for an LLM. The prompt is assembled in the browser from the current form state, so unsaved changes to selected databases, stored queries, and network origins are reflected immediately. It explains the sandbox, the `datasette.query()` and `datasette.storedQuery()` bridges, CSP restrictions, the current schema summary, and only the stored queries selected for that app.
81
+
82
+ The create and edit pages use Datasette's existing bundled CodeMirror editor for the HTML source textarea.
83
+
84
+ The edit page includes a private checkbox, SQL query database access, stored query access, and allowed network origins.
85
+
86
+ Plugins can add their own apps to the central catalog during startup:
87
+
88
+ ```python
89
+ from datasette import hookimpl
90
+ from datasette_apps import Registry
91
+
92
+
93
+ @hookimpl
94
+ async def startup(datasette):
95
+ await Registry(datasette).add_app(
96
+ id="myplugin:example",
97
+ name="Example plugin app",
98
+ description="A plugin-owned app that appears in /-/apps",
99
+ path="/-/myplugin-example",
100
+ source="myplugin",
101
+ )
102
+ ```
103
+
104
+ Plugins can remove a single external app from the catalog by ID:
105
+
106
+ ```python
107
+ await Registry(datasette).remove_app("myplugin:example")
108
+ ```
109
+
110
+ ## Development
111
+
112
+ To set up this plugin locally, first checkout the code. You can confirm it is available like this:
113
+ ```bash
114
+ cd datasette-apps
115
+ # Confirm the plugin is visible
116
+ uv run datasette plugins
117
+ ```
118
+
119
+ To run the tests:
120
+ ```bash
121
+ uv run pytest
122
+ ```
@@ -0,0 +1,108 @@
1
+ from datasette import hookimpl
2
+ from datasette.jump import JumpSQL
3
+
4
+ from .permissions import app_permission_sql, register_app_actions
5
+ from .registry import Registry
6
+ from .views import (
7
+ app_json,
8
+ app_query,
9
+ app_revision,
10
+ apps_index,
11
+ create_app,
12
+ delete_app,
13
+ edit_app,
14
+ launch_app,
15
+ pin_app,
16
+ top_homepage_html,
17
+ unpin_app,
18
+ view_app,
19
+ )
20
+
21
+ __all__ = ["Registry"]
22
+
23
+
24
+ @hookimpl
25
+ def register_routes():
26
+ return [
27
+ (r"^/-/apps$", apps_index),
28
+ (r"^/-/apps/create$", create_app),
29
+ (r"^/-/apps/(?P<id>[^/]+)\.json$", app_json),
30
+ (r"^/-/apps/(?P<id>[^/]+)/revisions/(?P<version>\d+)$", app_revision),
31
+ (r"^/-/apps/(?P<id>[^/]+)/edit$", edit_app),
32
+ (r"^/-/apps/(?P<id>[^/]+)/delete$", delete_app),
33
+ (r"^/-/apps/(?P<id>[^/]+)/pin$", pin_app),
34
+ (r"^/-/apps/(?P<id>[^/]+)/unpin$", unpin_app),
35
+ (r"^/-/apps/(?P<id>[^/]+)/launch$", launch_app),
36
+ (r"^/-/apps/(?P<id>[^/]+)/query$", app_query),
37
+ (r"^/-/apps/(?P<id>[^/]+)$", view_app),
38
+ ]
39
+
40
+
41
+ @hookimpl
42
+ def register_actions(datasette):
43
+ return register_app_actions()
44
+
45
+
46
+ @hookimpl
47
+ def permission_resources_sql(datasette, actor, action):
48
+ return app_permission_sql(actor, action)
49
+
50
+
51
+ @hookimpl
52
+ def jump_items_sql(datasette, actor, request):
53
+ async def inner():
54
+ app_sql, app_params = await datasette.allowed_resources_sql(
55
+ action="view-app", actor=actor
56
+ )
57
+ return JumpSQL(
58
+ sql=f"""
59
+ WITH allowed_apps AS (
60
+ {app_sql}
61
+ )
62
+ SELECT
63
+ 'app' AS type,
64
+ apps.name AS label,
65
+ apps.description AS description,
66
+ json_object(
67
+ 'method', 'path',
68
+ 'path', CASE
69
+ WHEN apps.external = 1
70
+ THEN '/-/apps/' || apps.id || '/launch'
71
+ ELSE apps.path
72
+ END
73
+ ) AS url,
74
+ 'app' || apps.name || ' ' || apps.description || ' ' ||
75
+ apps.id || ' ' || apps.source AS search_text,
76
+ NULL AS display_name
77
+ FROM apps
78
+ JOIN allowed_apps
79
+ ON allowed_apps.parent = 'apps'
80
+ AND allowed_apps.child = apps.id
81
+ WHERE apps.deleted_at IS NULL
82
+ """,
83
+ params=app_params,
84
+ )
85
+
86
+ return inner
87
+
88
+
89
+ @hookimpl
90
+ async def startup(datasette):
91
+ await Registry(datasette).ensure_tables()
92
+
93
+
94
+ @hookimpl
95
+ def top_homepage(datasette, request):
96
+ return top_homepage_html(datasette, request)
97
+
98
+
99
+ @hookimpl
100
+ def extra_css_urls():
101
+ return ["/-/static-plugins/datasette-apps/datasette-apps.css"]
102
+
103
+
104
+ @hookimpl
105
+ def menu_links(datasette, actor, request):
106
+ if not actor:
107
+ return []
108
+ return [{"href": datasette.urls.path("/-/apps"), "label": "Apps"}]
@@ -0,0 +1,72 @@
1
+ from __future__ import annotations
2
+
3
+ import ipaddress
4
+ import os
5
+ from urllib.parse import urlsplit
6
+
7
+ BASE_DIRECTIVES = [
8
+ "default-src 'none'",
9
+ "script-src 'unsafe-inline'",
10
+ "style-src 'unsafe-inline'",
11
+ ]
12
+
13
+ APP_VIEW_PARENT_CSP = "frame-src 'none';"
14
+
15
+
16
+ def _is_localhost(hostname):
17
+ if not hostname:
18
+ return False
19
+ hostname = hostname.lower()
20
+ if hostname == "localhost" or hostname.endswith(".localhost"):
21
+ return True
22
+ try:
23
+ return ipaddress.ip_address(hostname).is_loopback
24
+ except ValueError:
25
+ return False
26
+
27
+
28
+ def normalize_connect_origin(origin):
29
+ parsed = urlsplit((origin or "").strip())
30
+ allow_insecure_test_origins = os.environ.get(
31
+ "DATASETTE_APPS_ALLOW_INSECURE_TEST_CSP_ORIGINS"
32
+ )
33
+ if parsed.scheme != "https" and not allow_insecure_test_origins:
34
+ raise ValueError("Only https:// origins are allowed")
35
+ if parsed.scheme not in {"http", "https"}:
36
+ raise ValueError("Only http:// and https:// origins are allowed")
37
+ if not parsed.hostname:
38
+ raise ValueError("Origin must include a host")
39
+ if parsed.username or parsed.password:
40
+ raise ValueError("Origin must not include username or password")
41
+ if parsed.query or parsed.fragment:
42
+ raise ValueError("Origin must not include query string or fragment")
43
+ if parsed.path and parsed.path != "/":
44
+ raise ValueError("Origin must not include a path")
45
+ hostname = parsed.hostname.lower()
46
+ if "*" in hostname:
47
+ raise ValueError("Wildcard hosts are not allowed")
48
+ if _is_localhost(hostname) and not allow_insecure_test_origins:
49
+ raise ValueError("Localhost origins are not allowed")
50
+
51
+ # Accessing .port validates the port and raises ValueError if malformed.
52
+ port = parsed.port
53
+ if ":" in hostname:
54
+ netloc = f"[{hostname}]"
55
+ else:
56
+ netloc = hostname
57
+ if port is not None:
58
+ netloc = f"{netloc}:{port}"
59
+ return f"{parsed.scheme}://{netloc}"
60
+
61
+
62
+ def build_csp(connect_origins):
63
+ origins = [normalize_connect_origin(origin) for origin in connect_origins]
64
+ directives = [*BASE_DIRECTIVES]
65
+ if origins:
66
+ element_sources = ["'unsafe-inline'", *origins]
67
+ directives.append(f"script-src-elem {' '.join(element_sources)}")
68
+ directives.append(f"style-src-elem {' '.join(element_sources)}")
69
+ directives.append(f"img-src {' '.join(['data:', 'blob:', *origins])}")
70
+ if origins:
71
+ directives.append(f"connect-src {' '.join(origins)}")
72
+ return "; ".join(directives) + ";"