@livespace/plugin-studio 0.0.0-stage → 0.1.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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +87 -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/connection.js +2 -0
  8. package/dist/page/domain/display.js +38 -0
  9. package/dist/page/domain/draft.js +80 -0
  10. package/dist/page/domain/failures-store.js +41 -0
  11. package/dist/page/domain/failures.js +75 -0
  12. package/dist/page/domain/layout-store.js +119 -0
  13. package/dist/page/domain/log-store.js +37 -0
  14. package/dist/page/domain/navigation-store.js +16 -0
  15. package/dist/page/domain/plugin-data.js +70 -0
  16. package/dist/page/domain/plugin-store.js +257 -0
  17. package/dist/page/domain/probe-store.js +100 -0
  18. package/dist/page/domain/profile-session.js +115 -0
  19. package/dist/page/domain/profile-store.js +21 -0
  20. package/dist/page/domain/samples.js +221 -0
  21. package/dist/page/domain/secrets-store.js +159 -0
  22. package/dist/page/domain/secrets.js +135 -0
  23. package/dist/page/domain/settings-data.js +64 -0
  24. package/dist/page/domain/settings-session.js +206 -0
  25. package/dist/page/domain/settings-store.js +62 -0
  26. package/dist/page/domain/slot-store.js +50 -0
  27. package/dist/page/domain/studio.js +121 -0
  28. package/dist/page/domain/surface-store.js +71 -0
  29. package/dist/page/domain/toasts-store.js +60 -0
  30. package/dist/page/domain/view-data.js +122 -0
  31. package/dist/page/domain/view-store.js +132 -0
  32. package/dist/page/host.css +907 -0
  33. package/dist/page/index.html +31 -0
  34. package/dist/page/main.js +31 -0
  35. package/dist/page/plugin-studio-logo.svg +4 -0
  36. package/dist/page/reload.svg +1 -0
  37. package/dist/page/transport/browser-storage.js +41 -0
  38. package/dist/page/transport/embed.js +142 -0
  39. package/dist/page/transport/plugin-keys.js +68 -0
  40. package/dist/page/transport/studio-api.js +74 -0
  41. package/dist/page/ui/app.js +61 -0
  42. package/dist/page/ui/boot.js +44 -0
  43. package/dist/page/ui/brand.js +3 -0
  44. package/dist/page/ui/context.js +11 -0
  45. package/dist/page/ui/json-field.js +19 -0
  46. package/dist/page/ui/json-tokens.js +40 -0
  47. package/dist/page/ui/json-view.js +11 -0
  48. package/dist/page/ui/memo.js +23 -0
  49. package/dist/page/ui/messages.js +34 -0
  50. package/dist/page/ui/page-switcher.js +11 -0
  51. package/dist/page/ui/plugin-frame.js +43 -0
  52. package/dist/page/ui/profile-page.js +13 -0
  53. package/dist/page/ui/resize-handle.js +63 -0
  54. package/dist/page/ui/root.js +9 -0
  55. package/dist/page/ui/section.js +19 -0
  56. package/dist/page/ui/settings/config-form.js +59 -0
  57. package/dist/page/ui/settings/secret-field.js +22 -0
  58. package/dist/page/ui/settings/settings-page.js +60 -0
  59. package/dist/page/ui/sidebar/custom-settings-section.js +10 -0
  60. package/dist/page/ui/sidebar/failures-section.js +27 -0
  61. package/dist/page/ui/sidebar/installation-section.js +30 -0
  62. package/dist/page/ui/sidebar/metadata-section.js +9 -0
  63. package/dist/page/ui/sidebar/plugin-section.js +18 -0
  64. package/dist/page/ui/sidebar/preferences-section.js +16 -0
  65. package/dist/page/ui/sidebar/record-section.js +17 -0
  66. package/dist/page/ui/sidebar/viewer-section.js +8 -0
  67. package/dist/page/ui/sidebar-group.js +4 -0
  68. package/dist/page/ui/splash.js +6 -0
  69. package/dist/page/ui/status.js +10 -0
  70. package/dist/page/ui/surface.js +23 -0
  71. package/dist/page/ui/theme.js +13 -0
  72. package/dist/page/ui/toasts.js +31 -0
  73. package/dist/page/ui/top-bar.js +37 -0
  74. package/dist/server.js +519 -0
  75. package/dist/start.js +108 -0
  76. package/package.json +55 -5
@@ -0,0 +1,115 @@
1
+ /**
2
+ * One embed on the profile page, as plugin-slot speaks to it: the handshake and its updates, and
3
+ * answers to the plugin's requests. API credentials are refused, as there's no real account behind
4
+ * the studio. Plugin tokens come from the dev account, unless a failure switch says otherwise.
5
+ */
6
+ import { MSG_API_CREDENTIALS, MSG_MODAL_SIZE, MSG_NOTIFY, MSG_REQUEST_API_CREDENTIALS, MSG_REQUEST_SESSION_TOKEN, MSG_SESSION_TOKEN, } from "@livespace/plugin-sdk";
7
+ import { effect } from "@preact/signals";
8
+ import { Embed } from "../transport/embed.js";
9
+ import { credentialsAnswer, tokenPlan } from "./failures.js";
10
+ /** A request's id, or undefined: plugin-slot ignores a request it can't answer by id. */
11
+ const requestIdOf = (payload) => {
12
+ const requestId = payload?.requestId;
13
+ return typeof requestId === "string" && requestId !== ""
14
+ ? requestId
15
+ : undefined;
16
+ };
17
+ export class ProfileSession {
18
+ deps;
19
+ #embed;
20
+ #stops = [];
21
+ #lastTokenExpired = false;
22
+ constructor(deps) {
23
+ this.deps = deps;
24
+ this.#embed = new Embed({
25
+ post: deps.post,
26
+ log: deps.log.append,
27
+ state: () => ({
28
+ mode: "view",
29
+ preferences: deps.view.preferences.value,
30
+ context: deps.view.context.value,
31
+ config: deps.settings.saved.value,
32
+ fullscreen: deps.surface.display.value === "fullscreen",
33
+ }),
34
+ });
35
+ // What the plugin is sent follows the sidebar and the saved settings.
36
+ this.#stops.push(effect(() => {
37
+ deps.view.preferences.value;
38
+ deps.view.context.value;
39
+ deps.settings.saved.value;
40
+ this.#embed.update();
41
+ }));
42
+ // Fullscreen's edges, as plugin-slot sends them.
43
+ let fullscreen = deps.surface.display.peek() === "fullscreen";
44
+ this.#stops.push(effect(() => {
45
+ const now = deps.surface.display.value === "fullscreen";
46
+ if (now !== fullscreen) {
47
+ fullscreen = now;
48
+ this.#embed.fullscreenChanged(now);
49
+ }
50
+ }));
51
+ }
52
+ /** A message from this embed's iframe, on its origin. */
53
+ receive = (data) => {
54
+ this.#embed.receive(data);
55
+ const { type, payload } = (data ?? {});
56
+ // Like plugin-slot, these are handled whenever they come, handshake or not.
57
+ if (type === MSG_MODAL_SIZE) {
58
+ this.deps.surface.modalSize(payload);
59
+ }
60
+ else if (type === MSG_NOTIFY) {
61
+ this.deps.toasts.notify(payload);
62
+ }
63
+ else if (type === MSG_REQUEST_SESSION_TOKEN) {
64
+ void this.#answerSessionToken(payload);
65
+ }
66
+ else if (type === MSG_REQUEST_API_CREDENTIALS) {
67
+ this.#answerCredentials(payload);
68
+ }
69
+ };
70
+ /** The iframe's `load`. */
71
+ loaded = () => {
72
+ this.#embed.loaded();
73
+ };
74
+ #answerCredentials(payload) {
75
+ const requestId = requestIdOf(payload);
76
+ if (requestId === undefined) {
77
+ return;
78
+ }
79
+ const answer = credentialsAnswer(requestId, this.deps.failures.failures.value.credentials);
80
+ if (answer === null) {
81
+ this.deps.log.append("note", "Not answered, as switched: the SDK times out");
82
+ return;
83
+ }
84
+ this.#embed.reply(MSG_API_CREDENTIALS, answer);
85
+ }
86
+ /** A plugin token for the viewer, from the dev account, as plugin-slot gets one from Livespace. */
87
+ async #answerSessionToken(payload) {
88
+ const requestId = requestIdOf(payload);
89
+ if (requestId === undefined) {
90
+ return;
91
+ }
92
+ const plan = tokenPlan(this.deps.failures.failures.value.token, this.#lastTokenExpired);
93
+ if (plan.kind === "none") {
94
+ this.deps.log.append("note", "Not answered, as switched: the SDK times out");
95
+ return;
96
+ }
97
+ if (plan.kind === "error") {
98
+ this.#embed.reply(MSG_SESSION_TOKEN, { requestId, error: plan.code });
99
+ return;
100
+ }
101
+ this.#lastTokenExpired = plan.expired;
102
+ const sub = this.deps.view.context.value.user?.id ?? "";
103
+ const answer = await this.deps.api.sessionToken(sub, plan.expired).then((token) => ({ requestId, ...token }), () => ({ requestId, error: "unauthenticated" }));
104
+ if (plan.expired) {
105
+ this.deps.log.append("note", "This token is already expired, as switched: expect a 401 and a retry");
106
+ }
107
+ this.#embed.reply(MSG_SESSION_TOKEN, answer);
108
+ }
109
+ dispose() {
110
+ for (const stop of this.#stops) {
111
+ stop();
112
+ }
113
+ this.#embed.dispose();
114
+ }
115
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The profile page, as plugin-slot shows a plugin on a record: one view-mode embed in Livespace's
3
+ * chrome, inline in its slot, its dialog and fullscreen. Each embed gets a `ProfileSession`, which
4
+ * answers its messages.
5
+ */
6
+ import { ProfileSession } from "./profile-session.js";
7
+ import { SurfaceStore } from "./surface-store.js";
8
+ export class ProfileStore {
9
+ deps;
10
+ surface;
11
+ constructor(deps) {
12
+ this.deps = deps;
13
+ this.surface = new SurfaceStore({ log: deps.log.append }, deps.slot.size);
14
+ }
15
+ /** A new embed of the plugin: its session answers it through `post`. */
16
+ connect = (post) => {
17
+ this.surface.reset();
18
+ this.deps.toasts.reset();
19
+ return new ProfileSession({ ...this.deps, surface: this.surface, post });
20
+ };
21
+ }
@@ -0,0 +1,221 @@
1
+ /**
2
+ * The records the studio starts from, one per type: copies of the SDK's own fixtures
3
+ * (packages/sdk/src/__fixtures__), which aren't published. A test keeps them equal.
4
+ */
5
+ export const SAMPLES = {
6
+ deal: {
7
+ version: 1,
8
+ type: "deal",
9
+ id: "e2251091-7efa-aaee-9dfd-81717a2d2782",
10
+ name: "Google Ads campaign 2027",
11
+ number: "D/2026/148",
12
+ status: "open",
13
+ stage: "Proposal sent",
14
+ value: {
15
+ amount: 48500,
16
+ currency: "PLN",
17
+ },
18
+ probability: 60,
19
+ startDate: "2026-09-01",
20
+ endDate: "2026-11-30",
21
+ source: "Website",
22
+ contact: {
23
+ name: "Malina Borkowska",
24
+ restricted: false,
25
+ },
26
+ company: {
27
+ name: null,
28
+ restricted: true,
29
+ },
30
+ createdAt: "2026-09-01T09:15:00+02:00",
31
+ modifiedAt: "2026-09-24T16:40:12+02:00",
32
+ lastActivityAt: "2026-09-26T11:02:47+02:00",
33
+ customId: "CRM-EXT-00148",
34
+ owners: [
35
+ {
36
+ type: "user",
37
+ id: "465912ec-bb4d-14d1-14de-436be62a20ea",
38
+ name: "Kasia Krajewska",
39
+ },
40
+ {
41
+ type: "team",
42
+ id: "7c1d2e3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f",
43
+ name: "Sales North",
44
+ },
45
+ ],
46
+ groups: ["VIP", "Q4 pipeline"],
47
+ customFields: {
48
+ "0f3a9b1e-7c2d-4e8f-a1b2-c3d4e5f60718": {
49
+ name: "Campaign brief",
50
+ type: "textarea",
51
+ value: "Search + display, focus on Q1 2027.\nBudget reviewed monthly.",
52
+ },
53
+ "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d": {
54
+ name: "Contract type",
55
+ type: "select",
56
+ value: "Annual",
57
+ },
58
+ "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e": {
59
+ name: "Channels",
60
+ type: "multiselect",
61
+ value: ["Google Search", "YouTube"],
62
+ },
63
+ "3c4d5e6f-7a8b-4c9d-0e1f-2a3b4c5d6e7f": {
64
+ name: "Priority",
65
+ type: "radio",
66
+ value: "High",
67
+ },
68
+ "4d5e6f7a-8b9c-4d0e-1f2a-3b4c5d6e7f80": {
69
+ name: "NDA signed",
70
+ type: "checkbox",
71
+ value: true,
72
+ },
73
+ "5e6f7a8b-9c0d-4e1f-2a3b-4c5d6e7f8091": {
74
+ name: "Deliverables",
75
+ type: "multicheckbox",
76
+ value: ["Keyword research", "Monthly report"],
77
+ },
78
+ "6f7a8b9c-0d1e-4f2a-3b4c-5d6e7f809102": {
79
+ name: "Monthly budget",
80
+ type: "number",
81
+ value: 12500.5,
82
+ },
83
+ "7a8b9c0d-1e2f-4a3b-4c5d-6e7f80910213": {
84
+ name: "Licences",
85
+ type: "integer",
86
+ value: 25,
87
+ },
88
+ "8b9c0d1e-2f3a-4b4c-5d6e-7f8091021324": {
89
+ name: "Kick-off date",
90
+ type: "date",
91
+ value: "2026-10-15",
92
+ },
93
+ "9c0d1e2f-3a4b-4c5d-6e7f-809102132435": {
94
+ name: "Next review",
95
+ type: "datetime",
96
+ value: "2026-10-05T14:30:00+02:00",
97
+ },
98
+ },
99
+ },
100
+ company: {
101
+ version: 1,
102
+ type: "company",
103
+ id: "9f8f4cdf-5f69-7b40-baa7-137bb9add15a",
104
+ name: "Northwind Holding S.A.",
105
+ taxId: "5252448481",
106
+ regon: "146164297",
107
+ website: "https://northwind.example",
108
+ clientStatus: "Client",
109
+ source: "Website",
110
+ createdAt: "2026-07-13T06:44:58+02:00",
111
+ modifiedAt: "2026-09-20T19:38:23+02:00",
112
+ lastActivityAt: "2026-09-26T11:02:47+02:00",
113
+ customId: "CRM-EXT-C-2031",
114
+ owners: [
115
+ {
116
+ type: "user",
117
+ id: "465912ec-bb4d-14d1-14de-436be62a20ea",
118
+ name: "Kasia Krajewska",
119
+ },
120
+ {
121
+ type: "user",
122
+ id: "b2f4a6c8-1d3e-4f50-9a7b-6c5d4e3f2a10",
123
+ name: "Tomasz Wiśniewski",
124
+ },
125
+ ],
126
+ groups: ["Key accounts", "Retail"],
127
+ customFields: {
128
+ "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f80": {
129
+ name: "Industry",
130
+ type: "select",
131
+ value: "Retail",
132
+ },
133
+ "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8091": {
134
+ name: "Annual ad budget",
135
+ type: "number",
136
+ value: 250000,
137
+ },
138
+ "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f809102": {
139
+ name: "Employees",
140
+ type: "integer",
141
+ value: 420,
142
+ },
143
+ },
144
+ },
145
+ person: {
146
+ version: 1,
147
+ type: "person",
148
+ id: "560e3f92-1b9a-115c-827b-b65ddf7d5774",
149
+ name: "Malina Borkowska",
150
+ firstName: "Malina",
151
+ middleName: null,
152
+ lastName: "Borkowska",
153
+ position: "Marketing Director",
154
+ source: "Phone contact",
155
+ company: {
156
+ name: "Northwind Holding S.A.",
157
+ restricted: false,
158
+ },
159
+ createdAt: "2026-07-08T22:35:15+02:00",
160
+ modifiedAt: "2026-09-22T15:06:18+02:00",
161
+ lastActivityAt: "2026-09-26T11:02:47+02:00",
162
+ customId: null,
163
+ owners: [
164
+ {
165
+ type: "user",
166
+ id: "465912ec-bb4d-14d1-14de-436be62a20ea",
167
+ name: "Kasia Krajewska",
168
+ },
169
+ ],
170
+ groups: ["Decision makers"],
171
+ customFields: {
172
+ "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d": {
173
+ name: "LinkedIn",
174
+ type: "text",
175
+ value: "https://www.linkedin.com/in/malina-borkowska",
176
+ },
177
+ "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e": {
178
+ name: "Newsletter consent",
179
+ type: "checkbox",
180
+ value: false,
181
+ },
182
+ "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f": {
183
+ name: "Birthday",
184
+ type: "date",
185
+ value: "1984-05-17",
186
+ },
187
+ },
188
+ },
189
+ space: {
190
+ version: 1,
191
+ type: "space",
192
+ id: "5776590c-27c9-36da-6b80-62116de30c8b",
193
+ name: "Product ideas",
194
+ number: "S/12",
195
+ description: "Ideas for new products and services we could offer our clients.",
196
+ createdAt: "2026-07-14T11:49:04+02:00",
197
+ modifiedAt: "2026-09-18T18:13:35+02:00",
198
+ lastActivityAt: "2026-09-25T09:41:10+02:00",
199
+ customId: null,
200
+ owners: [
201
+ {
202
+ type: "user",
203
+ id: "b2f4a6c8-1d3e-4f50-9a7b-6c5d4e3f2a10",
204
+ name: "Tomasz Wiśniewski",
205
+ },
206
+ ],
207
+ groups: ["Internal"],
208
+ customFields: {
209
+ "0a1b2c3d-4e5f-4a6b-7c8d-9e0f1a2b3c4d": {
210
+ name: "Status",
211
+ type: "radio",
212
+ value: "In review",
213
+ },
214
+ "1b2c3d4e-5f6a-4b7c-8d9e-0f1a2b3c4d5e": {
215
+ name: "Target quarter",
216
+ type: "select",
217
+ value: "Q1 2027",
218
+ },
219
+ },
220
+ },
221
+ };
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Secret fields on the settings page, as the plugins-2 settings screen does them: the plugin's key
3
+ * set found where Livespace finds it, each field shown by its state, and what's typed sealed in
4
+ * this browser on Save. Only ciphertext leaves the page, and the plaintext is dropped once stored.
5
+ */
6
+ import { computed, signal, } from "@preact/signals";
7
+ import { ISSUE_TEXT, encryptionKeysOf, seal, secretState, } from "./secrets.js";
8
+ /** The line about the keys: where they were found, or why they can't be used. */
9
+ export function describeLookup(lookup) {
10
+ switch (lookup.status) {
11
+ case "found": {
12
+ const kids = encryptionKeysOf(lookup.keySet).map((key) => key.kid);
13
+ return {
14
+ text: `Keys from ${lookup.from}. New secrets are sealed for ${kids[0]}${kids.length > 1 ? `; ${kids.slice(1).join(", ")} still opens older ones` : ""}.`,
15
+ isError: false,
16
+ };
17
+ }
18
+ case "unusable":
19
+ return {
20
+ text: `The keys at ${lookup.from} can't be used: ${ISSUE_TEXT[lookup.issue]}. Livespace would refuse them, so no secret can be saved.`,
21
+ isError: true,
22
+ };
23
+ default:
24
+ return {
25
+ text: `No keys at ${lookup.from}: ${lookup.why}. Livespace couldn't seal a secret for this plugin.`,
26
+ isError: true,
27
+ };
28
+ }
29
+ }
30
+ export class SecretsStore {
31
+ deps;
32
+ #lookup = signal(null);
33
+ #stored;
34
+ #changes = signal({});
35
+ #errors = signal({});
36
+ /** The keys new secrets can be sealed for, newest first. */
37
+ keys;
38
+ /** The line about the keys, once they've been looked for. */
39
+ keysStatus;
40
+ constructor(deps) {
41
+ this.deps = deps;
42
+ this.#stored = deps.stored ?? signal({});
43
+ this.keys = computed(() => {
44
+ const lookup = this.#lookup.value;
45
+ return typeof lookup === "object" && lookup?.status === "found"
46
+ ? encryptionKeysOf(lookup.keySet)
47
+ : [];
48
+ });
49
+ this.keysStatus = computed(() => {
50
+ const lookup = this.#lookup.value;
51
+ if (lookup === null) {
52
+ return null;
53
+ }
54
+ if (lookup === "looking") {
55
+ return { text: "Looking for the plugin's keys…", isError: false };
56
+ }
57
+ return describeLookup(lookup);
58
+ });
59
+ }
60
+ get stored() {
61
+ return this.#stored;
62
+ }
63
+ get changes() {
64
+ return this.#changes;
65
+ }
66
+ get errors() {
67
+ return this.#errors;
68
+ }
69
+ /** Whether the keys have been looked for yet. */
70
+ get checked() {
71
+ return this.#lookup.peek() !== null;
72
+ }
73
+ /** Each field's state: unset, set under a listed key, or to enter again. */
74
+ stateOf(key) {
75
+ return secretState(key, this.#stored.value, this.keys.value);
76
+ }
77
+ async loadStored() {
78
+ this.#stored.value = await this.deps.api.secrets();
79
+ }
80
+ /** Looks for the plugin's keys, again on "Check again". */
81
+ checkKeys = async () => {
82
+ this.#lookup.value = "looking";
83
+ this.#lookup.value = await this.deps.lookUp();
84
+ };
85
+ replace = (key) => {
86
+ this.#change(key, { kind: "replace", value: "" });
87
+ };
88
+ type = (key, value) => {
89
+ this.#change(key, { kind: "replace", value });
90
+ };
91
+ clear = (key) => {
92
+ this.#change(key, { kind: "clear" });
93
+ };
94
+ /** Back to what's stored: undoes a Replace or a Clear. */
95
+ undo = (key) => {
96
+ this.#change(key, undefined);
97
+ };
98
+ #change(key, change) {
99
+ const changes = { ...this.#changes.value };
100
+ if (change === undefined) {
101
+ delete changes[key];
102
+ }
103
+ else {
104
+ changes[key] = change;
105
+ }
106
+ this.#changes.value = changes;
107
+ }
108
+ /** A required secret needs a value now, or one stored under a listed key and not cleared. */
109
+ validate(fields) {
110
+ const errors = {};
111
+ for (const field of fields) {
112
+ if (!field.required) {
113
+ continue;
114
+ }
115
+ const change = this.#changes.value[field.key];
116
+ const typed = change?.kind === "replace" && change.value.trim() !== "";
117
+ const kept = this.stateOf(field.key) === "set" && change?.kind !== "clear";
118
+ if (!typed && !kept) {
119
+ errors[field.key] = "Required.";
120
+ }
121
+ }
122
+ this.#errors.value = errors;
123
+ return Object.keys(errors).length === 0;
124
+ }
125
+ /**
126
+ * Seals what's typed for the first encryption key and stores it with the clears. Sends only
127
+ * what changes something, as plugins-2 does. `iss` is the account the secret belongs to. The
128
+ * number of secrets stored or cleared.
129
+ */
130
+ async save(fields, iss) {
131
+ const declared = new Set(fields.map((field) => field.key));
132
+ const sealed = {};
133
+ for (const [key, change] of Object.entries(this.#changes.value)) {
134
+ if (!declared.has(key)) {
135
+ continue;
136
+ }
137
+ if (change.kind === "clear") {
138
+ if (this.#stored.value[key] !== undefined) {
139
+ sealed[key] = null;
140
+ }
141
+ continue;
142
+ }
143
+ if (change.value.trim() === "") {
144
+ continue;
145
+ }
146
+ const current = this.keys.value[0];
147
+ if (current === undefined) {
148
+ throw new Error("No encryption key to seal the secrets for: see the line about keys above.");
149
+ }
150
+ sealed[key] = await seal({ iss, key, value: change.value }, current);
151
+ }
152
+ if (Object.keys(sealed).length === 0) {
153
+ return 0;
154
+ }
155
+ this.#stored.value = await this.deps.api.storeSecrets(sealed);
156
+ this.#changes.value = {};
157
+ return Object.keys(sealed).length;
158
+ }
159
+ }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Secret fields as the plugins-2 settings screen handles them: the plugin's key set checked the
3
+ * same way, each secret sealed in the browser as a compact JWE for the plugin's backend, and each
4
+ * field's state. Ported from ls-fe plugins-2 (`domain/entities/public-keys.ts`,
5
+ * `domain/entities/plugin-secrets.ts`, `data/crypto/web-crypto-secret-sealer.ts`).
6
+ */
7
+ const MIN_RSA_BITS = 2048;
8
+ const MAX_KEYS_PER_USE = 2;
9
+ const ALG_BY_USE = { sig: "RS256", enc: "RSA-OAEP-256" };
10
+ /** Members only a private RSA JWK has. */
11
+ const PRIVATE_MEMBERS = ["d", "p", "q", "dp", "dq", "qi", "oth"];
12
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13
+ const nonEmpty = (value) => typeof value === "string" && value !== "";
14
+ /** The modulus length in bits, from its base64url form. */
15
+ const modulusBits = (n) => Math.floor((n.length * 6) / 8) * 8;
16
+ function readKey(raw) {
17
+ if (!isRecord(raw)) {
18
+ return "invalidKey";
19
+ }
20
+ if (PRIVATE_MEMBERS.some((member) => member in raw)) {
21
+ return "privateKey";
22
+ }
23
+ const { kty, kid, use, alg, n, e } = raw;
24
+ if (kty !== "RSA" ||
25
+ !nonEmpty(kid) ||
26
+ (use !== "sig" && use !== "enc") ||
27
+ (alg !== undefined && alg !== ALG_BY_USE[use]) ||
28
+ !nonEmpty(n) ||
29
+ !nonEmpty(e)) {
30
+ return "invalidKey";
31
+ }
32
+ if (modulusBits(n) < MIN_RSA_BITS) {
33
+ return "keyTooShort";
34
+ }
35
+ return { kty, kid, use, ...(typeof alg === "string" ? { alg } : {}), n, e };
36
+ }
37
+ /** A key set, checked as plugins-2 checks one published by a plugin added by URL. */
38
+ export function readKeySet(value) {
39
+ if (!isRecord(value) ||
40
+ !Array.isArray(value.keys) ||
41
+ value.keys.length === 0) {
42
+ return { ok: false, issue: "notKeySet" };
43
+ }
44
+ const keys = [];
45
+ for (const raw of value.keys) {
46
+ const key = readKey(raw);
47
+ if (typeof key === "string") {
48
+ return { ok: false, issue: key };
49
+ }
50
+ if (keys.some((other) => other.kid === key.kid)) {
51
+ return { ok: false, issue: "duplicateKid" };
52
+ }
53
+ keys.push(key);
54
+ }
55
+ const count = (use) => keys.filter((key) => key.use === use).length;
56
+ if (count("sig") === 0) {
57
+ return { ok: false, issue: "missingSigningKey" };
58
+ }
59
+ if (count("enc") === 0) {
60
+ return { ok: false, issue: "missingEncryptionKey" };
61
+ }
62
+ if (count("sig") > MAX_KEYS_PER_USE || count("enc") > MAX_KEYS_PER_USE) {
63
+ return { ok: false, issue: "tooManyKeys" };
64
+ }
65
+ return { ok: true, keySet: { keys } };
66
+ }
67
+ export function parseKeySet(text) {
68
+ try {
69
+ return readKeySet(JSON.parse(text));
70
+ }
71
+ catch {
72
+ return { ok: false, issue: "notJson" };
73
+ }
74
+ }
75
+ export const ISSUE_TEXT = {
76
+ notJson: "it isn't JSON",
77
+ notKeySet: 'it isn\'t a key set: { "keys": [...] } with at least one key',
78
+ invalidKey: "a key isn't an RSA public key with a kid, a use of sig or enc, and a matching alg",
79
+ privateKey: "it holds a private key. Publish only the public halves",
80
+ duplicateKid: "two keys share a kid",
81
+ keyTooShort: "a key is shorter than 2048 bits",
82
+ missingSigningKey: "it has no signing key (use: sig)",
83
+ missingEncryptionKey: "it has no encryption key (use: enc)",
84
+ tooManyKeys: "it has more than two keys of one use",
85
+ };
86
+ /** The encryption keys, newest first, as listed. New secrets use the first. */
87
+ export const encryptionKeysOf = (keySet) => keySet.keys
88
+ .filter((key) => key.use === "enc")
89
+ .map(({ kid, n, e }) => ({ kid, n, e }));
90
+ export function secretState(key, stored, keys) {
91
+ const entry = stored[key];
92
+ if (entry === undefined) {
93
+ return "unset";
94
+ }
95
+ return keys.some((candidate) => candidate.kid === entry.kid)
96
+ ? "set"
97
+ : "reenter";
98
+ }
99
+ const encoder = new TextEncoder();
100
+ const base64Url = (bytes) => {
101
+ let binary = "";
102
+ for (const byte of bytes) {
103
+ binary += String.fromCharCode(byte);
104
+ }
105
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
106
+ };
107
+ /** AES-GCM's tag length, in bytes. Web Crypto appends it to the ciphertext. */
108
+ const TAG_BYTES = 16;
109
+ /**
110
+ * A secret as a compact JWE, RSA-OAEP-256 + A256GCM, exactly as an admin's browser seals it: a
111
+ * fresh content key encrypts the plaintext, authenticating the protected header, and RSA-OAEP
112
+ * wraps the content key for the plugin's public key.
113
+ */
114
+ export async function seal(plaintext, key) {
115
+ const header = base64Url(encoder.encode(JSON.stringify({ alg: "RSA-OAEP-256", enc: "A256GCM", kid: key.kid })));
116
+ const wrappingKey = await crypto.subtle.importKey("jwk", { kty: "RSA", n: key.n, e: key.e, alg: "RSA-OAEP-256", ext: true }, { name: "RSA-OAEP", hash: "SHA-256" }, false, ["encrypt"]);
117
+ const contentKey = crypto.getRandomValues(new Uint8Array(32));
118
+ const iv = crypto.getRandomValues(new Uint8Array(12));
119
+ const aesKey = await crypto.subtle.importKey("raw", contentKey, { name: "AES-GCM" }, false, ["encrypt"]);
120
+ const encryptedKey = new Uint8Array(await crypto.subtle.encrypt({ name: "RSA-OAEP" }, wrappingKey, contentKey));
121
+ const sealed = new Uint8Array(await crypto.subtle.encrypt({
122
+ name: "AES-GCM",
123
+ iv,
124
+ additionalData: encoder.encode(header),
125
+ tagLength: TAG_BYTES * 8,
126
+ }, aesKey, encoder.encode(JSON.stringify(plaintext))));
127
+ contentKey.fill(0);
128
+ return [
129
+ header,
130
+ base64Url(encryptedKey),
131
+ base64Url(iv),
132
+ base64Url(sealed.slice(0, sealed.length - TAG_BYTES)),
133
+ base64Url(sealed.slice(sealed.length - TAG_BYTES)),
134
+ ].join(".");
135
+ }