@genspark/cli 1.15.4 → 1.15.6
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.
- package/README.md +31 -11
- package/dist/acp-serve.d.ts +2 -2
- package/dist/acp-serve.d.ts.map +1 -1
- package/dist/acp-serve.js +7 -2
- package/dist/acp-serve.js.map +1 -1
- package/dist/client.d.ts +5 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +23 -12
- package/dist/client.js.map +1 -1
- package/dist/commands/aidrive-contract.generated.d.ts.map +1 -1
- package/dist/commands/aidrive-contract.generated.js +21 -2
- package/dist/commands/aidrive-contract.generated.js.map +1 -1
- package/dist/commands/task-status-follow.d.ts +9 -0
- package/dist/commands/task-status-follow.d.ts.map +1 -1
- package/dist/commands/task-status-follow.js +24 -4
- package/dist/commands/task-status-follow.js.map +1 -1
- package/dist/confirm.d.ts.map +1 -1
- package/dist/confirm.js +18 -1
- package/dist/confirm.js.map +1 -1
- package/dist/humanApproval.d.ts +48 -0
- package/dist/humanApproval.d.ts.map +1 -0
- package/dist/humanApproval.js +86 -0
- package/dist/humanApproval.js.map +1 -0
- package/dist/index.js +88 -21
- package/dist/index.js.map +1 -1
- package/dist/mediaSummary.d.ts.map +1 -1
- package/dist/mediaSummary.js +4 -1
- package/dist/mediaSummary.js.map +1 -1
- package/dist/task-shim.d.ts +11 -2
- package/dist/task-shim.d.ts.map +1 -1
- package/dist/task-shim.js +21 -2
- package/dist/task-shim.js.map +1 -1
- package/docs/skills.md +1 -1
- package/gated-skills/gsk-issue/SKILL.md +7 -0
- package/gated-skills/gsk-m365-apps/SKILL.md +197 -0
- package/gated-skills/gsk-m365-apps/references/add-genspark-ai.md +399 -0
- package/gated-skills/gsk-m365-apps/scripts/install-genspark-connector.mjs +548 -0
- package/gated-skills/gsk-m365-apps/scripts/sync-microsoft-guidance.mjs +557 -0
- package/package.json +1 -1
- package/skills/gsk-aidrive/SKILL.md +14 -2
- package/skills/gsk-aidrive/command-reference.md +13 -3
- package/skills/gsk-image-generation/SKILL.md +6 -3
- package/skills/gsk-phone-call/SKILL.md +33 -13
- package/skills/gsk-second-brain/SKILL.md +2 -2
- package/skills/gsk-slack/SKILL.md +4 -1
- package/skills/gsk-team-brain/SKILL.md +89 -22
- package/skills/gsk-video-generation/SKILL.md +3 -3
|
@@ -0,0 +1,548 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Install (or update) the "Genspark" custom MCP connector in the Power Platform
|
|
3
|
+
// environment of a Microsoft 365 managed app, so the app can call Genspark AI.
|
|
4
|
+
//
|
|
5
|
+
// Usage, from the app folder (the one with ms.config.json):
|
|
6
|
+
// node <skill>/scripts/install-genspark-connector.mjs [--environment-id <id>]
|
|
7
|
+
// [--tenant <tenant-id-or-domain>] [--project <dir>] [--gsk <gsk-binary>] [--dry-run]
|
|
8
|
+
//
|
|
9
|
+
// Steps:
|
|
10
|
+
// 1. Environment id from ms.config.json (`environmentId`), tenant from
|
|
11
|
+
// `ms auth status --json` (the active account's homeAccountId), unless flags say otherwise.
|
|
12
|
+
// 2. Microsoft sign-in by the OAuth 2.0 device code flow with Microsoft's public Azure CLI
|
|
13
|
+
// client (the client Microsoft's own `paconn` CLI uses): a Power Apps service token plus an
|
|
14
|
+
// ID token (`openid profile`) that proves to Genspark which tenant the user belongs to.
|
|
15
|
+
// 3. `gsk m365 connector_config` with {environment_id, tenant_id, id_token} on stdin (never on
|
|
16
|
+
// the command line): the Genspark OAuth client of that tenant environment (one per Microsoft
|
|
17
|
+
// tenant environment, created on first use and shared by every maker in it) plus the
|
|
18
|
+
// connector definition.
|
|
19
|
+
// 4. Create (POST) or update (PATCH) the connector through the Power Apps API, exactly like
|
|
20
|
+
// Genspark's backend does (backend/m365_apps/connector.py). Only a connector Genspark created
|
|
21
|
+
// (description marker + a backend host of this deployment) is updated; a maker's own "Genspark" connector is
|
|
22
|
+
// left alone and ours is created as "Genspark (Microsoft 365 apps)" instead.
|
|
23
|
+
// 5. Print {"connector_id", "created", "display_name", "environment_id"} as JSON on stdout.
|
|
24
|
+
//
|
|
25
|
+
// --dry-run asks gsk for a preview (no secret, no sign-in), makes no Microsoft call and prints
|
|
26
|
+
// the request it would send, client secret redacted.
|
|
27
|
+
//
|
|
28
|
+
// Never prints, logs or writes the client secret or a Microsoft token: the secret only travels
|
|
29
|
+
// inside the request body to api.powerapps.com. Node >= 18, no dependencies.
|
|
30
|
+
|
|
31
|
+
import { spawnSync } from 'node:child_process'
|
|
32
|
+
import { readFileSync, realpathSync } from 'node:fs'
|
|
33
|
+
import { join, resolve } from 'node:path'
|
|
34
|
+
import { fileURLToPath } from 'node:url'
|
|
35
|
+
|
|
36
|
+
export const AZURE_CLI_CLIENT_ID = '04b07795-8ddb-461a-bbee-02f9e1bf7b46'
|
|
37
|
+
export const POWER_APPS_SCOPE = 'https://service.powerapps.com//.default'
|
|
38
|
+
export const SIGN_IN_SCOPES = `openid profile ${POWER_APPS_SCOPE}`
|
|
39
|
+
export const POWERAPPS_API = 'https://api.powerapps.com/providers/Microsoft.PowerApps/apis'
|
|
40
|
+
export const API_VERSION = '2016-11-01'
|
|
41
|
+
export const LOGIN_HOST = 'https://login.microsoftonline.com'
|
|
42
|
+
export const CONNECTOR_DISPLAY_NAME = 'Genspark'
|
|
43
|
+
// Same values as backend/m365_apps/config.py; `gsk m365 connector_config` also returns them.
|
|
44
|
+
export const CONNECTOR_FALLBACK_DISPLAY_NAME = 'Genspark (Microsoft 365 apps)'
|
|
45
|
+
export const CONNECTOR_MARKER = '[genspark-mcp-connector]'
|
|
46
|
+
export const REDACTED = '<redacted>'
|
|
47
|
+
const ORIGIN_HEADER = { 'x-ms-origin': 'genspark-gencode-m365-apps' }
|
|
48
|
+
|
|
49
|
+
const GUID = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}'
|
|
50
|
+
const ENVIRONMENT_ID = new RegExp(`^(?:(default)-)?(${GUID})$`, 'i')
|
|
51
|
+
const TENANT_GUID = new RegExp(`^${GUID}$`)
|
|
52
|
+
const TENANT_DOMAIN = /^(?=.{3,253}$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/
|
|
53
|
+
|
|
54
|
+
export class InstallError extends Error {
|
|
55
|
+
constructor(code, message) {
|
|
56
|
+
super(message)
|
|
57
|
+
this.code = code
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Parse CLI flags. Unknown flags are an error, so a typo never silently does the wrong thing. */
|
|
62
|
+
export function parseArgs(argv) {
|
|
63
|
+
const opts = { dryRun: false, project: '.', gsk: process.env.GSK_BIN || 'gsk' }
|
|
64
|
+
const valued = {
|
|
65
|
+
'--environment-id': 'environmentId',
|
|
66
|
+
'--tenant': 'tenant',
|
|
67
|
+
'--project': 'project',
|
|
68
|
+
'--gsk': 'gsk',
|
|
69
|
+
}
|
|
70
|
+
for (let i = 0; i < argv.length; i++) {
|
|
71
|
+
const arg = argv[i]
|
|
72
|
+
if (arg === '--dry-run') {
|
|
73
|
+
opts.dryRun = true
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
if (arg === '-h' || arg === '--help') {
|
|
77
|
+
opts.help = true
|
|
78
|
+
continue
|
|
79
|
+
}
|
|
80
|
+
const [flag, inline] = arg.includes('=') ? [arg.slice(0, arg.indexOf('=')), arg.slice(arg.indexOf('=') + 1)] : [arg, undefined]
|
|
81
|
+
const key = valued[flag]
|
|
82
|
+
if (!key) throw new InstallError('bad_arguments', `Unknown argument: ${arg}`)
|
|
83
|
+
const value = inline !== undefined ? inline : argv[++i]
|
|
84
|
+
if (value === undefined || value === '') throw new InstallError('bad_arguments', `${flag} needs a value`)
|
|
85
|
+
opts[key] = value
|
|
86
|
+
}
|
|
87
|
+
return opts
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** `<GUID>` or `Default-<GUID>` in the backend's canonical form, or null. */
|
|
91
|
+
export function normalizeEnvironmentId(raw) {
|
|
92
|
+
if (typeof raw !== 'string') return null
|
|
93
|
+
const match = ENVIRONMENT_ID.exec(raw.trim())
|
|
94
|
+
if (!match) return null
|
|
95
|
+
const guid = match[2].toLowerCase()
|
|
96
|
+
return match[1] ? `Default-${guid}` : guid
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A tenant GUID or verified domain (contoso.onmicrosoft.com), or null. */
|
|
100
|
+
export function normalizeTenant(raw) {
|
|
101
|
+
if (typeof raw !== 'string') return null
|
|
102
|
+
const value = raw.trim()
|
|
103
|
+
if (TENANT_GUID.test(value)) return value.toLowerCase()
|
|
104
|
+
if (TENANT_DOMAIN.test(value)) return value.toLowerCase()
|
|
105
|
+
return null
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** environmentId from the app's ms.config.json text. */
|
|
109
|
+
export function environmentFromMsConfig(text) {
|
|
110
|
+
let parsed
|
|
111
|
+
try {
|
|
112
|
+
parsed = JSON.parse(text)
|
|
113
|
+
} catch {
|
|
114
|
+
throw new InstallError('bad_ms_config', 'ms.config.json is not valid JSON')
|
|
115
|
+
}
|
|
116
|
+
const env = normalizeEnvironmentId(parsed && parsed.environmentId)
|
|
117
|
+
if (!env) throw new InstallError('no_environment', 'ms.config.json has no valid environmentId; pass --environment-id')
|
|
118
|
+
return env
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Tenant id from `ms auth status --json`: MSAL homeAccountId is `<objectId>.<tenantId>`. */
|
|
122
|
+
export function tenantFromAuthStatus(text) {
|
|
123
|
+
let parsed
|
|
124
|
+
try {
|
|
125
|
+
parsed = JSON.parse(text)
|
|
126
|
+
} catch {
|
|
127
|
+
throw new InstallError('bad_auth_status', '`ms auth status --json` did not return JSON')
|
|
128
|
+
}
|
|
129
|
+
const account = parsed && (parsed.activeAccount || (Array.isArray(parsed.accounts) ? parsed.accounts.find(a => a && a.isActive) : null))
|
|
130
|
+
if (!parsed || parsed.signedIn === false || !account) {
|
|
131
|
+
throw new InstallError('not_signed_in', 'No active Microsoft account in the ms CLI. Run `ms auth login` with a work account, or pass --tenant.')
|
|
132
|
+
}
|
|
133
|
+
const home = typeof account.homeAccountId === 'string' ? account.homeAccountId : ''
|
|
134
|
+
const tenant = normalizeTenant(home.split('.')[1] || '')
|
|
135
|
+
if (!tenant) throw new InstallError('no_tenant', 'Could not read the tenant from `ms auth status --json`; pass --tenant.')
|
|
136
|
+
return tenant
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Claims of a JWT without verifying it (Genspark verifies the ID token; we only read `tid`). */
|
|
140
|
+
export function unverifiedClaims(token) {
|
|
141
|
+
const part = typeof token === 'string' ? token.split('.')[1] : undefined
|
|
142
|
+
if (!part) throw new InstallError('bad_id_token', 'Microsoft returned no usable ID token')
|
|
143
|
+
try {
|
|
144
|
+
return JSON.parse(Buffer.from(part.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'))
|
|
145
|
+
} catch {
|
|
146
|
+
throw new InstallError('bad_id_token', 'Microsoft returned no usable ID token')
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The connector config from `gsk m365 connector_config` stdout (the gsk JSON envelope). */
|
|
151
|
+
export function parseGskEnvelope(stdout) {
|
|
152
|
+
let parsed
|
|
153
|
+
try {
|
|
154
|
+
parsed = JSON.parse(String(stdout).trim())
|
|
155
|
+
} catch {
|
|
156
|
+
throw new InstallError('bad_gsk_output', '`gsk m365 connector_config` did not return JSON')
|
|
157
|
+
}
|
|
158
|
+
if (parsed && parsed.status === 'error') {
|
|
159
|
+
const message = (parsed.data && parsed.data.message) || parsed.message || 'unknown error'
|
|
160
|
+
throw new InstallError('gsk_error', `gsk m365 connector_config failed: ${message}`)
|
|
161
|
+
}
|
|
162
|
+
const data = parsed && typeof parsed.data === 'object' && parsed.data ? parsed.data : parsed
|
|
163
|
+
if (data && data.error) {
|
|
164
|
+
throw new InstallError(String(data.error), `gsk m365 connector_config failed: ${data.message || data.error}`)
|
|
165
|
+
}
|
|
166
|
+
for (const key of ['client_secret', 'openapi_definition', 'oauth_settings', 'connector']) {
|
|
167
|
+
if (!data || data[key] === undefined || data[key] === null) {
|
|
168
|
+
throw new InstallError('bad_gsk_output', `gsk m365 connector_config returned no ${key}`)
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return data
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Request body for POST|PATCH …/apis — the same shape as backend/m365_apps/connector.py builds. */
|
|
175
|
+
export function buildConnectorPayload(config, environmentId) {
|
|
176
|
+
const connector = config.connector
|
|
177
|
+
return {
|
|
178
|
+
properties: {
|
|
179
|
+
displayName: connector.display_name,
|
|
180
|
+
description: connector.description,
|
|
181
|
+
iconBrandColor: connector.icon_brand_color,
|
|
182
|
+
openApiDefinition: config.openapi_definition,
|
|
183
|
+
backendService: { serviceUrl: connector.backend_service_url },
|
|
184
|
+
environment: { name: environmentId },
|
|
185
|
+
capabilities: [],
|
|
186
|
+
policyTemplateInstances: [],
|
|
187
|
+
scriptDefinitionUrl: '',
|
|
188
|
+
connectionParameters: {
|
|
189
|
+
token: { type: 'oauthSetting', oAuthSettings: config.oauth_settings },
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** A copy of the payload that is safe to print. */
|
|
196
|
+
export function redactPayload(payload) {
|
|
197
|
+
const copy = JSON.parse(JSON.stringify(payload))
|
|
198
|
+
const settings = copy.properties?.connectionParameters?.token?.oAuthSettings
|
|
199
|
+
if (settings && 'clientSecret' in settings) settings.clientSecret = REDACTED
|
|
200
|
+
return copy
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Replace every occurrence of each secret in text (for error bodies we echo). */
|
|
204
|
+
export function scrub(text, secrets) {
|
|
205
|
+
let out = String(text)
|
|
206
|
+
for (const secret of secrets) {
|
|
207
|
+
if (secret && secret.length >= 8) out = out.split(secret).join(REDACTED)
|
|
208
|
+
}
|
|
209
|
+
return out
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const hostOf = url => {
|
|
213
|
+
try {
|
|
214
|
+
return new URL(String(url)).hostname.toLowerCase()
|
|
215
|
+
} catch {
|
|
216
|
+
return ''
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* True only for a connector this Genspark deployment created: the description carries the marker
|
|
222
|
+
* and the backend (when the listing reports it) is `host` or one of `platformHosts` (the
|
|
223
|
+
* deployment's hosts from `gsk m365 connector_config`), so one installed via genspark.ai is still
|
|
224
|
+
* ours from www.genspark.ai or an org vanity host. Display names prove nothing — a maker's own
|
|
225
|
+
* connector called "Genspark" is never updated (backend/m365_apps/connector.py, same rule).
|
|
226
|
+
*/
|
|
227
|
+
export function isGensparkConnector(api, { host, platformHosts = [], marker = CONNECTOR_MARKER } = {}) {
|
|
228
|
+
const props = (api && api.properties) || {}
|
|
229
|
+
if (props.isCustomApi === false) return false
|
|
230
|
+
if (!String(props.description || '').includes(marker)) return false
|
|
231
|
+
const serviceUrl = props.backendService && props.backendService.serviceUrl
|
|
232
|
+
if (!serviceUrl) return true
|
|
233
|
+
const serviceHost = hostOf(serviceUrl)
|
|
234
|
+
if (!serviceHost) return false
|
|
235
|
+
const ours = [host, ...(Array.isArray(platformHosts) ? platformHosts : [])].map(h => String(h || '').toLowerCase())
|
|
236
|
+
return ours.includes(serviceHost)
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Our connector in a Power Apps `apis` listing (or null) and the display name to save it under:
|
|
241
|
+
* its current name, else "Genspark", else the fallback name when a foreign connector holds it.
|
|
242
|
+
* Among several of ours, the one holding `clientId` wins, then the one on `host`.
|
|
243
|
+
*/
|
|
244
|
+
export function findGensparkConnector(
|
|
245
|
+
listing,
|
|
246
|
+
{
|
|
247
|
+
host,
|
|
248
|
+
platformHosts = [],
|
|
249
|
+
clientId,
|
|
250
|
+
marker = CONNECTOR_MARKER,
|
|
251
|
+
displayName = CONNECTOR_DISPLAY_NAME,
|
|
252
|
+
fallbackDisplayName = CONNECTOR_FALLBACK_DISPLAY_NAME,
|
|
253
|
+
} = {}
|
|
254
|
+
) {
|
|
255
|
+
const value = listing && Array.isArray(listing.value) ? listing.value : []
|
|
256
|
+
let ours = null
|
|
257
|
+
let bestRank = Infinity
|
|
258
|
+
const ownHost = String(host || '').toLowerCase()
|
|
259
|
+
for (const api of value) {
|
|
260
|
+
if (!isGensparkConnector(api, { host, platformHosts, marker })) continue
|
|
261
|
+
const serviceUrl = api.properties.backendService && api.properties.backendService.serviceUrl
|
|
262
|
+
const currentClient = api.properties.connectionParameters?.token?.oAuthSettings?.clientId
|
|
263
|
+
const rank = clientId && currentClient === clientId ? 0 : !serviceUrl || hostOf(serviceUrl) === ownHost ? 1 : 2
|
|
264
|
+
if (rank < bestRank) {
|
|
265
|
+
ours = api
|
|
266
|
+
bestRank = rank
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
const foreign = new Set()
|
|
270
|
+
for (const api of value) {
|
|
271
|
+
const props = (api && api.properties) || {}
|
|
272
|
+
if (api !== ours && props.isCustomApi !== false && props.displayName) foreign.add(props.displayName)
|
|
273
|
+
}
|
|
274
|
+
if (ours && ours.properties && ours.properties.displayName) return { ours, displayName: ours.properties.displayName }
|
|
275
|
+
for (const name of [displayName, fallbackDisplayName]) {
|
|
276
|
+
if (!foreign.has(name)) return { ours, displayName: name }
|
|
277
|
+
}
|
|
278
|
+
throw new InstallError(
|
|
279
|
+
'connector_name_taken',
|
|
280
|
+
`This environment already has custom connectors named "${displayName}" and "${fallbackDisplayName}" that Genspark did not create; rename one of them and run the installer again.`
|
|
281
|
+
)
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export function environmentQuery(environmentId) {
|
|
285
|
+
return new URLSearchParams({ 'api-version': API_VERSION, $filter: `environment eq '${environmentId}'` }).toString()
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const sleepMs = ms => new Promise(r => setTimeout(r, ms))
|
|
289
|
+
|
|
290
|
+
async function readJson(response) {
|
|
291
|
+
const text = await response.text()
|
|
292
|
+
try {
|
|
293
|
+
return { text, json: text ? JSON.parse(text) : {} }
|
|
294
|
+
} catch {
|
|
295
|
+
return { text, json: null }
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Device code sign-in (RFC 8628) for the Power Apps service. Resolves to
|
|
301
|
+
* {accessToken, idToken}. Prints only Microsoft's sign-in instructions (URL + user code)
|
|
302
|
+
* to `log`; never a token.
|
|
303
|
+
*/
|
|
304
|
+
export async function deviceCodeSignIn({ tenant, fetchImpl = fetch, sleep = sleepMs, log = console.error, now = Date.now }) {
|
|
305
|
+
const base = `${LOGIN_HOST}/${encodeURIComponent(tenant)}/oauth2/v2.0`
|
|
306
|
+
const start = await fetchImpl(`${base}/devicecode`, {
|
|
307
|
+
method: 'POST',
|
|
308
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
309
|
+
body: new URLSearchParams({ client_id: AZURE_CLI_CLIENT_ID, scope: SIGN_IN_SCOPES }).toString(),
|
|
310
|
+
})
|
|
311
|
+
const { json: device } = await readJson(start)
|
|
312
|
+
if (!start.ok || !device || !device.device_code) {
|
|
313
|
+
const reason = (device && (device.error_description || device.error)) || `HTTP ${start.status}`
|
|
314
|
+
throw new InstallError('device_code_failed', `Microsoft refused the device code request: ${String(reason).split('\n')[0]}`)
|
|
315
|
+
}
|
|
316
|
+
log(device.message || `To sign in, open ${device.verification_uri} and enter the code ${device.user_code}`)
|
|
317
|
+
let interval = Math.max(Number(device.interval) || 5, 1)
|
|
318
|
+
const deadline = now() + (Number(device.expires_in) || 900) * 1000
|
|
319
|
+
while (now() < deadline) {
|
|
320
|
+
await sleep(interval * 1000)
|
|
321
|
+
const response = await fetchImpl(`${base}/token`, {
|
|
322
|
+
method: 'POST',
|
|
323
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
324
|
+
body: new URLSearchParams({
|
|
325
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
|
|
326
|
+
client_id: AZURE_CLI_CLIENT_ID,
|
|
327
|
+
device_code: device.device_code,
|
|
328
|
+
}).toString(),
|
|
329
|
+
})
|
|
330
|
+
const { json } = await readJson(response)
|
|
331
|
+
if (response.ok && json && json.access_token) {
|
|
332
|
+
if (!json.id_token) throw new InstallError('bad_id_token', 'Microsoft returned no ID token')
|
|
333
|
+
return { accessToken: json.access_token, idToken: json.id_token }
|
|
334
|
+
}
|
|
335
|
+
const error = json && json.error
|
|
336
|
+
if (error === 'authorization_pending') continue
|
|
337
|
+
if (error === 'slow_down') {
|
|
338
|
+
interval += 5
|
|
339
|
+
continue
|
|
340
|
+
}
|
|
341
|
+
const reason = (json && (json.error_description || error)) || `HTTP ${response.status}`
|
|
342
|
+
throw new InstallError(error || 'token_failed', `Microsoft sign-in did not complete: ${String(reason).split('\n')[0]}`)
|
|
343
|
+
}
|
|
344
|
+
throw new InstallError('expired_token', 'The sign-in code expired before it was used. Run the installer again.')
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Host to save an existing connector of ours under — the same rule as connector_host in
|
|
349
|
+
* backend/m365_apps/connector.py. One on an org vanity host keeps it (moving it would sign every
|
|
350
|
+
* app user out, possibly onto another org's SSO-only host); one on a shared host (`shared_hosts`:
|
|
351
|
+
* www, the apex, jpw — never a vanity host) moves to the maker's vanity host; otherwise it keeps its host.
|
|
352
|
+
*/
|
|
353
|
+
export function connectorHost(existingHost, wantedHost, { platformHosts = [], sharedHosts = [] } = {}) {
|
|
354
|
+
const existing = String(existingHost || '').toLowerCase()
|
|
355
|
+
const wanted = String(wantedHost || '').toLowerCase()
|
|
356
|
+
const ours = new Set([wanted, ...platformHosts].map(h => String(h || '').toLowerCase()))
|
|
357
|
+
if (!existing || !ours.has(existing)) return wanted
|
|
358
|
+
const own = new Set(sharedHosts.map(h => String(h || '').toLowerCase()))
|
|
359
|
+
if (own.has(existing) && !own.has(wanted)) return wanted
|
|
360
|
+
return existing
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** `payload` with every `https://<fromHost>` URL (and the OpenAPI host) pointed at `toHost`. */
|
|
364
|
+
export function retargetPayload(payload, fromHost, toHost) {
|
|
365
|
+
if (!fromHost || !toHost || fromHost === toHost) return payload
|
|
366
|
+
const swap = value => {
|
|
367
|
+
if (typeof value === 'string') return value.split(`https://${fromHost}`).join(`https://${toHost}`)
|
|
368
|
+
if (Array.isArray(value)) return value.map(swap)
|
|
369
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, swap(v)]))
|
|
370
|
+
return value
|
|
371
|
+
}
|
|
372
|
+
const copy = swap(payload)
|
|
373
|
+
const definition = copy.properties && copy.properties.openApiDefinition
|
|
374
|
+
if (definition && definition.host === fromHost) definition.host = toHost
|
|
375
|
+
return copy
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Create or update the connector. Returns {connector_id, created, display_name}. Only a connector
|
|
380
|
+
* carrying our marker and a backend host of this deployment is PATCHed; anything else is never touched.
|
|
381
|
+
*/
|
|
382
|
+
export async function upsertConnector({
|
|
383
|
+
token,
|
|
384
|
+
environmentId,
|
|
385
|
+
payload,
|
|
386
|
+
fetchImpl = fetch,
|
|
387
|
+
secrets = [],
|
|
388
|
+
marker = CONNECTOR_MARKER,
|
|
389
|
+
fallbackDisplayName = CONNECTOR_FALLBACK_DISPLAY_NAME,
|
|
390
|
+
platformHosts = [],
|
|
391
|
+
sharedHosts = [],
|
|
392
|
+
}) {
|
|
393
|
+
const headers = { Authorization: `Bearer ${token}`, ...ORIGIN_HEADER }
|
|
394
|
+
const query = environmentQuery(environmentId)
|
|
395
|
+
const listResponse = await fetchImpl(`${POWERAPPS_API}?${query}`, { headers })
|
|
396
|
+
const listed = await readJson(listResponse)
|
|
397
|
+
if (!listResponse.ok) {
|
|
398
|
+
throw new InstallError('list_failed', `Power Apps API ${listResponse.status}: ${scrub(listed.text, secrets).slice(0, 500)}`)
|
|
399
|
+
}
|
|
400
|
+
const { ours: existing, displayName } = findGensparkConnector(listed.json, {
|
|
401
|
+
host: hostOf(payload.properties.backendService && payload.properties.backendService.serviceUrl),
|
|
402
|
+
platformHosts,
|
|
403
|
+
clientId: payload.properties.connectionParameters?.token?.oAuthSettings?.clientId,
|
|
404
|
+
marker,
|
|
405
|
+
displayName: payload.properties.displayName || CONNECTOR_DISPLAY_NAME,
|
|
406
|
+
fallbackDisplayName,
|
|
407
|
+
})
|
|
408
|
+
// Genspark refresh tokens are bound to their OAuth client: never swap the client of a connector
|
|
409
|
+
// that already holds another one (every app user would be signed out). Leave it as is.
|
|
410
|
+
const currentClient = existing?.properties?.connectionParameters?.token?.oAuthSettings?.clientId
|
|
411
|
+
const ourClient = payload.properties.connectionParameters?.token?.oAuthSettings?.clientId
|
|
412
|
+
if (existing && currentClient && ourClient && currentClient !== ourClient) {
|
|
413
|
+
return { connector_id: String(existing.name), created: false, display_name: displayName, skipped: 'client_mismatch' }
|
|
414
|
+
}
|
|
415
|
+
const wantedHost = hostOf(payload.properties.backendService && payload.properties.backendService.serviceUrl)
|
|
416
|
+
const existingHost = existing ? hostOf(existing.properties?.backendService?.serviceUrl) : ''
|
|
417
|
+
const targetHost = existing ? connectorHost(existingHost, wantedHost, { platformHosts, sharedHosts }) : wantedHost
|
|
418
|
+
const retargeted = retargetPayload(payload, wantedHost, targetHost)
|
|
419
|
+
const body = { ...retargeted, properties: { ...retargeted.properties, displayName } }
|
|
420
|
+
// Power Apps refuses any displayName on an update (CannotUpdateApiDisplayName), even an unchanged one.
|
|
421
|
+
if (existing) delete body.properties.displayName
|
|
422
|
+
const url = existing ? `${POWERAPPS_API}/${encodeURIComponent(existing.name)}?${query}` : `${POWERAPPS_API}?${query}`
|
|
423
|
+
const response = await fetchImpl(url, {
|
|
424
|
+
method: existing ? 'PATCH' : 'POST',
|
|
425
|
+
headers: { ...headers, 'content-type': 'application/json' },
|
|
426
|
+
body: JSON.stringify(body),
|
|
427
|
+
})
|
|
428
|
+
const saved = await readJson(response)
|
|
429
|
+
if (!response.ok) {
|
|
430
|
+
const code = response.status === 403 ? 'forbidden' : 'save_failed'
|
|
431
|
+
throw new InstallError(code, `Power Apps API ${response.status}: ${scrub(saved.text, secrets).slice(0, 500)}`)
|
|
432
|
+
}
|
|
433
|
+
const connectorId = (saved.json && saved.json.name) || (existing && existing.name) || ''
|
|
434
|
+
return { connector_id: String(connectorId), created: !existing, display_name: displayName }
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function run(command, args, input) {
|
|
438
|
+
const result = spawnSync(command, args, {
|
|
439
|
+
encoding: 'utf8',
|
|
440
|
+
shell: process.platform === 'win32',
|
|
441
|
+
input,
|
|
442
|
+
stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'inherit'],
|
|
443
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
444
|
+
})
|
|
445
|
+
if (result.error) throw new InstallError('spawn_failed', `Could not run ${command}: ${result.error.message}`)
|
|
446
|
+
return result
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
const HELP = `Install the Genspark connector into a Microsoft 365 managed app's environment.
|
|
450
|
+
|
|
451
|
+
node install-genspark-connector.mjs [--environment-id <id>] [--tenant <id|domain>]
|
|
452
|
+
[--project <dir>] [--gsk <binary>] [--dry-run]
|
|
453
|
+
`
|
|
454
|
+
|
|
455
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
456
|
+
const opts = parseArgs(argv)
|
|
457
|
+
if (opts.help) {
|
|
458
|
+
process.stdout.write(HELP)
|
|
459
|
+
return null
|
|
460
|
+
}
|
|
461
|
+
const project = resolve(opts.project)
|
|
462
|
+
|
|
463
|
+
let environmentId = opts.environmentId ? normalizeEnvironmentId(opts.environmentId) : null
|
|
464
|
+
if (opts.environmentId && !environmentId) throw new InstallError('bad_arguments', '--environment-id must be a GUID or Default-<GUID>')
|
|
465
|
+
if (!environmentId) {
|
|
466
|
+
let text
|
|
467
|
+
try {
|
|
468
|
+
text = readFileSync(join(project, 'ms.config.json'), 'utf8')
|
|
469
|
+
} catch {
|
|
470
|
+
throw new InstallError('no_ms_config', `No ms.config.json in ${project}; run from the app folder or pass --environment-id`)
|
|
471
|
+
}
|
|
472
|
+
environmentId = environmentFromMsConfig(text)
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
let tenant = opts.tenant ? normalizeTenant(opts.tenant) : null
|
|
476
|
+
if (opts.tenant && !tenant) throw new InstallError('bad_arguments', '--tenant must be a tenant GUID or domain')
|
|
477
|
+
if (!tenant) {
|
|
478
|
+
const status = run('ms', ['auth', 'status', '--json'])
|
|
479
|
+
if (status.status !== 0) throw new InstallError('not_signed_in', '`ms auth status` failed. Run `ms auth login` with a work account, or pass --tenant.')
|
|
480
|
+
tenant = tenantFromAuthStatus(status.stdout)
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
const gskArgs = ['--output', 'json', 'm365', 'connector_config', '--args-file', '-']
|
|
484
|
+
const askGsk = args => {
|
|
485
|
+
const gsk = run(opts.gsk, gskArgs, JSON.stringify(args))
|
|
486
|
+
const config = parseGskEnvelope(gsk.stdout)
|
|
487
|
+
if (gsk.status !== 0) throw new InstallError('gsk_error', 'gsk m365 connector_config failed')
|
|
488
|
+
return config
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
if (opts.dryRun) {
|
|
492
|
+
const preview = askGsk({ environment_id: environmentId, preview: true, ...(TENANT_GUID.test(tenant) ? { tenant_id: tenant } : {}) })
|
|
493
|
+
const payload = buildConnectorPayload(preview, environmentId)
|
|
494
|
+
const result = {
|
|
495
|
+
dry_run: true,
|
|
496
|
+
environment_id: environmentId,
|
|
497
|
+
tenant,
|
|
498
|
+
requests: [
|
|
499
|
+
{ method: 'GET', url: `${POWERAPPS_API}?${environmentQuery(environmentId)}` },
|
|
500
|
+
{
|
|
501
|
+
method: 'POST (new) or PATCH /<connector name> (existing Genspark-created connector only)',
|
|
502
|
+
url: `${POWERAPPS_API}?${environmentQuery(environmentId)}`,
|
|
503
|
+
body: redactPayload(payload),
|
|
504
|
+
},
|
|
505
|
+
],
|
|
506
|
+
}
|
|
507
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`)
|
|
508
|
+
return result
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
const { accessToken, idToken } = await deviceCodeSignIn({ tenant })
|
|
512
|
+
const tenantId = normalizeTenant(String(unverifiedClaims(idToken).tid || ''))
|
|
513
|
+
if (!tenantId || !TENANT_GUID.test(tenantId)) throw new InstallError('bad_id_token', 'The Microsoft ID token names no tenant')
|
|
514
|
+
const config = askGsk({ environment_id: environmentId, tenant_id: tenantId, id_token: idToken })
|
|
515
|
+
const payload = buildConnectorPayload(config, environmentId)
|
|
516
|
+
const saved = await upsertConnector({
|
|
517
|
+
token: accessToken,
|
|
518
|
+
environmentId,
|
|
519
|
+
payload,
|
|
520
|
+
secrets: [config.client_secret, accessToken, idToken],
|
|
521
|
+
marker: config.connector.marker || CONNECTOR_MARKER,
|
|
522
|
+
fallbackDisplayName: config.connector.fallback_display_name || CONNECTOR_FALLBACK_DISPLAY_NAME,
|
|
523
|
+
platformHosts: Array.isArray(config.platform_hosts) ? config.platform_hosts : [],
|
|
524
|
+
sharedHosts: Array.isArray(config.shared_hosts) ? config.shared_hosts : [],
|
|
525
|
+
})
|
|
526
|
+
const result = { ...saved, environment_id: environmentId }
|
|
527
|
+
process.stdout.write(`${JSON.stringify(result)}\n`)
|
|
528
|
+
return result
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** True when `argv1` (process.argv[1]) is this module, also when run through a symlink. */
|
|
532
|
+
export function isEntryPoint(moduleUrl, argv1) {
|
|
533
|
+
if (!argv1) return false
|
|
534
|
+
try {
|
|
535
|
+
return realpathSync(argv1) === realpathSync(fileURLToPath(moduleUrl))
|
|
536
|
+
} catch {
|
|
537
|
+
return false
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
if (isEntryPoint(import.meta.url, process.argv[1])) {
|
|
542
|
+
main().catch(error => {
|
|
543
|
+
const code = error instanceof InstallError ? error.code : 'unexpected'
|
|
544
|
+
process.stderr.write(`install-genspark-connector: ${error.message}\n`)
|
|
545
|
+
process.stdout.write(`${JSON.stringify({ error: code, message: error.message })}\n`)
|
|
546
|
+
process.exitCode = 1
|
|
547
|
+
})
|
|
548
|
+
}
|