@colixsystems/widget-sdk 0.339.0 → 0.341.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.
@@ -0,0 +1,620 @@
1
+ // Validation for a manifest's `connectorTemplates` — the REST connectors an
2
+ // Action or a widget ships PREFILLED and the installing workspace gets created
3
+ // for it. One validator for both kinds (sc-17829); a widget's template also
4
+ // lists the `appOperations` the widget calls, an Action's never does.
5
+ //
6
+ // The author knows everything about the upstream API except the workspace's own
7
+ // credential: the base URL, which auth scheme it speaks, its OAuth endpoints,
8
+ // the scope string, the headers it insists on. `connectorRef` (the property
9
+ // type) lets an Action *require* a connector; this lets it *ship* one, so an
10
+ // operator's whole job is pasting their secret.
11
+ //
12
+ // The rule that shapes everything here: **a manifest may never carry credential
13
+ // material.** It is reviewed once and then shipped to every workspace, so an
14
+ // author-supplied token would be a shared credential in a file the author hands
15
+ // out. Refused as a publish error rather than stripped — an author who put a
16
+ // secret in a manifest has misunderstood the model and must be told.
17
+ //
18
+ // A token request header or parameter that carries a credential (a
19
+ // subscription key) is declared secret by NAME in `secret_token_extra_headers`
20
+ // / `secret_token_extra_params`; the value is the workspace's to enter, so a
21
+ // manifest naming one in the value map too is refused (sc-12193).
22
+ //
23
+ // `missingCredentialFields` is the other half, and lives here because it is
24
+ // derived from the SAME contract table: the fields the operator still owes.
25
+ // The backend reads it to refuse a call on a connector nobody has finished
26
+ // setting up, so "incomplete" is derived from the auth config rather than
27
+ // stored in a column that could drift out of sync with it (sc-6352).
28
+
29
+ "use strict";
30
+
31
+ const DATA = require("./connector-template-data.json");
32
+ const { validateAppOperations } = require("./connector-app-operations.cjs");
33
+ const { isCredentialEntry } = require("./connector-credential-entry.cjs");
34
+
35
+ /** Freeze `value` and everything it holds. */
36
+ const deepFreeze = (value) =>
37
+ value === null || typeof value !== "object" || Object.isFrozen(value)
38
+ ? value
39
+ : Object.freeze(Object.values(value).reduce((frozen, v) => (deepFreeze(v), frozen), value));
40
+
41
+ /** The shared connector-template contract; each SDK spreads it into its CONTRACT. */
42
+ const CONNECTOR_CONTRACT = deepFreeze(
43
+ Object.fromEntries([
44
+ ...Object.entries(DATA).filter(([key]) => !key.startsWith("_")),
45
+ ["connectorTemplateKeyPattern", new RegExp(DATA.connectorTemplateKeyPattern)],
46
+ ]),
47
+ );
48
+ const CONTRACT = CONNECTOR_CONTRACT;
49
+
50
+ function isPlainObject(value) {
51
+ return value !== null && typeof value === "object" && !Array.isArray(value);
52
+ }
53
+
54
+ /** The manifest kinds that declare templates. */
55
+ const TEMPLATE_KINDS = Object.freeze(["action", "widget"]);
56
+
57
+ const VALID_AUTH_TYPES = new Set(CONTRACT.connectorAuthTypes);
58
+
59
+ // A stable, manifest-local identifier. It is half the idempotency key that
60
+ // keeps a re-install from provisioning a second connector beside the one
61
+ // holding the operator's credential, so it is as tight as a translation key.
62
+ const TEMPLATE_KEY_RE = CONTRACT.connectorTemplateKeyPattern;
63
+
64
+ // RFC 7230 field-name token and the field-value characters `fetch` refuses.
65
+ // Mirrors the backend connector service's own header rules so a manifest that
66
+ // lints clean cannot be refused at provisioning time.
67
+ const HEADER_NAME_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
68
+ const HEADER_VALUE_FORBIDDEN_RE = /[\r\n\0]/;
69
+ // A token request form-parameter name; mirrors the backend's save-time rule.
70
+ const FORM_PARAM_NAME_RE = /^[A-Za-z0-9_.-]+$/;
71
+
72
+ const MAX_NAME_LENGTH = CONTRACT.connectorTemplateNameMaxLength;
73
+ const MAX_HEADERS = CONTRACT.connectorTemplateMaxHeaders;
74
+ const MAX_DESCRIPTION_LENGTH = CONTRACT.connectorTemplateDescriptionMaxLength;
75
+
76
+ // authConfig keys the backend interprets. Anything else is refused rather than
77
+ // passed through: the connector service reads this blob field by field, so an
78
+ // unknown key is either a typo the author wants to hear about or an attempt to
79
+ // reach a field that is not the manifest's to set.
80
+ const ALLOWED_AUTH_CONFIG_KEYS = CONTRACT.connectorAuthConfigKeys;
81
+
82
+ const TEMPLATE_FIELDS = new Set(CONTRACT.connectorTemplateFields.map((f) => f.name));
83
+
84
+ // List key -> the token-request map its secret entries' values live in.
85
+ const SECRET_TOKEN_EXTRAS = CONTRACT.connectorSecretTokenExtras;
86
+
87
+ // The URL-shaped authConfig keys, checked for syntax and scheme here. Whether
88
+ // the host is publicly routable is the backend's question — only it can resolve
89
+ // DNS — so the publish-time analyzer re-checks these through the SSRF guard.
90
+ const URL_AUTH_CONFIG_KEYS = Object.freeze(["token_url", "authorize_url"]);
91
+
92
+ function isNonEmptyString(v) {
93
+ return typeof v === "string" && v.length > 0;
94
+ }
95
+
96
+ /** An http(s) absolute URL. Scheme and syntax only — see URL_AUTH_CONFIG_KEYS. */
97
+ function isHttpUrl(value) {
98
+ if (typeof value !== "string" || !value.trim()) return false;
99
+ let parsed;
100
+ try {
101
+ parsed = new URL(value.trim());
102
+ } catch {
103
+ return false;
104
+ }
105
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
106
+ }
107
+
108
+ /**
109
+ * The authConfig keys a manifest may never carry for this auth type.
110
+ * @param {unknown} authType
111
+ * @returns {string[]}
112
+ */
113
+ function connectorSecretFields(authType) {
114
+ const fields = CONTRACT.connectorSecretFields[String(authType)];
115
+ return Array.isArray(fields) ? [...fields] : [];
116
+ }
117
+
118
+ /**
119
+ * The authConfig keys the installing workspace must supply before this
120
+ * connector can be called — its own credential, plus the non-secret identifiers
121
+ * only it can know (an OAuth `client_id`, a `basic` username).
122
+ *
123
+ * `authConfig` is optional and consulted only for a `token_auth_method` that
124
+ * changes WHICH credential is owed: `private_key_jwt` owes a signing key, not
125
+ * a shared secret.
126
+ * @param {unknown} authType
127
+ * @param {unknown} [authConfig]
128
+ * @returns {string[]}
129
+ */
130
+ function connectorOperatorFields(authType, authConfig) {
131
+ const method = isPlainObject(authConfig) ? authConfig.token_auth_method : undefined;
132
+ const variant = CONTRACT.connectorOperatorFieldsByAuthMethod[String(method)];
133
+ const fields = (variant && variant[String(authType)])
134
+ || CONTRACT.connectorOperatorFields[String(authType)];
135
+ return Array.isArray(fields) ? [...fields] : [];
136
+ }
137
+
138
+ /**
139
+ * Every authConfig key the INSTALLING workspace owns for this auth type —
140
+ * across EVERY token_auth_method, not just the default one.
141
+ *
142
+ * Distinct from `missingCredentialFields`, which answers "what is absent from
143
+ * this one config". A credential STRIP needs the whole set: a private_key_jwt
144
+ * connector owes a signing key the default variant never lists, so stripping
145
+ * the default's view would carry that key into another workspace.
146
+ * @param {unknown} authType
147
+ * @returns {string[]}
148
+ */
149
+ function connectorWorkspaceOwnedFields(authType) {
150
+ const owned = new Set([
151
+ ...connectorSecretFields(authType),
152
+ ...connectorOperatorFields(authType),
153
+ ]);
154
+ for (const byType of Object.values(CONTRACT.connectorOperatorFieldsByAuthMethod)) {
155
+ for (const field of byType[String(authType)] || []) owned.add(field);
156
+ }
157
+ return [...owned];
158
+ }
159
+
160
+ function isFilled(value) {
161
+ return typeof value === "string" && value.trim().length > 0;
162
+ }
163
+
164
+ /**
165
+ * The token-request entries this config declares secret, for an auth type
166
+ * that takes them. `field` is the entry's name in the owed list.
167
+ * @param {unknown} authType
168
+ * @param {unknown} authConfig
169
+ * @returns {Array<{ list: string, map: string, name: string, field: string }>}
170
+ */
171
+ function connectorSecretTokenEntries(authType, authConfig) {
172
+ if (!isPlainObject(authConfig)) return [];
173
+ const type = String(authType);
174
+ const allowed = Object.hasOwn(ALLOWED_AUTH_CONFIG_KEYS, type) ? ALLOWED_AUTH_CONFIG_KEYS[type] : [];
175
+ const entries = [];
176
+ for (const [list, map] of Object.entries(SECRET_TOKEN_EXTRAS)) {
177
+ const names = authConfig[list];
178
+ if (!allowed.includes(list) || !Array.isArray(names)) continue;
179
+ for (const name of new Set(names)) {
180
+ if (isNonEmptyString(name)) entries.push({ list, map, name, field: `${map}.${name}` });
181
+ }
182
+ }
183
+ return entries;
184
+ }
185
+
186
+ /**
187
+ * Why this list of secret entry names cannot be stored, or null when it can.
188
+ * The one rule, read by this validator and by the backend's save path.
189
+ * @param {string} list a key of `CONTRACT.connectorSecretTokenExtras`
190
+ * @param {unknown} names
191
+ * @returns {string|null}
192
+ */
193
+ function connectorSecretTokenNamesRefusal(list, names) {
194
+ const map = Object.hasOwn(SECRET_TOKEN_EXTRAS, list) ? SECRET_TOKEN_EXTRAS[list] : null;
195
+ if (!map) return "is not a secret entry list";
196
+ if (!Array.isArray(names)) return "must be an array of names";
197
+ if (names.length > MAX_HEADERS) return `may name at most ${MAX_HEADERS} entries`;
198
+ const isHeader = map === "token_extra_headers";
199
+ const seen = new Set();
200
+ for (const name of names) {
201
+ if (typeof name !== "string" || !(isHeader ? HEADER_NAME_RE : FORM_PARAM_NAME_RE).test(name)) {
202
+ return `"${String(name)}" is not a valid name`;
203
+ }
204
+ // Header names are case-insensitive on the wire.
205
+ const key = isHeader ? name.toLowerCase() : name;
206
+ if (seen.has(key)) return `"${name}" is listed twice`;
207
+ seen.add(key);
208
+ if (!isHeader && CONTRACT.connectorReservedTokenParams.includes(name)) {
209
+ return `"${name}" is set by the token request itself`;
210
+ }
211
+ }
212
+ return null;
213
+ }
214
+
215
+ /**
216
+ * What a connector still needs before it can call anything: the operator fields
217
+ * its auth type requires that hold no value yet, then each secret token entry
218
+ * still without one (`token_extra_headers.<name>`).
219
+ *
220
+ * The ONE definition of "incomplete", read by the connector service's call
221
+ * guard, its read projection, and the installed-action view's notice. Derived
222
+ * from the auth config rather than stored, so it cannot disagree with the
223
+ * credentials actually present (sc-6352).
224
+ *
225
+ * @param {unknown} authType
226
+ * @param {unknown} authConfig
227
+ * @returns {string[]} field names, in contract order; empty when ready.
228
+ */
229
+ function missingCredentialFields(authType, authConfig) {
230
+ const cfg = isPlainObject(authConfig) ? authConfig : {};
231
+ const fields = connectorOperatorFields(authType, cfg).filter((field) => !isFilled(cfg[field]));
232
+ const entries = connectorSecretTokenEntries(authType, cfg)
233
+ .filter(({ map, name }) => {
234
+ const values = isPlainObject(cfg[map]) ? cfg[map] : {};
235
+ return !Object.hasOwn(values, name) || !isFilled(values[name]);
236
+ })
237
+ .map(({ field }) => field);
238
+ return [...fields, ...entries];
239
+ }
240
+
241
+ function validateHeaderMap(headers, path, errors) {
242
+ if (!isPlainObject(headers)) {
243
+ errors.push(`${path}: must be an object of header name -> string`);
244
+ return;
245
+ }
246
+ const names = Object.keys(headers);
247
+ if (names.length > MAX_HEADERS) {
248
+ errors.push(`${path}: may declare at most ${MAX_HEADERS} headers`);
249
+ }
250
+ for (const name of names) {
251
+ if (!HEADER_NAME_RE.test(name)) {
252
+ errors.push(`${path}: "${name}" is not a valid header name`);
253
+ continue;
254
+ }
255
+ const value = headers[name];
256
+ if (typeof value !== "string") {
257
+ errors.push(`${path}["${name}"]: must be a string`);
258
+ } else if (HEADER_VALUE_FORBIDDEN_RE.test(value)) {
259
+ errors.push(`${path}["${name}"]: must not contain CR, LF or NUL`);
260
+ }
261
+ }
262
+ }
263
+
264
+ // A secret entry is named, never valued: the value is the installing
265
+ // workspace's credential, so naming it in the value map too is the error.
266
+ function validateSecretTokenNames(authConfig, path, errors) {
267
+ for (const [list, map] of Object.entries(SECRET_TOKEN_EXTRAS)) {
268
+ const names = authConfig[list];
269
+ if (names === undefined) continue;
270
+ const refusal = connectorSecretTokenNamesRefusal(list, names);
271
+ if (refusal) {
272
+ errors.push(`${path}.${list}: ${refusal}`);
273
+ continue;
274
+ }
275
+ const valued = new Set(Object.keys(isPlainObject(authConfig[map]) ? authConfig[map] : {}));
276
+ const fold = (name) => (map === "token_extra_headers" ? name.toLowerCase() : name);
277
+ const valuedFolded = new Set([...valued].map(fold));
278
+ for (const name of names) {
279
+ if (valuedFolded.has(fold(name))) {
280
+ errors.push(
281
+ `${path}.${map}["${name}"]: a secret entry carries no value in a manifest — name it only in ${list}; the installing workspace enters it`,
282
+ );
283
+ }
284
+ }
285
+ }
286
+ }
287
+
288
+ // RFC 6749 §A.10: a grant_type is a bare grant-name or a URI. Deliberately
289
+ // narrower than an encoder would tolerate — a stray space is a typo, not a
290
+ // provider's real grant. `%` is excluded: no real grant URN needs escaping.
291
+ const GRANT_TYPE_RE = /^[A-Za-z0-9._~:/?#[\]@!$&'()*+,;=-]{1,128}$/;
292
+
293
+ /** The grant a client-credentials connector requests when none is configured. */
294
+ function connectorDefaultGrantType() {
295
+ return CONTRACT.connectorDefaultGrantType;
296
+ }
297
+
298
+ /**
299
+ * Why this grant cannot be requested, or null when it can.
300
+ *
301
+ * The one rule, read by this SDK's template validator and by the backend that
302
+ * builds the token request, so a grant accepted at save time is always one the
303
+ * request can actually satisfy.
304
+ * @param {unknown} grantType
305
+ * @returns {string|null}
306
+ */
307
+ function connectorGrantTypeRefusal(grantType) {
308
+ if (typeof grantType !== "string" || !grantType.trim()) return "must be a non-empty string";
309
+ const value = grantType.trim();
310
+ if (!GRANT_TYPE_RE.test(value)) return "is not a valid grant type";
311
+ if (CONTRACT.connectorUnbuildableGrantTypes.includes(value)) {
312
+ return `needs a per-request credential this connector does not mint (refused: ${CONTRACT.connectorUnbuildableGrantTypes.join(", ")})`;
313
+ }
314
+ return null;
315
+ }
316
+
317
+ function validateAuthConfig(authType, authConfig, path, errors) {
318
+ if (authConfig === undefined) {
319
+ return;
320
+ }
321
+ if (!isPlainObject(authConfig)) {
322
+ errors.push(`${path}: must be an object`);
323
+ return;
324
+ }
325
+
326
+ // The security gate, first and unconditionally: a credential in a manifest is
327
+ // a credential in every workspace that installs it.
328
+ for (const field of connectorSecretFields(authType)) {
329
+ if (authConfig[field] !== undefined) {
330
+ errors.push(
331
+ `${path}.${field}: a manifest must not carry credential material — the installing workspace supplies it`,
332
+ );
333
+ }
334
+ }
335
+
336
+ const allowed = ALLOWED_AUTH_CONFIG_KEYS[String(authType)];
337
+ if (!Array.isArray(allowed)) return; // unknown authType already reported
338
+ const secrets = new Set(connectorSecretFields(authType));
339
+ for (const key of Object.keys(authConfig)) {
340
+ if (secrets.has(key)) continue; // reported above; do not double-report
341
+ if (!allowed.includes(key)) {
342
+ errors.push(
343
+ `${path}.${key}: not a prefillable field for authType "${authType}" (allowed: ${allowed.join(", ") || "none"})`,
344
+ );
345
+ }
346
+ }
347
+
348
+ for (const key of URL_AUTH_CONFIG_KEYS) {
349
+ if (authConfig[key] !== undefined && !isHttpUrl(authConfig[key])) {
350
+ errors.push(`${path}.${key}: must be an absolute http(s) URL`);
351
+ }
352
+ }
353
+
354
+ // Enums the backend also enforces. Checked here so a typo is a publish error
355
+ // in the author's terminal rather than a failed install in a workspace.
356
+ if (authConfig.pkce !== undefined && authConfig.pkce !== "S256" && authConfig.pkce !== "none") {
357
+ errors.push(`${path}.pkce: must be "S256" or "none"`);
358
+ }
359
+ if (authConfig.grant_type !== undefined) {
360
+ const refusal = connectorGrantTypeRefusal(authConfig.grant_type);
361
+ if (refusal) errors.push(`${path}.grant_type: ${refusal}`);
362
+ }
363
+ if (
364
+ authConfig.token_auth_method !== undefined &&
365
+ !CONTRACT.connectorTokenAuthMethods.includes(authConfig.token_auth_method)
366
+ ) {
367
+ errors.push(
368
+ `${path}.token_auth_method: must be one of ${CONTRACT.connectorTokenAuthMethods.join(", ")}`,
369
+ );
370
+ }
371
+ if (
372
+ authConfig.post_consent_mint !== undefined &&
373
+ authConfig.post_consent_mint !== "refresh_token" &&
374
+ authConfig.post_consent_mint !== "client_credentials"
375
+ ) {
376
+ errors.push(`${path}.post_consent_mint: must be "refresh_token" or "client_credentials"`);
377
+ }
378
+ for (const key of ["scope", "audience", "provider_id", "account_id_source"]) {
379
+ if (authConfig[key] !== undefined && typeof authConfig[key] !== "string") {
380
+ errors.push(`${path}.${key}: must be a string when present`);
381
+ }
382
+ }
383
+ for (const key of ["token_extra_headers", "token_extra_params"]) {
384
+ if (authConfig[key] !== undefined) validateHeaderMap(authConfig[key], `${path}.${key}`, errors);
385
+ }
386
+ if (isPlainObject(authConfig.token_extra_params)) {
387
+ for (const name of Object.keys(authConfig.token_extra_params)) {
388
+ if (CONTRACT.connectorReservedTokenParams.includes(name)) {
389
+ errors.push(`${path}.token_extra_params["${name}"]: the token request sets this parameter itself`);
390
+ }
391
+ }
392
+ }
393
+ validateSecretTokenNames(authConfig, path, errors);
394
+
395
+ // An authorization-code connector without its endpoints is unusable, and the
396
+ // operator has no way to discover them — the author does. Required here for
397
+ // the same reason the backend requires them: a connector that cannot start
398
+ // consent is worse than one that was never provisioned.
399
+ if (authType === "oauth2_authorization_code") {
400
+ if (authConfig.authorize_url === undefined) {
401
+ errors.push(`${path}.authorize_url: required for authType "oauth2_authorization_code"`);
402
+ }
403
+ if (authConfig.token_url === undefined) {
404
+ errors.push(`${path}.token_url: required for authType "oauth2_authorization_code"`);
405
+ }
406
+ }
407
+ if (authType === "oauth2_client_credentials" && authConfig.token_url === undefined) {
408
+ errors.push(`${path}.token_url: required for authType "oauth2_client_credentials"`);
409
+ }
410
+ }
411
+
412
+ // A widget calls its connector only through listed operations, so its template
413
+ // must list them and is provisioned app-callable; an Action's script calls the
414
+ // connector server-side and never takes them.
415
+ function validateTemplateOperations(template, kind, path, errors) {
416
+ if (kind !== "widget") {
417
+ if (template.appOperations !== undefined) {
418
+ errors.push(`${path}.appOperations: only a widget's connector template lists app operations`);
419
+ }
420
+ return;
421
+ }
422
+ if (!Array.isArray(template.appOperations) || template.appOperations.length === 0) {
423
+ errors.push(`${path}.appOperations: a widget's connector template must list the operations the widget calls`);
424
+ return;
425
+ }
426
+ try {
427
+ validateAppOperations(template.appOperations);
428
+ } catch (err) {
429
+ errors.push(`${path}.appOperations: ${String(err.message).replace(/^INVALID_APP_OPERATIONS: /, "invalid ")}`);
430
+ }
431
+ }
432
+
433
+ // Default headers reach every installing workspace and every app reading the
434
+ // manifest, so one that carries a credential would be a shared credential.
435
+ function validateNoCredentialHeaders(headers, path, errors) {
436
+ if (!isPlainObject(headers)) return;
437
+ for (const [name, value] of Object.entries(headers)) {
438
+ if (isCredentialEntry(name, value)) {
439
+ errors.push(
440
+ `${path}["${name}"]: a manifest must not carry credential material — send a key with authType "apiKey" and its header_name, and the installing workspace supplies it`,
441
+ );
442
+ }
443
+ }
444
+ }
445
+
446
+ function validateTemplate(template, path, errors, seenKeys, kind) {
447
+ if (!isPlainObject(template)) {
448
+ errors.push(`${path}: must be an object`);
449
+ return;
450
+ }
451
+
452
+ if (!isNonEmptyString(template.key)) {
453
+ errors.push(`${path}.key: must be a non-empty string`);
454
+ } else if (!TEMPLATE_KEY_RE.test(template.key)) {
455
+ errors.push(`${path}.key: must match /${TEMPLATE_KEY_RE.source}/`);
456
+ } else if (seenKeys.has(template.key)) {
457
+ errors.push(`${path}.key: "${template.key}" is duplicated`);
458
+ } else {
459
+ seenKeys.add(template.key);
460
+ }
461
+
462
+ if (!isNonEmptyString(template.name)) {
463
+ errors.push(`${path}.name: must be a non-empty string`);
464
+ } else if (template.name.length > MAX_NAME_LENGTH) {
465
+ errors.push(`${path}.name: must be at most ${MAX_NAME_LENGTH} characters`);
466
+ }
467
+
468
+ if (!isHttpUrl(template.baseUrl)) {
469
+ errors.push(`${path}.baseUrl: must be an absolute http(s) URL`);
470
+ }
471
+
472
+ const authType = template.authType === undefined ? "none" : template.authType;
473
+ if (!VALID_AUTH_TYPES.has(authType)) {
474
+ errors.push(
475
+ `${path}.authType: invalid type "${template.authType}" (one of ${CONTRACT.connectorAuthTypes.join(", ")})`,
476
+ );
477
+ }
478
+
479
+ if (template.description !== undefined) {
480
+ if (typeof template.description !== "string") {
481
+ errors.push(`${path}.description: must be a string when present`);
482
+ } else if (template.description.length > MAX_DESCRIPTION_LENGTH) {
483
+ errors.push(`${path}.description: must be at most ${MAX_DESCRIPTION_LENGTH} characters`);
484
+ }
485
+ }
486
+
487
+ if (template.defaultHeaders !== undefined) {
488
+ validateHeaderMap(template.defaultHeaders, `${path}.defaultHeaders`, errors);
489
+ }
490
+
491
+ validateAuthConfig(authType, template.authConfig, `${path}.authConfig`, errors);
492
+ validateTemplateOperations(template, kind, path, errors);
493
+ validateNoCredentialHeaders(template.defaultHeaders, `${path}.defaultHeaders`, errors);
494
+
495
+ for (const field of Object.keys(template)) {
496
+ if (!TEMPLATE_FIELDS.has(field)) {
497
+ errors.push(`${path}.${field}: unknown field`);
498
+ }
499
+ }
500
+ }
501
+
502
+ function kindOf(options) {
503
+ const kind = options && options.kind !== undefined ? options.kind : "action";
504
+ if (!TEMPLATE_KINDS.includes(kind)) throw new Error(`unknown connector template kind "${kind}"`);
505
+ return kind;
506
+ }
507
+
508
+ /**
509
+ * Validate a manifest's `connectorTemplates`.
510
+ * @param {unknown} templates
511
+ * @param {{ kind?: "action" | "widget" }} [options] the manifest's kind; default "action".
512
+ * @returns {{ ok: true } | { ok: false, errors: string[] }}
513
+ */
514
+ function validateConnectorTemplates(templates, options) {
515
+ const kind = kindOf(options);
516
+ if (templates === undefined || templates === null) return { ok: true };
517
+ const errors = [];
518
+ if (!Array.isArray(templates)) {
519
+ return { ok: false, errors: ["manifest.connectorTemplates: must be an array"] };
520
+ }
521
+ if (templates.length > CONTRACT.connectorTemplatesMax) {
522
+ errors.push(
523
+ `manifest.connectorTemplates: may declare at most ${CONTRACT.connectorTemplatesMax} connectors`,
524
+ );
525
+ }
526
+ const seenKeys = new Set();
527
+ templates.forEach((template, i) => {
528
+ validateTemplate(template, `manifest.connectorTemplates[${i}]`, errors, seenKeys, kind);
529
+ });
530
+ return errors.length === 0 ? { ok: true } : { ok: false, errors };
531
+ }
532
+
533
+ /**
534
+ * The templates a manifest declares, filtered to the well-formed ones.
535
+ *
536
+ * Re-filters rather than trusting the stored manifest: a row written before a
537
+ * rule existed must not reach the provisioner, which creates real connectors.
538
+ * @param {unknown} manifest
539
+ * @param {{ kind?: "action" | "widget" }} [options]
540
+ * @returns {Array<Record<string, unknown>>}
541
+ */
542
+ function connectorTemplatesOf(manifest, options) {
543
+ const kind = kindOf(options);
544
+ const raw = isPlainObject(manifest) ? manifest.connectorTemplates : null;
545
+ if (!Array.isArray(raw)) return [];
546
+ const seenKeys = new Set();
547
+ return raw.filter((template) => {
548
+ const errors = [];
549
+ validateTemplate(template, "template", errors, seenKeys, kind);
550
+ return errors.length === 0;
551
+ });
552
+ }
553
+
554
+ const CONNECTOR_CALL_SCOPE = "connectors.call:*";
555
+
556
+ /**
557
+ * A widget manifest's connector errors: its templates, the scope that calls
558
+ * them, and each `connectorRef` property's `template` binding. The ONE check
559
+ * read by `appstudio-widget lint` and the publish analyzer (sc-17829).
560
+ * @param {unknown} manifest
561
+ * @returns {string[]}
562
+ */
563
+ function widgetConnectorTemplateErrors(manifest) {
564
+ if (!isPlainObject(manifest)) return [];
565
+ const result = validateConnectorTemplates(manifest.connectorTemplates, { kind: "widget" });
566
+ const errors = result.ok ? [] : [...result.errors];
567
+ const keys = new Set(connectorTemplatesOf(manifest, { kind: "widget" }).map((t) => t.key));
568
+ const declared = Array.isArray(manifest.connectorTemplates) && manifest.connectorTemplates.length > 0;
569
+ const scopes = Array.isArray(manifest.requestedScopes) ? manifest.requestedScopes : [];
570
+ if (declared && !scopes.includes(CONNECTOR_CALL_SCOPE)) {
571
+ errors.push(`manifest.requestedScopes: a widget that ships connectorTemplates must request "${CONNECTOR_CALL_SCOPE}"`);
572
+ }
573
+ const schema = isPlainObject(manifest.propertySchema) ? manifest.propertySchema : {};
574
+ for (const [name, def] of Object.entries(schema)) {
575
+ if (!isPlainObject(def) || def.template === undefined) continue;
576
+ const at = `manifest.propertySchema.${name}.template`;
577
+ if (def.type !== "connectorRef") {
578
+ errors.push(`${at}: only a connectorRef property names a connector template`);
579
+ } else if (typeof def.template !== "string" || !keys.has(def.template)) {
580
+ errors.push(`${at}: "${String(def.template)}" is not the key of one of this manifest's valid connectorTemplates`);
581
+ }
582
+ }
583
+ return errors;
584
+ }
585
+
586
+ /**
587
+ * `{ property name -> template key }` for the manifest's connectorRef
588
+ * properties bound to one of its own templates.
589
+ * @param {unknown} manifest
590
+ * @returns {Map<string, string>}
591
+ */
592
+ function connectorTemplateProperties(manifest) {
593
+ const schema = isPlainObject(manifest) && isPlainObject(manifest.propertySchema) ? manifest.propertySchema : {};
594
+ const keys = new Set(connectorTemplatesOf(manifest, { kind: "widget" }).map((t) => t.key));
595
+ return new Map(
596
+ Object.entries(schema).flatMap(([name, def]) =>
597
+ isPlainObject(def) && def.type === "connectorRef" && keys.has(def.template) ? [[name, def.template]] : [],
598
+ ),
599
+ );
600
+ }
601
+
602
+ module.exports = {
603
+ isCredentialEntry,
604
+ CONNECTOR_CONTRACT,
605
+ deepFreeze,
606
+ CONNECTOR_CALL_SCOPE,
607
+ widgetConnectorTemplateErrors,
608
+ connectorTemplateProperties,
609
+ TEMPLATE_KINDS,
610
+ validateConnectorTemplates,
611
+ connectorTemplatesOf,
612
+ missingCredentialFields,
613
+ connectorWorkspaceOwnedFields,
614
+ connectorDefaultGrantType,
615
+ connectorGrantTypeRefusal,
616
+ connectorSecretFields,
617
+ connectorOperatorFields,
618
+ connectorSecretTokenEntries,
619
+ connectorSecretTokenNamesRefusal,
620
+ };
package/dist/contract.cjs CHANGED
@@ -4375,6 +4375,13 @@ const MANIFEST_SCHEMA = {
4375
4375
  "Optional (REQ-L10N-WIDGET). Translation strings the widget ships. Shape { <key>: { en: string, <locale>?: string, ... } } — `en` is REQUIRED per key. At install the host merges these into the tenant's localization dictionary under a per-widget namespace (`widget.<manifest.id>.<key>`); `useI18n().t(\"<key>\")` resolves the namespaced key automatically, so authors never type the prefix. Non-destructive: an existing admin-edited value is never overwritten, and a language the tenant has not added is never created (values for absent locales are dropped; the widget's `en` seeds the tenant's base language so every key renders). Keys persist across uninstalls; admins prune them from the Translations admin (bulk delete by `widget.<id>.` prefix). Limits: ≤500 keys; each key matches /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/; each value ≤1 KB; the namespaced key must fit the dictionary key cap (128 chars).",
4376
4376
  default: {},
4377
4377
  },
4378
+ connectorTemplates: {
4379
+ type: "array",
4380
+ required: false,
4381
+ description:
4382
+ "Optional. The REST connectors the widget calls, created in the installing workspace at install so the installer only adds the credential. Each entry is { key, name, baseUrl, authType?, authConfig?, defaultHeaders?, description?, appOperations }, the same contract an Action's connectorTemplates follow, plus `appOperations` (required): the operations the widget calls with `useConnector(connectorId).call(\"<operation>\", { params, query, body })`, each { key, method, path, query?, body? }. The connector is created callable from the app with exactly those operations. A manifest never carries a credential (a token, password, API key value or client secret): publishing one is refused, and the installer enters it on the connector. Declare `connectors.call:*` in requestedScopes, and give the widget a `connectorRef` property with `template: \"<key>\"` so placing it binds the property to the connector its install created. A reinstall or an upgrade keeps the installer's credential and creates no second connector. An upgrade that adds or changes an operation, asks its token for more, or moves the connector to another host is not applied to an installed connector, so keep the operations an earlier version listed working. At most 4 templates.",
4383
+ default: [],
4384
+ },
4378
4385
  };
4379
4386
 
4380
4387
  const WIDGET_CONTEXT_SHAPE = {
@@ -7123,7 +7130,12 @@ const CONTRACT = deepFreeze({
7123
7130
  // script's own run, inside a 1 s cap on the whole press, so a press can
7124
7131
  // wait up to about 1 s before ACTION_TIMEOUT. A press that never started
7125
7132
  // its script rejects RATE_LIMITED (429, Retry-After: 1): nothing ran.
7126
- version: "1.277.0",
7133
+ // 1.278.0: additive (sc-17829) — manifest `connectorTemplates`: the REST
7134
+ // connectors a widget ships, provisioned at install with the
7135
+ // `appOperations` it calls; a `connectorRef` property may name one with
7136
+ // `template`. Checked by `appstudio-widget lint --manifest`. The template
7137
+ // contract is shared with the action SDK (`./connector-template`).
7138
+ version: "1.278.0",
7127
7139
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7128
7140
  hooks: HOOKS,
7129
7141
  primitives: PRIMITIVES,
package/dist/contract.js CHANGED
@@ -4370,6 +4370,13 @@ const MANIFEST_SCHEMA = {
4370
4370
  "Optional (REQ-L10N-WIDGET). Translation strings the widget ships. Shape { <key>: { en: string, <locale>?: string, ... } } — `en` is REQUIRED per key. At install the host merges these into the tenant's localization dictionary under a per-widget namespace (`widget.<manifest.id>.<key>`); `useI18n().t(\"<key>\")` resolves the namespaced key automatically, so authors never type the prefix. Non-destructive: an existing admin-edited value is never overwritten, and a language the tenant has not added is never created (values for absent locales are dropped; the widget's `en` seeds the tenant's base language so every key renders). Keys persist across uninstalls; admins prune them from the Translations admin (bulk delete by `widget.<id>.` prefix). Limits: ≤500 keys; each key matches /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/; each value ≤1 KB; the namespaced key must fit the dictionary key cap (128 chars).",
4371
4371
  default: {},
4372
4372
  },
4373
+ connectorTemplates: {
4374
+ type: "array",
4375
+ required: false,
4376
+ description:
4377
+ "Optional. The REST connectors the widget calls, created in the installing workspace at install so the installer only adds the credential. Each entry is { key, name, baseUrl, authType?, authConfig?, defaultHeaders?, description?, appOperations }, the same contract an Action's connectorTemplates follow, plus `appOperations` (required): the operations the widget calls with `useConnector(connectorId).call(\"<operation>\", { params, query, body })`, each { key, method, path, query?, body? }. The connector is created callable from the app with exactly those operations. A manifest never carries a credential (a token, password, API key value or client secret): publishing one is refused, and the installer enters it on the connector. Declare `connectors.call:*` in requestedScopes, and give the widget a `connectorRef` property with `template: \"<key>\"` so placing it binds the property to the connector its install created. A reinstall or an upgrade keeps the installer's credential and creates no second connector. An upgrade that adds or changes an operation, asks its token for more, or moves the connector to another host is not applied to an installed connector, so keep the operations an earlier version listed working. At most 4 templates.",
4378
+ default: [],
4379
+ },
4373
4380
  };
4374
4381
 
4375
4382
  const WIDGET_CONTEXT_SHAPE = {
@@ -7118,7 +7125,12 @@ const CONTRACT = deepFreeze({
7118
7125
  // script's own run, inside a 1 s cap on the whole press, so a press can
7119
7126
  // wait up to about 1 s before ACTION_TIMEOUT. A press that never started
7120
7127
  // its script rejects RATE_LIMITED (429, Retry-After: 1): nothing ran.
7121
- version: "1.277.0",
7128
+ // 1.278.0: additive (sc-17829) — manifest `connectorTemplates`: the REST
7129
+ // connectors a widget ships, provisioned at install with the
7130
+ // `appOperations` it calls; a `connectorRef` property may name one with
7131
+ // `template`. Checked by `appstudio-widget lint --manifest`. The template
7132
+ // contract is shared with the action SDK (`./connector-template`).
7133
+ version: "1.278.0",
7122
7134
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7123
7135
  hooks: HOOKS,
7124
7136
  primitives: PRIMITIVES,