@livespace/plugin-studio 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -2
  3. package/dist/auth.js +220 -0
  4. package/dist/cli.js +67 -0
  5. package/dist/keys.js +42 -0
  6. package/dist/manifest.js +16 -0
  7. package/dist/page/domain/address.js +79 -0
  8. package/dist/page/domain/connection.js +2 -0
  9. package/dist/page/domain/display.js +38 -0
  10. package/dist/page/domain/draft.js +80 -0
  11. package/dist/page/domain/failures-store.js +41 -0
  12. package/dist/page/domain/failures.js +75 -0
  13. package/dist/page/domain/layout-store.js +119 -0
  14. package/dist/page/domain/log-store.js +37 -0
  15. package/dist/page/domain/navigation-store.js +17 -0
  16. package/dist/page/domain/plugin-data.js +70 -0
  17. package/dist/page/domain/plugin-store.js +257 -0
  18. package/dist/page/domain/probe-store.js +100 -0
  19. package/dist/page/domain/profile-session.js +115 -0
  20. package/dist/page/domain/profile-store.js +51 -0
  21. package/dist/page/domain/samples.js +221 -0
  22. package/dist/page/domain/secrets-store.js +159 -0
  23. package/dist/page/domain/secrets.js +135 -0
  24. package/dist/page/domain/settings-data.js +64 -0
  25. package/dist/page/domain/settings-session.js +206 -0
  26. package/dist/page/domain/settings-store.js +62 -0
  27. package/dist/page/domain/slot-store.js +50 -0
  28. package/dist/page/domain/studio.js +162 -0
  29. package/dist/page/domain/surface-store.js +71 -0
  30. package/dist/page/domain/toasts-store.js +60 -0
  31. package/dist/page/domain/view-data.js +122 -0
  32. package/dist/page/domain/view-store.js +132 -0
  33. package/dist/page/host.css +907 -0
  34. package/dist/page/index.html +31 -0
  35. package/dist/page/main.js +43 -0
  36. package/dist/page/plugin-studio-logo.svg +4 -0
  37. package/dist/page/reload.svg +1 -0
  38. package/dist/page/transport/browser-storage.js +41 -0
  39. package/dist/page/transport/console-mirror.js +48 -0
  40. package/dist/page/transport/embed.js +142 -0
  41. package/dist/page/transport/plugin-keys.js +68 -0
  42. package/dist/page/transport/studio-api.js +74 -0
  43. package/dist/page/ui/app.js +61 -0
  44. package/dist/page/ui/boot.js +44 -0
  45. package/dist/page/ui/brand.js +3 -0
  46. package/dist/page/ui/context.js +11 -0
  47. package/dist/page/ui/json-field.js +19 -0
  48. package/dist/page/ui/json-tokens.js +40 -0
  49. package/dist/page/ui/json-view.js +11 -0
  50. package/dist/page/ui/memo.js +23 -0
  51. package/dist/page/ui/messages.js +34 -0
  52. package/dist/page/ui/page-switcher.js +11 -0
  53. package/dist/page/ui/plugin-frame.js +43 -0
  54. package/dist/page/ui/profile-page.js +13 -0
  55. package/dist/page/ui/resize-handle.js +63 -0
  56. package/dist/page/ui/root.js +9 -0
  57. package/dist/page/ui/section.js +19 -0
  58. package/dist/page/ui/settings/config-form.js +59 -0
  59. package/dist/page/ui/settings/secret-field.js +22 -0
  60. package/dist/page/ui/settings/settings-page.js +60 -0
  61. package/dist/page/ui/sidebar/custom-settings-section.js +10 -0
  62. package/dist/page/ui/sidebar/failures-section.js +27 -0
  63. package/dist/page/ui/sidebar/installation-section.js +30 -0
  64. package/dist/page/ui/sidebar/metadata-section.js +9 -0
  65. package/dist/page/ui/sidebar/plugin-section.js +18 -0
  66. package/dist/page/ui/sidebar/preferences-section.js +16 -0
  67. package/dist/page/ui/sidebar/record-section.js +17 -0
  68. package/dist/page/ui/sidebar/viewer-section.js +8 -0
  69. package/dist/page/ui/sidebar-group.js +4 -0
  70. package/dist/page/ui/splash.js +6 -0
  71. package/dist/page/ui/status.js +10 -0
  72. package/dist/page/ui/surface.js +23 -0
  73. package/dist/page/ui/theme.js +13 -0
  74. package/dist/page/ui/toasts.js +31 -0
  75. package/dist/page/ui/top-bar.js +37 -0
  76. package/dist/server.js +519 -0
  77. package/dist/start.js +108 -0
  78. package/package.json +55 -5
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Livespace S.A.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,123 @@
1
- # Temporary Holding Version
1
+ # @livespace/plugin-studio
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Plugin Studio: try and debug a Livespace plugin locally. It embeds your plugin's page the way
4
+ Livespace does, and acts as the Livespace account your plugin's backend calls.
5
+
6
+ ```sh
7
+ npm install --save-dev @livespace/plugin-studio
8
+ ```
9
+
10
+ Projects that [`@livespace/plugin-cli create`](https://www.npmjs.com/package/@livespace/plugin-cli)
11
+ makes already have it, with a `studio` script. Outside a project, `npx @livespace/plugin-studio`
12
+ runs it for any plugin page, a deployed one included.
13
+
14
+ The studio uses the project's own `@livespace/plugin-sdk` (a peer dependency, `^1`), so it speaks
15
+ the same protocol version as the plugin.
16
+
17
+ ## Usage
18
+
19
+ ```sh
20
+ npm run dev # your plugin's dev server, in one terminal
21
+ npm run studio # the studio, in another: http://localhost:5190
22
+ ```
23
+
24
+ The studio embeds your page the way Livespace does: the same sandbox, the same messages in the
25
+ same order, sent again whenever your dev server reloads the page. The address is a field at the
26
+ top, so any plugin page works, a deployed one included.
27
+
28
+ - **Profile page**, as Livespace shows a plugin on a record (view mode only):
29
+ - the plugin in Livespace's chrome: inline in its slot's column, with "Open in dialog" (sized as
30
+ Livespace sizes it) and "Fullscreen";
31
+ - toasts.
32
+ - **Settings page**, as Livespace's settings screen (config and preview modes only):
33
+ - A hidden embed, on both pages, asks for your config form and hears what your plugin declares
34
+ about itself. A visible preview, in the same chrome and in the plugin's slot, shows what's
35
+ typed.
36
+ - Save checks the form as Livespace does. What's saved is what the profile page sends.
37
+ - Secret fields are sealed for your public key, from your manifest or your published
38
+ `jwks.json`, as an admin's browser seals them.
39
+ - **The sidebar**, grouped by what each thing is:
40
+ - **Plugin information**, what it declares about itself: its identity (below) and its metadata.
41
+ - **Stored settings**: where it's installed (a deal, company, person or space profile, or the
42
+ apps menu) and in which slot, whose column sets its width. Also its custom settings: the
43
+ config its form saved, the stored secrets' names, and Forget.
44
+ - **Context**: the profile's record, a sample editable as JSON, the viewer, and their
45
+ preferences as Livespace builds them.
46
+ - **Error handling**: the failure switches (below).
47
+
48
+ It's the same on both pages. The settings preview gets only the preferences: Livespace previews
49
+ a plugin with no record and no viewer. A warning mark says which sections it can't use.
50
+ - **The plugin's identity**, on both pages:
51
+ - The **client id**: the plugin's identity as a client, the `aud` of its tokens. A catalog
52
+ plugin's is `plugin:<its key>`; Livespace assigns one to a plugin added by URL.
53
+ - **How accounts add it**, which decides where its keys are: by URL (its
54
+ `/.well-known/livespace/jwks.json`) or from the catalog (a manifest, loaded from the project's
55
+ `plugin-manifest.json` or pasted). It also decides where the plugin can be installed: by URL,
56
+ where it declares (`supportedContextTypes`); from the catalog, where its manifest says
57
+ (`allowedObjectTypes`).
58
+ - **Your backend**: the studio is also a Livespace account, the dev account. It issues plugin
59
+ tokens, runs the token exchange and serves the sealed secrets. The Identity section shows what
60
+ your backend's environment needs, with a Copy button:
61
+
62
+ ```
63
+ LIVESPACE_KEYS_URL=http://localhost:5190/core/api/auth/jwks
64
+ LIVESPACE_AUTH_URL=http://localhost:5190
65
+ PLUGIN_CLIENT_ID=plugin:<your plugin's key>
66
+ ```
67
+ - **Failures**: refuse `api.call`'s credentials (always, as there's no real account) with the code
68
+ you pick. Hand out expired plugin tokens to exercise the retry, or make the exchange refuse as
69
+ Livespace can.
70
+ - **Messages**: every message, both ways, in a pane on the right. Its button in the top bar hides
71
+ it, and its edge resizes it.
72
+ - **The browser console** gets the same log, one line per entry, prefixed `[studio]`, for the
73
+ browser tools coding agents use. The studio's notes (what it refused or dropped as Livespace
74
+ would, timeouts, what the address set) are warnings. The plugin's messages are `debug`, hidden
75
+ unless asked for: Chrome's "Verbose" level, or `level: "debug"` in the Playwright MCP's
76
+ `browser_console_messages`. Payloads over 4000 characters are cut.
77
+
78
+ `--url` fills in the address (default: Vite's `http://localhost:5173` or Bun's
79
+ `http://localhost:3000`, from the project; outside one, the page asks). `--port` moves the
80
+ studio, and `--client-id` sets the starting client id (default: the manifest's `plugin:<id>`, else
81
+ `plugin:dev`). The sidebar, the address and the layout are kept in your browser; what you save on
82
+ the settings page lives in the studio's memory, so a restart starts that afresh.
83
+
84
+ ## Setting up a state from the address
85
+
86
+ The address can set up a state in one go, which is quicker for a coding agent than clicking
87
+ through the sidebar. Params go after the page in the hash, `#?…` for the profile page and
88
+ `#settings?…` for the settings page:
89
+
90
+ ```
91
+ http://localhost:5190/#?type=none&viewer=&display=fullscreen&token=forbidden
92
+ http://localhost:5190/#settings?preferences=en-US&width=320
93
+ ```
94
+
95
+ | Param | Values | Sets |
96
+ |---|---|---|
97
+ | `type` | `deal`, `company`, `person`, `space`, `none` (the apps menu) | Where it's installed. A type the plugin can't be installed on gives way, as in the sidebar. |
98
+ | `viewer` | A user id; empty for no user | The viewer. |
99
+ | `preferences` | `pl`, `en-US`, `none` (an older Livespace) | The preferences preset. |
100
+ | `width` | `320`, `420`, `640`, `full` | The slot's column width. |
101
+ | `height` | Pixels, 40–2000 | The plugin's inline height. |
102
+ | `display` | `inline`, `dialog`, `fullscreen` | The profile page's display, for its next embed if none is open. |
103
+ | `credentials` | `bad_request`, `unauthenticated`, `forbidden`, `not_found`, `conflict`, `server_error`, `no-answer` | How `api.call`'s credentials are refused. |
104
+ | `token` | `token`, `every-other-expired`, a refusal code above or `not_purchased`, `no-answer` | How plugin tokens are answered. |
105
+
106
+ - **Set once, then dropped.** What's set is kept as if chosen in the sidebar, and the params
107
+ leave the address, so a reload or Back never sets them again. The message log notes what was
108
+ set, and what was ignored and why.
109
+ - **This browser's state only.** The saved settings, the stored secrets and the exchange's
110
+ refusal live in the studio's memory, so everyone using that studio shares them: a plugin's
111
+ backend reads them without a browser. The address never sets them. Use the settings form and
112
+ the Switches section instead.
113
+
114
+ ## Flags
115
+
116
+ | Flag | What it does |
117
+ |---|---|
118
+ | `--url <page>` | The plugin's page to start with. The page can change it. |
119
+ | `--port <n>` | Where the studio listens (default: 5190). |
120
+ | `--client-id <id>` | The starting client id. The page can change it. |
121
+ | `--dir <path>` | The plugin project, for its manifest and template (default: the current directory). |
122
+
123
+ Real Livespace stays the final check: its own chrome, permissions and catalog.
package/dist/auth.js ADDED
@@ -0,0 +1,220 @@
1
+ /**
2
+ * The dev account: the Livespace services a plugin's backend calls, as `packages/sdk/docs/backend.md`
3
+ * describes them. It signs plugin tokens with a key made at start and publishes that key, runs the
4
+ * token exchange (checking the backend's signed request against the plugin's own key set), and
5
+ * serves the installation's sealed secrets. In memory; nothing survives a restart.
6
+ */
7
+ import { createPrivateKey, createPublicKey, createSign, createVerify, randomBytes, randomUUID, } from "node:crypto";
8
+ import { generateKeyPair } from "./keys.js";
9
+ export const KEYS_PATH = "/core/api/auth/jwks";
10
+ export const TOKEN_PATH = "/core/api/auth/oauth/token";
11
+ export const SECRETS_PATH = "/core/api/plugins/installation/secrets";
12
+ /** A plugin token and an access token both live 60 seconds, as Livespace's do. */
13
+ export const TOKEN_LIFETIME_S = 60;
14
+ /** The clock difference backend.md tells backends to allow, allowed here too. */
15
+ const CLOCK_TOLERANCE_S = 30;
16
+ /** The dev account's fixed ids, as a plugin token names them. */
17
+ export const TENANT_ID = "dev-tenant";
18
+ export const INSTALLATION_ID = "dev-installation";
19
+ const TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange";
20
+ const JWT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:jwt";
21
+ const JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
22
+ const part = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
23
+ function signRs256(header, claims, key) {
24
+ const input = `${part(header)}.${part(claims)}`;
25
+ const signature = createSign("RSA-SHA256").update(input).sign(key);
26
+ return `${input}.${signature.toString("base64url")}`;
27
+ }
28
+ /** A JWT's header and claims, unverified, or undefined when it isn't one. */
29
+ function decode(token) {
30
+ const parts = token.split(".");
31
+ if (parts.length !== 3) {
32
+ return undefined;
33
+ }
34
+ const [header = "", claims = "", signature = ""] = parts;
35
+ try {
36
+ return {
37
+ header: JSON.parse(Buffer.from(header, "base64url").toString("utf8")),
38
+ claims: JSON.parse(Buffer.from(claims, "base64url").toString("utf8")),
39
+ input: `${header}.${claims}`,
40
+ signature: Buffer.from(signature, "base64url"),
41
+ };
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ }
47
+ const verifies = (input, signature, key) => createVerify("RSA-SHA256").update(input).verify(key, signature);
48
+ /** How the exchange can be made to refuse, as backend.md's table lists Livespace's refusals. */
49
+ export const EXCHANGE_REFUSALS = [
50
+ "not_installed",
51
+ "not_purchased",
52
+ "user_not_allowed",
53
+ "invalid_client",
54
+ ];
55
+ export class DevAccount {
56
+ issuer;
57
+ clientId;
58
+ kid;
59
+ privateKey;
60
+ publicJwk;
61
+ now;
62
+ /** Set from the studio's failure switches: how the next exchanges refuse, if they do. */
63
+ refusal = null;
64
+ accessTokens = new Map();
65
+ seenJtis = new Map();
66
+ constructor(
67
+ /** `http://localhost:<port>`: the account's address, `iss` in its tokens. */
68
+ issuer,
69
+ /** The plugin's client id: the `aud` of its tokens. The page can change it. */
70
+ clientId, kid, privateKey, publicJwk, now) {
71
+ this.issuer = issuer;
72
+ this.clientId = clientId;
73
+ this.kid = kid;
74
+ this.privateKey = privateKey;
75
+ this.publicJwk = publicJwk;
76
+ this.now = now;
77
+ }
78
+ /** A fresh signing key every run: a backend's remote key set refetches on a new `kid`. */
79
+ static async create(issuer, clientId, now = () => Date.now()) {
80
+ const kid = `dev-${randomBytes(4).toString("hex")}`;
81
+ const { publicJwk, privatePem } = await generateKeyPair("sig", kid);
82
+ return new DevAccount(issuer, clientId, kid, createPrivateKey(privatePem), publicJwk, now);
83
+ }
84
+ get keysUrl() {
85
+ return this.issuer + KEYS_PATH;
86
+ }
87
+ get tokenUrl() {
88
+ return this.issuer + TOKEN_PATH;
89
+ }
90
+ /** What `LIVESPACE_KEYS_URL` serves: the key the plugin tokens are signed with. */
91
+ keySet() {
92
+ return { keys: [this.publicJwk] };
93
+ }
94
+ seconds() {
95
+ return Math.floor(this.now() / 1000);
96
+ }
97
+ /**
98
+ * A plugin token for the viewer, as Livespace answers `request-session-token`. `expired` signs
99
+ * one already past its `exp`, beyond the clock tolerance, while still saying it lives 60 s:
100
+ * the SDK keeps it, the backend answers 401, and `backend.fetch` asks for a fresh one.
101
+ */
102
+ sessionToken(sub, { expired = false } = {}) {
103
+ const lifetime = TOKEN_LIFETIME_S;
104
+ const iat = this.seconds() - (expired ? lifetime + 2 * CLOCK_TOLERANCE_S : 0);
105
+ const token = signRs256({ alg: "RS256", typ: "JWT", kid: this.kid }, {
106
+ iss: this.issuer,
107
+ tid: TENANT_ID,
108
+ sub,
109
+ installationId: INSTALLATION_ID,
110
+ aud: this.clientId,
111
+ iat,
112
+ exp: iat + lifetime,
113
+ jti: randomUUID(),
114
+ }, this.privateKey);
115
+ return { token, expiresIn: lifetime };
116
+ }
117
+ /** The plugin token's claims, if this account signed it for this plugin and it's in date. */
118
+ subjectClaims(token) {
119
+ const decoded = decode(token);
120
+ if (decoded === undefined ||
121
+ decoded.header.alg !== "RS256" ||
122
+ decoded.header.kid !== this.kid ||
123
+ !verifies(decoded.input, decoded.signature, createPublicKey(this.privateKey))) {
124
+ return undefined;
125
+ }
126
+ const { claims } = decoded;
127
+ return claims.iss === this.issuer &&
128
+ claims.aud === this.clientId &&
129
+ typeof claims.exp === "number" &&
130
+ claims.exp + CLOCK_TOLERANCE_S > this.seconds()
131
+ ? claims
132
+ : undefined;
133
+ }
134
+ /**
135
+ * `POST /core/api/auth/oauth/token`: the backend trades a plugin token for an access token,
136
+ * signing its request with its own key (`private_key_jwt`). Refusals as backend.md lists them.
137
+ */
138
+ async exchange(form, signingKeys) {
139
+ if (form.get("grant_type") !== TOKEN_EXCHANGE) {
140
+ return { status: 400, body: { error: "unsupported_grant_type" } };
141
+ }
142
+ const subjectToken = form.get("subject_token");
143
+ const assertion = form.get("client_assertion");
144
+ if (subjectToken === null ||
145
+ form.get("subject_token_type") !== JWT_TOKEN_TYPE ||
146
+ assertion === null ||
147
+ form.get("client_assertion_type") !== JWT_BEARER) {
148
+ return { status: 400, body: { error: "invalid_request" } };
149
+ }
150
+ // The backend's own signature first: a request that can't prove who sent it learns nothing.
151
+ const decoded = decode(assertion);
152
+ const kid = decoded?.header.kid;
153
+ const jwk = typeof kid === "string" ? await signingKeys(kid) : undefined;
154
+ const now = this.seconds();
155
+ const claims = decoded?.claims;
156
+ const jti = claims?.jti;
157
+ if (decoded === undefined ||
158
+ decoded.header.alg !== "RS256" ||
159
+ jwk === undefined ||
160
+ !verifies(decoded.input, decoded.signature, createPublicKey({ key: { ...jwk }, format: "jwk" })) ||
161
+ claims?.iss !== this.clientId ||
162
+ claims.sub !== this.clientId ||
163
+ claims.aud !== this.tokenUrl ||
164
+ typeof claims.exp !== "number" ||
165
+ claims.exp + CLOCK_TOLERANCE_S <= now ||
166
+ typeof jti !== "string" ||
167
+ this.seen(jti, claims.exp)) {
168
+ return { status: 401, body: { error: "invalid_client" } };
169
+ }
170
+ if (this.refusal === "invalid_client") {
171
+ return { status: 401, body: { error: "invalid_client" } };
172
+ }
173
+ if (this.subjectClaims(subjectToken) === undefined) {
174
+ return {
175
+ status: 400,
176
+ body: { error: "invalid_grant", reason: "token_invalid" },
177
+ };
178
+ }
179
+ if (this.refusal !== null) {
180
+ return {
181
+ status: 400,
182
+ body: { error: "invalid_grant", reason: this.refusal },
183
+ };
184
+ }
185
+ const accessToken = randomBytes(24).toString("base64url");
186
+ this.accessTokens.set(accessToken, now + TOKEN_LIFETIME_S);
187
+ return {
188
+ status: 200,
189
+ body: {
190
+ access_token: accessToken,
191
+ token_type: "Bearer",
192
+ expires_in: TOKEN_LIFETIME_S,
193
+ issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
194
+ },
195
+ };
196
+ }
197
+ /** Whether a `jti` was used before; remembers it until its assertion expires. */
198
+ seen(jti, exp) {
199
+ const now = this.seconds();
200
+ for (const [old, until] of this.seenJtis) {
201
+ if (until + CLOCK_TOLERANCE_S <= now) {
202
+ this.seenJtis.delete(old);
203
+ }
204
+ }
205
+ if (this.seenJtis.has(jti)) {
206
+ return true;
207
+ }
208
+ this.seenJtis.set(jti, exp);
209
+ return false;
210
+ }
211
+ /** `GET …/installation/secrets`: every sealed secret, for a valid access token. */
212
+ secrets(authorization, sealed) {
213
+ const token = authorization?.replace(/^Bearer /, "");
214
+ const until = token === undefined ? undefined : this.accessTokens.get(token);
215
+ if (until === undefined || until <= this.seconds()) {
216
+ return { status: 401, body: { error: "invalid_token" } };
217
+ }
218
+ return { status: 200, body: { data: sealed } };
219
+ }
220
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * livespace-plugin-studio: Plugin Studio, a local stand-in for Livespace that embeds a plugin's
4
+ * page as Livespace does. See `--help`.
5
+ */
6
+ import { readFileSync } from "node:fs";
7
+ import { resolve } from "node:path";
8
+ import { parseArgs } from "node:util";
9
+ import { startStudio } from "./server.js";
10
+ import { STUDIO_PORT, UsageError, start, untilSignal } from "./start.js";
11
+ const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
12
+ const HELP = `livespace-plugin-studio ${version}: try a Livespace plugin locally
13
+
14
+ Usage: livespace-plugin-studio [--url <plugin page>] [--port <n>] [--client-id <id>]
15
+ [--dir <path>]
16
+
17
+ Serves Plugin Studio at http://localhost:${STUDIO_PORT}. It embeds your plugin's page the way
18
+ Livespace does, renders its settings form, logs every message, and acts as the account your
19
+ backend calls (it prints the env values). Start your dev server first; the studio doesn't start it.
20
+
21
+ --url <page> The plugin's page (default: Vite's or Bun's dev server, from the
22
+ project's template; otherwise the page asks). The page can change it.
23
+ --port <n> Where the studio listens (default: ${STUDIO_PORT}).
24
+ --client-id <id> The plugin's client id (default: plugin:<id> from the project's
25
+ plugin-manifest.json, else plugin:dev). The page can change it.
26
+ --dir <path> The plugin project (default: the current directory).
27
+ --help, -h This text.
28
+ --version, -v The version.
29
+ `;
30
+ async function main(argv) {
31
+ const { values } = parseArgs({
32
+ args: argv,
33
+ options: {
34
+ url: { type: "string" },
35
+ port: { type: "string" },
36
+ "client-id": { type: "string" },
37
+ dir: { type: "string" },
38
+ help: { type: "boolean", short: "h" },
39
+ version: { type: "boolean", short: "v" },
40
+ },
41
+ });
42
+ if (values.help) {
43
+ console.log(HELP);
44
+ return 0;
45
+ }
46
+ if (values.version) {
47
+ console.log(version);
48
+ return 0;
49
+ }
50
+ await start({
51
+ dir: resolve(values.dir ?? process.cwd()),
52
+ url: values.url,
53
+ port: values.port,
54
+ clientId: values["client-id"],
55
+ }, { start: startStudio, untilStopped: untilSignal, print: console.log });
56
+ return 0;
57
+ }
58
+ main(process.argv.slice(2)).then((code) => {
59
+ process.exitCode = code;
60
+ }, (error) => {
61
+ const usage = error instanceof UsageError ||
62
+ error.code?.startsWith("ERR_PARSE_ARGS") === true;
63
+ console.error(usage
64
+ ? `livespace-plugin-studio: ${error.message}\nSee livespace-plugin-studio --help.`
65
+ : `Unexpected error: ${error.stack ?? error}`);
66
+ process.exitCode = 1;
67
+ });
package/dist/keys.js ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The dev account's key pairs, from Web Crypto, and the shapes the studio reads from a catalog
3
+ * manifest. The CLI's `keys` commands make authors' keys the same way; the studio keeps its own
4
+ * copy rather than depending on the CLI.
5
+ */
6
+ /** Signing is RS256 only; secrets are RSA-OAEP-256, as Livespace accepts them. */
7
+ const KEY_ALG = { sig: "RS256", enc: "RSA-OAEP-256" };
8
+ const RSA_BITS = 2048;
9
+ /** A catalog plugin's client id, from its manifest's `id`. */
10
+ export const clientIdOf = (id) => `plugin:${id}`;
11
+ const ALGORITHMS = {
12
+ sig: {
13
+ name: "RSASSA-PKCS1-v1_5",
14
+ hash: "SHA-256",
15
+ usages: ["sign", "verify"],
16
+ },
17
+ enc: { name: "RSA-OAEP", hash: "SHA-256", usages: ["encrypt", "decrypt"] },
18
+ };
19
+ const toPem = (der) => {
20
+ const lines = Buffer.from(der)
21
+ .toString("base64")
22
+ .match(/.{1,64}/g) ?? [];
23
+ return `-----BEGIN PRIVATE KEY-----\n${lines.join("\n")}\n-----END PRIVATE KEY-----\n`;
24
+ };
25
+ export async function generateKeyPair(use, kid) {
26
+ const { name, hash, usages } = ALGORITHMS[use];
27
+ const pair = await crypto.subtle.generateKey({
28
+ name,
29
+ hash,
30
+ modulusLength: RSA_BITS,
31
+ publicExponent: new Uint8Array([1, 0, 1]),
32
+ }, true, [...usages]);
33
+ const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey);
34
+ if (jwk.n === undefined || jwk.e === undefined) {
35
+ throw new Error("Web Crypto returned an RSA key without n or e");
36
+ }
37
+ const privatePem = toPem(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
38
+ return {
39
+ publicJwk: { kty: "RSA", kid, use, alg: KEY_ALG[use], n: jwk.n, e: jwk.e },
40
+ privatePem,
41
+ };
42
+ }
@@ -0,0 +1,16 @@
1
+ /** The project's `plugin-manifest.json`, read as text: the studio only needs its id and keys. */
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ export const MANIFEST_FILE = "plugin-manifest.json";
5
+ /** The manifest's text, or undefined when the project has none. */
6
+ export async function readManifestText(dir) {
7
+ try {
8
+ return await readFile(join(dir, MANIFEST_FILE), "utf8");
9
+ }
10
+ catch (error) {
11
+ if (error.code === "ENOENT") {
12
+ return undefined;
13
+ }
14
+ throw error;
15
+ }
16
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The studio's address: the page, and a one-off instruction to set up a state, so a coding agent
3
+ * opens one URL per state instead of clicking through the sidebar. E.g.
4
+ * `#settings?type=company&preferences=en-US`, or `#?type=deal&display=dialog` for the profile.
5
+ * Only what this browser keeps: the saved settings, secrets and the exchange's refusal are the
6
+ * server's, shared by everyone on the studio. No DOM here.
7
+ */
8
+ import { COLUMN_WIDTHS } from "./display.js";
9
+ import { CREDENTIALS_CHOICES, TOKEN_CHOICES } from "./failures.js";
10
+ import { MAX_HEIGHT_PX, MIN_HEIGHT_PX } from "./slot-store.js";
11
+ import { PREFERENCE_PRESETS, RECORD_CHOICES, } from "./view-data.js";
12
+ const DISPLAYS = ["inline", "dialog", "fullscreen"];
13
+ const widthText = (width) => width === null ? "full" : String(width);
14
+ const oneOf = (values, set) => (value) => values.includes(value)
15
+ ? { ok: true, set: set(value) }
16
+ : { ok: false, reason: `one of ${values.join(", ")}` };
17
+ const READERS = {
18
+ type: oneOf(RECORD_CHOICES.map((c) => c.value), (type) => ({ type })),
19
+ viewer: (viewer) => ({ ok: true, set: { viewer: viewer.trim() } }),
20
+ preferences: oneOf(PREFERENCE_PRESETS.map((p) => p.value), (preferences) => ({ preferences })),
21
+ width: (value) => {
22
+ const width = COLUMN_WIDTHS.find((w) => widthText(w.value) === value);
23
+ return width === undefined
24
+ ? {
25
+ ok: false,
26
+ reason: `one of ${COLUMN_WIDTHS.map((w) => widthText(w.value)).join(", ")}`,
27
+ }
28
+ : { ok: true, set: { width: width.value } };
29
+ },
30
+ height: (value) => {
31
+ const height = Number(value);
32
+ return /^\d+$/.test(value) &&
33
+ height >= MIN_HEIGHT_PX &&
34
+ height <= MAX_HEIGHT_PX
35
+ ? { ok: true, set: { height } }
36
+ : { ok: false, reason: `pixels, ${MIN_HEIGHT_PX}–${MAX_HEIGHT_PX}` };
37
+ },
38
+ display: oneOf(DISPLAYS, (display) => ({ display })),
39
+ credentials: oneOf(CREDENTIALS_CHOICES.map((c) => c.value), (credentials) => ({ credentials })),
40
+ token: oneOf(TOKEN_CHOICES.map((c) => c.value), (token) => ({ token })),
41
+ };
42
+ /** Kept on the server, so never set from an address: say why, rather than "unknown". */
43
+ const SERVER_SIDE = {
44
+ config: "the saved settings are the studio server's: use the settings form",
45
+ exchange: "the exchange's refusal is the studio server's: use the Switches section",
46
+ };
47
+ export function readAddress(hash) {
48
+ const text = hash.startsWith("#") ? hash.slice(1) : hash;
49
+ const at = text.indexOf("?");
50
+ const path = at === -1 ? text : text.slice(0, at);
51
+ const page = path === "settings" ? "settings" : "profile";
52
+ const address = {
53
+ page,
54
+ changes: {},
55
+ applied: [],
56
+ ignored: [],
57
+ clean: page === "settings" ? "#settings" : "",
58
+ };
59
+ if (at === -1) {
60
+ return address;
61
+ }
62
+ new URLSearchParams(text.slice(at + 1)).forEach((value, name) => {
63
+ const read = READERS[name];
64
+ if (read === undefined) {
65
+ address.ignored.push(`${name} (${SERVER_SIDE[name] ?? "unknown"})`);
66
+ return;
67
+ }
68
+ const result = name === "display" && page === "settings"
69
+ ? { ok: false, reason: "the profile page's alone" }
70
+ : read(value);
71
+ if (!result.ok) {
72
+ address.ignored.push(`${name}=${value} (${result.reason})`);
73
+ return;
74
+ }
75
+ Object.assign(address.changes, result.set);
76
+ address.applied.push(`${name}=${value}`);
77
+ });
78
+ return address;
79
+ }
@@ -0,0 +1,2 @@
1
+ /** What answers one embed of the plugin: a page's session, which `PluginFrame` connects. */
2
+ export {};
@@ -0,0 +1,38 @@
1
+ /**
2
+ * How plugin-slot lays out its one iframe: inline in a profile column, in a dialog, or
3
+ * fullscreen. The same element is restyled, never moved, so the plugin never reloads
4
+ * (ls-fe plugin-slot core/src/domain/plugin-slot.ts). No DOM here.
5
+ */
6
+ /** Livespace's dialog before the plugin says otherwise. */
7
+ export const DIALOG_WIDTH_PX = 1100;
8
+ export const DIALOG_HEIGHT_PX = 760;
9
+ /** Room kept around the dialog, and above it for Livespace's top bar. */
10
+ export const DIALOG_MARGIN_PX = 64;
11
+ export const TOP_INSET_PX = 60;
12
+ /** Widths a profile column comes in; `null` is the whole stage. */
13
+ export const COLUMN_WIDTHS = [
14
+ { value: 320, label: "Narrow column (320 px)" },
15
+ { value: 420, label: "Column (420 px)" },
16
+ { value: 640, label: "Wide column (640 px)" },
17
+ { value: null, label: "Full width" },
18
+ ];
19
+ export const DEFAULT_HEIGHT_PX = 360;
20
+ /**
21
+ * One axis of the dialog, as CSS: the default clamped to the plugin's bounds (the minimum winning
22
+ * over the maximum), then to the room it has, which wins over both. Livespace's room is the
23
+ * window; the studio's is its main area, a size container (`cqw`, `cqh`).
24
+ */
25
+ function axis(fallback, min, max, room) {
26
+ let size = max === undefined ? `${fallback}px` : `min(${fallback}px, ${max}px)`;
27
+ if (min !== undefined) {
28
+ size = `max(${min}px, ${size})`;
29
+ }
30
+ return `min(${size}, ${room})`;
31
+ }
32
+ /** The dialog's size for the latest `modal-size` bounds, already through `sanitizeModalSize`. */
33
+ export function dialogSize(bounds) {
34
+ return {
35
+ width: axis(DIALOG_WIDTH_PX, bounds.minWidthPx, bounds.maxWidthPx, `calc(100cqw - ${DIALOG_MARGIN_PX}px)`),
36
+ height: axis(DIALOG_HEIGHT_PX, bounds.minHeightPx, bounds.maxHeightPx, `calc(100cqh - ${TOP_INSET_PX}px - ${DIALOG_MARGIN_PX}px)`),
37
+ };
38
+ }