@zortexhq/indra-v2.5 0.4.1 → 0.4.2
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 +5 -5
- package/bin/codex-postinstall.mjs +1 -1
- package/dist/action-effect.js +1 -0
- package/dist/action-read-progress.js +1 -1
- package/dist/actions-catalog.js +1 -0
- package/dist/auto-sync.js +1 -1
- package/dist/auto-update.js +1 -1
- package/dist/automatic-updates.js +1 -0
- package/dist/bundled-handbook.js +1 -1
- package/dist/cli-run.js +1 -1
- package/dist/cli.js +1 -1
- package/dist/codex-install.js +1 -1
- package/dist/codex-setup.js +1 -1
- package/dist/computer-use-setup.js +1 -0
- package/dist/default-root.js +1 -1
- package/dist/documentation-action.js +1 -0
- package/dist/gateway.js +1 -1
- package/dist/imessage-sync.js +1 -1
- package/dist/local-cloud-policy.js +1 -1
- package/dist/local-cloud.js +1 -1
- package/dist/mcp.js +1 -3
- package/dist/native-connect.js +1 -1
- package/dist/native-level1-setup.js +1 -1
- package/dist/native-ollama-discovery.js +1 -0
- package/dist/native-vault-discovery.js +1 -1
- package/dist/onboard-cli.js +1 -1
- package/dist/onboard.js +1 -1
- package/dist/onboarding.js +1 -1
- package/dist/profile.js +1 -1
- package/dist/public-tool.js +4 -1
- package/dist/recovery-authorization-url.js +1 -1
- package/dist/recovery-progress.js +1 -1
- package/dist/recovery.js +1 -1
- package/dist/resident-autopilot.js +1 -0
- package/dist/resident-ensure-ready.js +1 -1
- package/dist/resident-host.js +2 -2
- package/dist/resident-jobs.js +1 -1
- package/dist/resident-platform.js +2 -2
- package/dist/resident-runtime-identity.js +1 -1
- package/dist/resident-startup-state.js +1 -0
- package/dist/resident-telemetry.js +1 -1
- package/dist/shared-action-schemas.js +1 -0
- package/dist/source-data.js +1 -1
- package/dist/storage-compatibility.js +1 -0
- package/dist/supervised-sync.js +1 -1
- package/dist/tools.js +1 -1
- package/dist/update-check.js +1 -1
- package/dist/update-cli.js +1 -1
- package/dist/update-command.js +1 -1
- package/dist/update-recovery.js +1 -1
- package/node_modules/@zortexhq/plugin-auto-connect/dist/api/durable-dispatcher.js +1 -1
- package/node_modules/@zortexhq/plugin-auto-connect/dist/api/job-contract.js +1 -1
- package/node_modules/@zortexhq/plugin-autopilot/dist/api.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/cua.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/feedback.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/index.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/python-runtime.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/service.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/worker.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/package.json +23 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/LICENSE +21 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/PROVENANCE.json +38 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/__init__.py +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/agent.py +178 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/browser.py +13 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/indra.patch +57 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/model.py +180 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/questions.py +26 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/transport.py +70 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/strategies.py +154 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/worker.py +260 -0
- package/node_modules/@zortexhq/plugin-connector-calendar/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-computer-files/dist/catalog.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/action-outcome.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/content-acquisition.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/authorization-metrics.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/native-principal.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-drive/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-drive/package.json +2 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/connector.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/package.json +2 -1
- package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/compounds.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-server.js +6 -6
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-native-process.mjs +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-server.js +2 -2
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-server.js +2 -2
- package/node_modules/@zortexhq/plugin-connector-level1/dist/cua-runtime.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/macos-contacts-server.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-apple-native.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-local.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/provisioning.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-slack/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-slack/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-teams/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-teams/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/auth-state.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/api/action-schemas.js +1 -0
- package/node_modules/@zortexhq/plugin-context-share/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/share.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-catalog.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/original-adapter.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/account.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -1
- package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/api/execution-scope.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/api/stdio-transport.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/windows-job.js +1 -1
- package/node_modules/@zortexhq/plugin-product-account/dist/index.js +4 -1
- package/node_modules/@zortexhq/plugin-product-account/dist/session-store.js +10 -0
- package/node_modules/@zortexhq/plugin-product-account/dist/storage.js +1 -0
- package/node_modules/@zortexhq/plugin-product-account/package.json +5 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/public-result-visibility.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/content-acquisition.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/credentials.js +3 -3
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/keychain.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/public-visibility.js +7 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/recovery-guard.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/runtime.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +2 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/search-records.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-worker.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/source-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +2 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql.js +1 -1
- package/package.json +13 -7
- package/profiles/core.yml +2 -0
- package/release-provenance.json +43 -36
- package/update-manifest.json +516 -275
- package/dist/content-find.js +0 -2
- package/dist/find-snapshots.js +0 -1
- package/dist/match-excerpt.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";const SOURCE="outlook",API="https://graph.microsoft.com/v1.0";const id={type:"string",minLength:1,maxLength:2048};const top={type:"integer",minimum:1,maximum:100};const text={type:"string",minLength:1,maxLength:1e4};const object={type:"object",minProperties:1,maxProperties:64};const methods=[{name:"outlook.identity",description:"Read the authorized Microsoft account identity.",httpMethod:"GET",effect:"read",scopes:["User.Read"],inputSchema:{type:"object",properties:{},additionalProperties:false}},{name:"outlook.mail.folders.list",description:"List mail folders, including hidden folders when requested.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{top,includeHidden:{type:"boolean"},skipToken:id},additionalProperties:false}},{name:"outlook.mail.folders.delta",description:"Read one independent mail-folder delta page.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{deltaLink:id},additionalProperties:false}},{name:"outlook.mail.messages.list",description:"List or search messages across every mail folder.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{top,search:text,filter:text,skipToken:id},additionalProperties:false}},{name:"outlook.mail.messages.get",description:"Read one message with headers and body.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{messageId:id},required:["messageId"],additionalProperties:false}},{name:"outlook.mail.messages.mime",description:"Download one message as MIME up to 1 MiB without storing it in Vault.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{messageId:id},required:["messageId"],additionalProperties:false}},{name:"outlook.mail.messages.delta",description:"Read one independent delta page for one exact mail folder.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{folderId:id,top,deltaLink:id},required:["folderId"],additionalProperties:false}},{name:"outlook.mail.attachments.list",description:"List attachment metadata for one message.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{messageId:id,top},required:["messageId"],additionalProperties:false}},{name:"outlook.mail.attachments.download",description:"Download one attachment up to 1 MiB without storing it in Vault.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{messageId:id,attachmentId:id},required:["messageId","attachmentId"],additionalProperties:false}},{name:"outlook.mail.drafts.create",description:"Create one unsent draft message for reversible verification.",httpMethod:"POST",effect:"write",scopes:["Mail.ReadWrite"],inputSchema:{type:"object",properties:{message:object},required:["message"],additionalProperties:false}},{name:"outlook.mail.messages.delete",description:"Delete one exact message or draft.",httpMethod:"DELETE",effect:"write",scopes:["Mail.ReadWrite"],inputSchema:{type:"object",properties:{messageId:id},required:["messageId"],additionalProperties:false}},{name:"outlook.calendars.list",description:"List calendars visible to the authorized account.",httpMethod:"GET",effect:"read",scopes:["Calendars.ReadWrite"],inputSchema:{type:"object",properties:{top,skipToken:id},additionalProperties:false}},{name:"outlook.events.list",description:"List events from one exact calendar.",httpMethod:"GET",effect:"read",scopes:["Calendars.ReadWrite"],inputSchema:{type:"object",properties:{calendarId:id,top,filter:text,skipToken:id},required:["calendarId"],additionalProperties:false}},{name:"outlook.events.get",description:"Read one event from one exact calendar.",httpMethod:"GET",effect:"read",scopes:["Calendars.ReadWrite"],inputSchema:{type:"object",properties:{calendarId:id,eventId:id},required:["calendarId","eventId"],additionalProperties:false}},{name:"outlook.events.delta",description:"Read one independent calendar-view delta page for an exact time range.",httpMethod:"GET",effect:"read",scopes:["Calendars.ReadWrite"],inputSchema:{type:"object",properties:{startDateTime:{type:"string",format:"date-time"},endDateTime:{type:"string",format:"date-time"},deltaLink:id},required:["startDateTime","endDateTime"],additionalProperties:false}},{name:"outlook.events.create",description:"Create one event in an exact calendar for reversible verification.",httpMethod:"POST",effect:"write",scopes:["Calendars.ReadWrite"],inputSchema:{type:"object",properties:{calendarId:id,event:object},required:["calendarId","event"],additionalProperties:false}},{name:"outlook.events.delete",description:"Delete one exact event.",httpMethod:"DELETE",effect:"write",scopes:["Calendars.ReadWrite"],inputSchema:{type:"object",properties:{calendarId:id,eventId:id},required:["calendarId","eventId"],additionalProperties:false}},{name:"outlook.contacts.list",description:"List contacts visible to the authorized account.",httpMethod:"GET",effect:"read",scopes:["Contacts.ReadWrite"],inputSchema:{type:"object",properties:{top,skipToken:id},additionalProperties:false}},{name:"outlook.contacts.get",description:"Read one exact contact.",httpMethod:"GET",effect:"read",scopes:["Contacts.ReadWrite"],inputSchema:{type:"object",properties:{contactId:id},required:["contactId"],additionalProperties:false}},{name:"outlook.contacts.delta",description:"Read one independent contacts delta page.",httpMethod:"GET",effect:"read",scopes:["Contacts.ReadWrite"],inputSchema:{type:"object",properties:{deltaLink:id},additionalProperties:false}},{name:"outlook.contacts.create",description:"Create one contact for reversible verification.",httpMethod:"POST",effect:"write",scopes:["Contacts.ReadWrite"],inputSchema:{type:"object",properties:{contact:object},required:["contact"],additionalProperties:false}},{name:"outlook.contacts.delete",description:"Delete one exact contact.",httpMethod:"DELETE",effect:"write",scopes:["Contacts.ReadWrite"],inputSchema:{type:"object",properties:{contactId:id},required:["contactId"],additionalProperties:false}},{name:"outlook.categories.list",description:"List the account master categories.",httpMethod:"GET",effect:"read",scopes:["MailboxSettings.ReadWrite"],inputSchema:{type:"object",properties:{top},additionalProperties:false}},{name:"outlook.categories.create",description:"Create one master category for reversible verification.",httpMethod:"POST",effect:"write",scopes:["MailboxSettings.ReadWrite"],inputSchema:{type:"object",properties:{category:object},required:["category"],additionalProperties:false}},{name:"outlook.categories.delete",description:"Delete one exact master category.",httpMethod:"DELETE",effect:"write",scopes:["MailboxSettings.ReadWrite"],inputSchema:{type:"object",properties:{categoryId:id},required:["categoryId"],additionalProperties:false}}];export const outlookContent=[...["message","mail-folder"].map(resource=>({resource:`mailbox/${resource}`,read:"implemented",acquisition:"collection",persistence:"durable",readFields:["selected-metadata","body"],storedFields:["selected-metadata","body"],updates:"delta",evidence:["src/mail-sync.ts"],limitations:["Attachment bytes and original MIME are not included; message body has a documented cap."]})),...methods.filter(m=>m.effect==="read").map(m=>({resource:m.name,read:"implemented",acquisition:"lookup",persistence:"unimplemented",readFields:["response"],storedFields:[],updates:"lookup",evidence:["src/actions.ts","https://learn.microsoft.com/graph/api/overview"],limitations:["Selected Action response is not persisted by the mailbox walker. Required scopes and selected account admission are checked at execution."]}))];const fail=(code,message)=>businessError(code,message,"plugin");function params(input){if(input.body!==void 0||input.media!==void 0)throw Error("outlook_actions_take_params_only");return input.params}function segment(value){if(typeof value!=="string"||!value||value.length>2048)throw Error("invalid_outlook_identifier");return encodeURIComponent(value)}function boundedObject(value){const encoded=JSON.stringify(value);if(!value||typeof value!=="object"||Array.isArray(value)||encoded.length>1e6)throw Error("invalid_outlook_body");return encoded}function addPage(url,p){if(p.top!==void 0)url.searchParams.set("$top",String(p.top));if(p.skipToken!==void 0)url.searchParams.set("$skiptoken",String(p.skipToken))}function nextLink(value){if(typeof value!=="string"||!value)throw Error("invalid_outlook_delta_link");const url=new URL(value);if(url.origin!=="https://graph.microsoft.com"||!url.pathname.startsWith("/v1.0/"))throw Error("invalid_outlook_delta_link");return url}function providerFailure(status){if(status===400)return fail("invalid_argument","Microsoft Graph rejected the Action parameters.");if(status===401)return fail("failed_precondition","Microsoft authorization is no longer valid.");if(status===403)return fail("permission_denied","Microsoft Graph refused the required permission.");if(status===404)return fail("not_found","Microsoft Graph could not find the requested resource.");if(status===429)return fail("resource_exhausted","Microsoft Graph rate-limited this Action.");return fail("unavailable","Microsoft Graph did not complete this Action.")}async function actionBody(response,limit){const declared=Number(response.headers.get("content-length"));if(Number.isFinite(declared)&&declared>limit){await response.body?.cancel().catch(()=>{});return}if(!response.body)return new Uint8Array;const reader=response.body.getReader(),chunks=[];let length=0,complete=false;try{for(;;){const next=await reader.read();if(next.done){complete=true;return Buffer.concat(chunks,length)}length+=next.value.byteLength;if(length>limit)return;chunks.push(next.value)}}finally{if(!complete)await reader.cancel().catch(()=>{});reader.releaseLock()}}export function createOutlookActions(resolveGrant,transport=fetch){async function request(required,url,method,body,signal,raw=false){const grant=await resolveGrant(signal);if(!("ok"in grant))return grant;if(required.some(scope=>!grant.ok.scopes.includes(scope)&&!grant.ok.scopes.includes("https://graph.microsoft.com/"+scope)))return fail("permission_denied","Reconnect Outlook with the scopes required by this Action.");signal=grant.ok.signal??signal;const checked=await grant.ok.check?.(signal);if(checked&&!("ok"in checked))return checked;const complete=async value=>{const final=await grant.ok.check?.(signal);return final&&!("ok"in final)?final:ok(value)};try{const response=await transport(url.href,{method,headers:{Authorization:"Bearer "+grant.ok.accessToken,...body===void 0?{}:{"Content-Type":"application/json"},...!raw?{Prefer:'outlook.body-content-type="text"'}:{}},...body===void 0?{}:{body:boundedObject(body)},signal:AbortSignal.any([signal,AbortSignal.timeout(45e3)]),redirect:"error"});if(!response.ok)return providerFailure(response.status);if(response.status===204)return complete({status:204,deleted:true});const bytes=await actionBody(response,raw?1048576:2e6);if(!bytes)return fail("resource_exhausted",raw?"Outlook content exceeds the 1 MiB L1 Action limit.":"Outlook response exceeds the 2 MB L1 Action limit.");if(raw)return complete({bytes:bytes.length,mime:response.headers.get("content-type")||"application/octet-stream",encoding:"base64",content:Buffer.from(bytes).toString("base64")});const text2=new TextDecoder().decode(bytes);try{return complete(text2?JSON.parse(text2):{})}catch{return fail("data_loss","Microsoft Graph returned malformed JSON.")}}catch{return fail(signal.aborted?"aborted":"unavailable","Microsoft Graph Action request did not complete.")}}return{catalog(){return ok({source:SOURCE,total:methods.length,methods:methods.map(({inputSchema:_,scopes:__,...row})=>({...row,level:1}))})},method(name){const row=methods.find(method=>method.name===name);return row?ok({...structuredClone(row),level:1}):fail("not_found",`Outlook has no action ${String(name).slice(0,100)}.`)},async invoke(name,input,options){try{const p=params(input),signal=options?.signal??new AbortController().signal,row=methods.find(method2=>method2.name===name);if(!row)return fail("not_found",`Outlook has no action ${String(name).slice(0,100)}.`);const scopes=row.scopes;let url=new URL(API),method="GET",body,raw=false;if(name==="outlook.identity")url=new URL(API+"/me?$select=id,displayName,mail,userPrincipalName");else if(name==="outlook.mail.folders.list"){url=new URL(API+"/me/mailFolders");addPage(url,p);if(p.includeHidden!==void 0)url.searchParams.set("includeHiddenFolders",String(p.includeHidden))}else if(name==="outlook.mail.folders.delta")url=p.deltaLink?nextLink(p.deltaLink):new URL(API+"/me/mailFolders/delta");else if(name==="outlook.mail.messages.list"){url=new URL(API+"/me/messages");addPage(url,p);if(p.search!==void 0)url.searchParams.set("$search",JSON.stringify(p.search));if(p.filter!==void 0)url.searchParams.set("$filter",String(p.filter));url.searchParams.set("$select","id,subject,body,bodyPreview,from,toRecipients,receivedDateTime,webLink,hasAttachments,categories,parentFolderId")}else if(name==="outlook.mail.messages.get")url=new URL(API+"/me/messages/"+segment(p.messageId)+"?$select=id,subject,body,bodyPreview,internetMessageHeaders,from,toRecipients,ccRecipients,bccRecipients,receivedDateTime,sentDateTime,webLink,hasAttachments,categories,parentFolderId");else if(name==="outlook.mail.messages.mime"){url=new URL(API+"/me/messages/"+segment(p.messageId)+"/$value");raw=true}else if(name==="outlook.mail.messages.delta"){url=p.deltaLink?nextLink(p.deltaLink):new URL(API+"/me/mailFolders/"+segment(p.folderId)+"/messages/delta");addPage(url,p)}else if(name==="outlook.mail.attachments.list"){url=new URL(API+"/me/messages/"+segment(p.messageId)+"/attachments");addPage(url,p)}else if(name==="outlook.mail.attachments.download"){url=new URL(API+"/me/messages/"+segment(p.messageId)+"/attachments/"+segment(p.attachmentId)+"/$value");raw=true}else if(name==="outlook.mail.drafts.create"){url=new URL(API+"/me/messages");method="POST";body=p.message}else if(name==="outlook.mail.messages.delete"){url=new URL(API+"/me/messages/"+segment(p.messageId));method="DELETE"}else if(name==="outlook.calendars.list"){url=new URL(API+"/me/calendars");addPage(url,p)}else if(name==="outlook.events.list"){url=new URL(API+"/me/calendars/"+segment(p.calendarId)+"/events");addPage(url,p);if(p.filter!==void 0)url.searchParams.set("$filter",String(p.filter))}else if(name==="outlook.events.get")url=new URL(API+"/me/calendars/"+segment(p.calendarId)+"/events/"+segment(p.eventId));else if(name==="outlook.events.delta"){if(p.deltaLink)url=nextLink(p.deltaLink);else{url=new URL(API+"/me/calendarView/delta");url.searchParams.set("startDateTime",String(p.startDateTime));url.searchParams.set("endDateTime",String(p.endDateTime))}}else if(name==="outlook.events.create"){url=new URL(API+"/me/calendars/"+segment(p.calendarId)+"/events");method="POST";body=p.event}else if(name==="outlook.events.delete"){url=new URL(API+"/me/calendars/"+segment(p.calendarId)+"/events/"+segment(p.eventId));method="DELETE"}else if(name==="outlook.contacts.list"){url=new URL(API+"/me/contacts");addPage(url,p)}else if(name==="outlook.contacts.get")url=new URL(API+"/me/contacts/"+segment(p.contactId));else if(name==="outlook.contacts.delta")url=p.deltaLink?nextLink(p.deltaLink):new URL(API+"/me/contacts/delta");else if(name==="outlook.contacts.create"){url=new URL(API+"/me/contacts");method="POST";body=p.contact}else if(name==="outlook.contacts.delete"){url=new URL(API+"/me/contacts/"+segment(p.contactId));method="DELETE"}else if(name==="outlook.categories.list"){url=new URL(API+"/me/outlook/masterCategories");addPage(url,p)}else if(name==="outlook.categories.create"){url=new URL(API+"/me/outlook/masterCategories");method="POST";body=p.category}else{url=new URL(API+"/me/outlook/masterCategories/"+segment(p.categoryId));method="DELETE"}return request(scopes,url,method,body,signal,raw)}catch(error){const message=error instanceof Error?error.message:"outlook_action_failed";return fail(options?.signal?.aborted?"aborted":message.startsWith("invalid_")?"invalid_argument":"unavailable",message)}}}}
|
|
1
|
+
import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{actionNotApplied,actionOutcome}from"@zortexhq/plugin-connector-core/api";const SOURCE="outlook",API="https://graph.microsoft.com/v1.0";const id={type:"string",minLength:1,maxLength:2048};const top={type:"integer",minimum:1,maximum:100};const text={type:"string",minLength:1,maxLength:1e4};const object={type:"object",minProperties:1,maxProperties:64};const methods=[{name:"outlook.identity",description:"Read the authorized Microsoft account identity.",httpMethod:"GET",effect:"read",scopes:["User.Read"],inputSchema:{type:"object",properties:{},additionalProperties:false}},{name:"outlook.mail.folders.list",description:"List mail folders, including hidden folders when requested.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{top,includeHidden:{type:"boolean"},skipToken:id},additionalProperties:false}},{name:"outlook.mail.folders.delta",description:"Read one independent mail-folder delta page.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{deltaLink:id},additionalProperties:false}},{name:"outlook.mail.messages.list",description:"List or search messages across every mail folder.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{top,search:text,filter:text,skipToken:id},additionalProperties:false}},{name:"outlook.mail.messages.get",description:"Read one message with headers and body.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{messageId:id},required:["messageId"],additionalProperties:false}},{name:"outlook.mail.messages.mime",description:"Download one message as MIME up to 1 MiB without storing it in Vault.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{messageId:id},required:["messageId"],additionalProperties:false}},{name:"outlook.mail.messages.delta",description:"Read one independent delta page for one exact mail folder.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{folderId:id,top,deltaLink:id},required:["folderId"],additionalProperties:false}},{name:"outlook.mail.attachments.list",description:"List attachment metadata for one message.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{messageId:id,top},required:["messageId"],additionalProperties:false}},{name:"outlook.mail.attachments.download",description:"Download one attachment up to 1 MiB without storing it in Vault.",httpMethod:"GET",effect:"read",scopes:["Mail.Read"],inputSchema:{type:"object",properties:{messageId:id,attachmentId:id},required:["messageId","attachmentId"],additionalProperties:false}},{name:"outlook.mail.drafts.create",description:"Create one unsent draft message for reversible verification.",httpMethod:"POST",effect:"write",scopes:["Mail.ReadWrite"],inputSchema:{type:"object",properties:{message:object},required:["message"],additionalProperties:false}},{name:"outlook.mail.messages.delete",description:"Delete one exact message or draft.",httpMethod:"DELETE",effect:"write",scopes:["Mail.ReadWrite"],inputSchema:{type:"object",properties:{messageId:id},required:["messageId"],additionalProperties:false}},{name:"outlook.calendars.list",description:"List calendars visible to the authorized account.",httpMethod:"GET",effect:"read",scopes:["Calendars.ReadWrite"],inputSchema:{type:"object",properties:{top,skipToken:id},additionalProperties:false}},{name:"outlook.events.list",description:"List events from one exact calendar.",httpMethod:"GET",effect:"read",scopes:["Calendars.ReadWrite"],inputSchema:{type:"object",properties:{calendarId:id,top,filter:text,skipToken:id},required:["calendarId"],additionalProperties:false}},{name:"outlook.events.get",description:"Read one event from one exact calendar.",httpMethod:"GET",effect:"read",scopes:["Calendars.ReadWrite"],inputSchema:{type:"object",properties:{calendarId:id,eventId:id},required:["calendarId","eventId"],additionalProperties:false}},{name:"outlook.events.delta",description:"Read one independent calendar-view delta page for an exact time range.",httpMethod:"GET",effect:"read",scopes:["Calendars.ReadWrite"],inputSchema:{type:"object",properties:{startDateTime:{type:"string",format:"date-time"},endDateTime:{type:"string",format:"date-time"},deltaLink:id},required:["startDateTime","endDateTime"],additionalProperties:false}},{name:"outlook.events.create",description:"Create one event in an exact calendar for reversible verification.",httpMethod:"POST",effect:"write",scopes:["Calendars.ReadWrite"],inputSchema:{type:"object",properties:{calendarId:id,event:object},required:["calendarId","event"],additionalProperties:false}},{name:"outlook.events.delete",description:"Delete one exact event.",httpMethod:"DELETE",effect:"write",scopes:["Calendars.ReadWrite"],inputSchema:{type:"object",properties:{calendarId:id,eventId:id},required:["calendarId","eventId"],additionalProperties:false}},{name:"outlook.contacts.list",description:"List contacts visible to the authorized account.",httpMethod:"GET",effect:"read",scopes:["Contacts.ReadWrite"],inputSchema:{type:"object",properties:{top,skipToken:id},additionalProperties:false}},{name:"outlook.contacts.get",description:"Read one exact contact.",httpMethod:"GET",effect:"read",scopes:["Contacts.ReadWrite"],inputSchema:{type:"object",properties:{contactId:id},required:["contactId"],additionalProperties:false}},{name:"outlook.contacts.delta",description:"Read one independent contacts delta page.",httpMethod:"GET",effect:"read",scopes:["Contacts.ReadWrite"],inputSchema:{type:"object",properties:{deltaLink:id},additionalProperties:false}},{name:"outlook.contacts.create",description:"Create one contact for reversible verification.",httpMethod:"POST",effect:"write",scopes:["Contacts.ReadWrite"],inputSchema:{type:"object",properties:{contact:object},required:["contact"],additionalProperties:false}},{name:"outlook.contacts.delete",description:"Delete one exact contact.",httpMethod:"DELETE",effect:"write",scopes:["Contacts.ReadWrite"],inputSchema:{type:"object",properties:{contactId:id},required:["contactId"],additionalProperties:false}},{name:"outlook.categories.list",description:"List the account master categories.",httpMethod:"GET",effect:"read",scopes:["MailboxSettings.ReadWrite"],inputSchema:{type:"object",properties:{top},additionalProperties:false}},{name:"outlook.categories.create",description:"Create one master category for reversible verification.",httpMethod:"POST",effect:"write",scopes:["MailboxSettings.ReadWrite"],inputSchema:{type:"object",properties:{category:object},required:["category"],additionalProperties:false}},{name:"outlook.categories.delete",description:"Delete one exact master category.",httpMethod:"DELETE",effect:"write",scopes:["MailboxSettings.ReadWrite"],inputSchema:{type:"object",properties:{categoryId:id},required:["categoryId"],additionalProperties:false}}];export const outlookContent=[...["message","mail-folder"].map(resource=>({resource:`mailbox/${resource}`,read:"implemented",acquisition:"collection",persistence:"durable",readFields:["selected-metadata","body"],storedFields:["selected-metadata","body"],updates:"delta",evidence:["src/mail-sync.ts"],limitations:["Attachment bytes and original MIME are not included; message body has a documented cap."]})),...methods.filter(m=>m.effect==="read").map(m=>({resource:m.name,read:"implemented",acquisition:"lookup",persistence:"unimplemented",readFields:["response"],storedFields:[],updates:"lookup",evidence:["src/actions.ts","https://learn.microsoft.com/graph/api/overview"],limitations:["Selected Action response is not persisted by the mailbox walker. Required scopes and selected account admission are checked at execution."]}))];const fail=(code,message)=>businessError(code,message,"plugin");function params(input){if(input.body!==void 0||input.media!==void 0)throw Error("outlook_actions_take_params_only");return input.params}function segment(value){if(typeof value!=="string"||!value||value.length>2048)throw Error("invalid_outlook_identifier");return encodeURIComponent(value)}function boundedObject(value){const encoded=JSON.stringify(value);if(!value||typeof value!=="object"||Array.isArray(value)||encoded.length>1e6)throw Error("invalid_outlook_body");return encoded}function addPage(url,p){if(p.top!==void 0)url.searchParams.set("$top",String(p.top));if(p.skipToken!==void 0)url.searchParams.set("$skiptoken",String(p.skipToken))}function nextLink(value){if(typeof value!=="string"||!value)throw Error("invalid_outlook_delta_link");const url=new URL(value);if(url.origin!=="https://graph.microsoft.com"||!url.pathname.startsWith("/v1.0/"))throw Error("invalid_outlook_delta_link");return url}function providerFailure(status){if(status===400)return fail("invalid_argument","Microsoft Graph rejected the Action parameters.");if(status===401)return fail("failed_precondition","Microsoft authorization is no longer valid.");if(status===403)return fail("permission_denied","Microsoft Graph refused the required permission.");if(status===404)return fail("not_found","Microsoft Graph could not find the requested resource.");if(status===429)return fail("resource_exhausted","Microsoft Graph rate-limited this Action.");return fail("unavailable","Microsoft Graph did not complete this Action.")}async function actionBody(response,limit){const declared=Number(response.headers.get("content-length"));if(Number.isFinite(declared)&&declared>limit){await response.body?.cancel().catch(()=>{});return}if(!response.body)return new Uint8Array;const reader=response.body.getReader(),chunks=[];let length=0,complete=false;try{for(;;){const next=await reader.read();if(next.done){complete=true;return Buffer.concat(chunks,length)}length+=next.value.byteLength;if(length>limit)return;chunks.push(next.value)}}finally{if(!complete)await reader.cancel().catch(()=>{});reader.releaseLock()}}export function createOutlookActions(resolveGrant,transport=fetch){async function request(required,url,method,body,signal,raw=false,dispatch=()=>{}){const grant=await resolveGrant(signal);if(!("ok"in grant))return grant;if(required.some(scope=>!grant.ok.scopes.includes(scope)&&!grant.ok.scopes.includes("https://graph.microsoft.com/"+scope)))return fail("permission_denied","Reconnect Outlook with the scopes required by this Action.");signal=grant.ok.signal??signal;const checked=await grant.ok.check?.(signal);if(checked&&!("ok"in checked))return checked;const complete=async value=>{const final=await grant.ok.check?.(signal);return final&&!("ok"in final)?final:ok(value)};try{const payload=body===void 0?{}:{body:boundedObject(body)};if(method!=="GET")dispatch();const response=await transport(url.href,{method,headers:{Authorization:"Bearer "+grant.ok.accessToken,...body===void 0?{}:{"Content-Type":"application/json"},...!raw?{Prefer:'outlook.body-content-type="text"'}:{}},...payload,signal:AbortSignal.any([signal,AbortSignal.timeout(45e3)]),redirect:"error"});if(!response.ok)return providerFailure(response.status);if(response.status===204)return complete({status:204,deleted:true});const bytes=await actionBody(response,raw?1048576:2e6);if(!bytes)return fail("resource_exhausted",raw?"Outlook content exceeds the 1 MiB L1 Action limit.":"Outlook response exceeds the 2 MB L1 Action limit.");if(raw)return complete({bytes:bytes.length,mime:response.headers.get("content-type")||"application/octet-stream",encoding:"base64",content:Buffer.from(bytes).toString("base64")});const text2=new TextDecoder().decode(bytes);try{return complete(text2?JSON.parse(text2):{})}catch{return fail("data_loss","Microsoft Graph returned malformed JSON.")}}catch{return fail(signal.aborted?"aborted":"unavailable","Microsoft Graph Action request did not complete.")}}return{catalogSnapshot(){return{revision:"installed-v1",complete:true,actions:methods.map(row=>({...row,level:1}))}},catalog(){return ok({source:SOURCE,total:methods.length,methods:methods.map(({inputSchema:_,scopes:__,...row})=>({...row,level:1}))})},method(name){const row=methods.find(method=>method.name===name);return row?ok({...structuredClone(row),level:1}):fail("not_found",`Outlook has no action ${String(name).slice(0,100)}.`)},async invoke(name,input,options){let dispatched=false;const execute=async()=>{try{const p=params(input),signal=options?.signal??new AbortController().signal,row=methods.find(method2=>method2.name===name);if(!row)return fail("not_found",`Outlook has no action ${String(name).slice(0,100)}.`);const scopes=row.scopes;let url=new URL(API),method="GET",body,raw=false;if(name==="outlook.identity")url=new URL(API+"/me?$select=id,displayName,mail,userPrincipalName");else if(name==="outlook.mail.folders.list"){url=new URL(API+"/me/mailFolders");addPage(url,p);if(p.includeHidden!==void 0)url.searchParams.set("includeHiddenFolders",String(p.includeHidden))}else if(name==="outlook.mail.folders.delta")url=p.deltaLink?nextLink(p.deltaLink):new URL(API+"/me/mailFolders/delta");else if(name==="outlook.mail.messages.list"){url=new URL(API+"/me/messages");addPage(url,p);if(p.search!==void 0)url.searchParams.set("$search",JSON.stringify(p.search));if(p.filter!==void 0)url.searchParams.set("$filter",String(p.filter));url.searchParams.set("$select","id,subject,body,bodyPreview,from,toRecipients,receivedDateTime,webLink,hasAttachments,categories,parentFolderId")}else if(name==="outlook.mail.messages.get")url=new URL(API+"/me/messages/"+segment(p.messageId)+"?$select=id,subject,body,bodyPreview,internetMessageHeaders,from,toRecipients,ccRecipients,bccRecipients,receivedDateTime,sentDateTime,webLink,hasAttachments,categories,parentFolderId");else if(name==="outlook.mail.messages.mime"){url=new URL(API+"/me/messages/"+segment(p.messageId)+"/$value");raw=true}else if(name==="outlook.mail.messages.delta"){url=p.deltaLink?nextLink(p.deltaLink):new URL(API+"/me/mailFolders/"+segment(p.folderId)+"/messages/delta");addPage(url,p)}else if(name==="outlook.mail.attachments.list"){url=new URL(API+"/me/messages/"+segment(p.messageId)+"/attachments");addPage(url,p)}else if(name==="outlook.mail.attachments.download"){url=new URL(API+"/me/messages/"+segment(p.messageId)+"/attachments/"+segment(p.attachmentId)+"/$value");raw=true}else if(name==="outlook.mail.drafts.create"){url=new URL(API+"/me/messages");method="POST";body=p.message}else if(name==="outlook.mail.messages.delete"){url=new URL(API+"/me/messages/"+segment(p.messageId));method="DELETE"}else if(name==="outlook.calendars.list"){url=new URL(API+"/me/calendars");addPage(url,p)}else if(name==="outlook.events.list"){url=new URL(API+"/me/calendars/"+segment(p.calendarId)+"/events");addPage(url,p);if(p.filter!==void 0)url.searchParams.set("$filter",String(p.filter))}else if(name==="outlook.events.get")url=new URL(API+"/me/calendars/"+segment(p.calendarId)+"/events/"+segment(p.eventId));else if(name==="outlook.events.delta"){if(p.deltaLink)url=nextLink(p.deltaLink);else{url=new URL(API+"/me/calendarView/delta");url.searchParams.set("startDateTime",String(p.startDateTime));url.searchParams.set("endDateTime",String(p.endDateTime))}}else if(name==="outlook.events.create"){url=new URL(API+"/me/calendars/"+segment(p.calendarId)+"/events");method="POST";body=p.event}else if(name==="outlook.events.delete"){url=new URL(API+"/me/calendars/"+segment(p.calendarId)+"/events/"+segment(p.eventId));method="DELETE"}else if(name==="outlook.contacts.list"){url=new URL(API+"/me/contacts");addPage(url,p)}else if(name==="outlook.contacts.get")url=new URL(API+"/me/contacts/"+segment(p.contactId));else if(name==="outlook.contacts.delta")url=p.deltaLink?nextLink(p.deltaLink):new URL(API+"/me/contacts/delta");else if(name==="outlook.contacts.create"){url=new URL(API+"/me/contacts");method="POST";body=p.contact}else if(name==="outlook.contacts.delete"){url=new URL(API+"/me/contacts/"+segment(p.contactId));method="DELETE"}else if(name==="outlook.categories.list"){url=new URL(API+"/me/outlook/masterCategories");addPage(url,p)}else if(name==="outlook.categories.create"){url=new URL(API+"/me/outlook/masterCategories");method="POST";body=p.category}else{url=new URL(API+"/me/outlook/masterCategories/"+segment(p.categoryId));method="DELETE"}return request(scopes,url,method,body,signal,raw,()=>{dispatched=true})}catch(error){const message=error instanceof Error?error.message:"outlook_action_failed";return fail(options?.signal?.aborted?"aborted":message.startsWith("invalid_")?"invalid_argument":"unavailable",message)}};const result=await execute().catch(()=>fail("unavailable","Outlook Action did not complete."));return dispatched?actionOutcome(result,"unknown"):actionNotApplied(result)}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{readJson}from"./http.js";const SOURCE="slack",API="https://slack.com/api/";const text={type:"string",minLength:1,maxLength:4e4};const id={type:"string",minLength:1,maxLength:255};const cursor={type:"string",minLength:1,maxLength:2048};const limit={type:"integer",minimum:1,maximum:200};const timestamp={type:"string",pattern:"^[0-9]+(?:\\.[0-9]+)?$",maxLength:32};const methods=[{name:"slack.identity",description:"Read the authorized Slack workspace and user identity.",httpMethod:"GET",effect:"read",scopes:[],inputSchema:{type:"object",properties:{},additionalProperties:false}},{name:"slack.messages.search",description:"Search messages visible to the authorized Slack user.",httpMethod:"GET",effect:"read",scopes:["search:read"],inputSchema:{type:"object",properties:{query:text,count:{type:"integer",minimum:1,maximum:100},page:{type:"integer",minimum:1,maximum:100}},required:["query"],additionalProperties:false}},{name:"slack.conversations.list",description:"List public channels, private channels, DMs, and multi-person DMs visible to the authorized user.",httpMethod:"GET",effect:"read",scopes:["channels:read","groups:read","im:read","mpim:read"],inputSchema:{type:"object",properties:{types:{type:"string",enum:["public_channel,private_channel,mpim,im","public_channel","private_channel","mpim","im"]},limit,cursor,excludeArchived:{type:"boolean"}},additionalProperties:false}},{name:"slack.conversations.history",description:"Read a bounded page of messages from one authorized conversation.",httpMethod:"GET",effect:"read",scopes:["channels:history","groups:history","im:history","mpim:history"],inputSchema:{type:"object",properties:{channel:id,limit,cursor,oldest:timestamp,latest:timestamp,inclusive:{type:"boolean"}},required:["channel"],additionalProperties:false}},{name:"slack.conversations.replies",description:"Read a bounded thread, including its parent and replies.",httpMethod:"GET",effect:"read",scopes:["channels:history","groups:history","im:history","mpim:history"],inputSchema:{type:"object",properties:{channel:id,ts:timestamp,limit,cursor,oldest:timestamp,latest:timestamp,inclusive:{type:"boolean"}},required:["channel","ts"],additionalProperties:false}},{name:"slack.conversations.members",description:"List the members of one authorized conversation.",httpMethod:"GET",effect:"read",scopes:["channels:read","groups:read","im:read","mpim:read"],inputSchema:{type:"object",properties:{channel:id,limit,cursor},required:["channel"],additionalProperties:false}},{name:"slack.users.list",description:"List workspace members visible to the authorized Slack user.",httpMethod:"GET",effect:"read",scopes:["users:read"],inputSchema:{type:"object",properties:{limit,cursor,includeLocale:{type:"boolean"}},additionalProperties:false}},{name:"slack.reactions.get",description:"Read reactions on one message.",httpMethod:"GET",effect:"read",scopes:["reactions:read"],inputSchema:{type:"object",properties:{channel:id,timestamp,full:{type:"boolean"}},required:["channel","timestamp"],additionalProperties:false}},{name:"slack.files.info",description:"Read metadata for one Slack file.",httpMethod:"GET",effect:"read",scopes:["files:read"],inputSchema:{type:"object",properties:{file:id},required:["file"],additionalProperties:false}},{name:"slack.files.download",description:"Download one authorized Slack file up to 1 MiB and return its bytes as base64 without storing them in Vault.",httpMethod:"GET",effect:"read",scopes:["files:read"],inputSchema:{type:"object",properties:{file:id},required:["file"],additionalProperties:false}},{name:"slack.conversations.open",description:"Open or resume a DM or multi-person DM with exact workspace user ids.",httpMethod:"POST",effect:"write",scopes:["im:write","mpim:write"],inputSchema:{type:"object",properties:{users:{type:"array",items:id,minItems:1,maxItems:8,uniqueItems:true},returnIm:{type:"boolean"}},required:["users"],additionalProperties:false}},{name:"slack.conversations.create",description:"Create one public or private channel with an exact Slack channel name.",httpMethod:"POST",effect:"write",scopes:["channels:write","groups:write"],inputSchema:{type:"object",properties:{name:{type:"string",pattern:"^[a-z0-9_-]{1,80}$"},isPrivate:{type:"boolean"}},required:["name","isPrivate"],additionalProperties:false}},{name:"slack.conversations.archive",description:"Archive one exact public or private Slack channel.",httpMethod:"POST",effect:"write",scopes:["channels:write","groups:write"],inputSchema:{type:"object",properties:{channel:id},required:["channel"],additionalProperties:false}},{name:"slack.chat.postMessage",description:"Post one message to an exact authorized conversation.",httpMethod:"POST",effect:"write",scopes:["chat:write"],inputSchema:{type:"object",properties:{channel:id,text,threadTs:timestamp},required:["channel","text"],additionalProperties:false}},{name:"slack.chat.delete",description:"Delete one exact message created by the authorized user.",httpMethod:"POST",effect:"write",scopes:["chat:write"],inputSchema:{type:"object",properties:{channel:id,ts:timestamp},required:["channel","ts"],additionalProperties:false}},{name:"slack.reactions.add",description:"Add one emoji reaction to an exact message.",httpMethod:"POST",effect:"write",scopes:["reactions:write"],inputSchema:{type:"object",properties:{channel:id,timestamp,name:{type:"string",pattern:"^[A-Za-z0-9_+\\-]+$",maxLength:100}},required:["channel","timestamp","name"],additionalProperties:false}},{name:"slack.reactions.remove",description:"Remove one emoji reaction added by the authorized user.",httpMethod:"POST",effect:"write",scopes:["reactions:write"],inputSchema:{type:"object",properties:{channel:id,timestamp,name:{type:"string",pattern:"^[A-Za-z0-9_+\\-]+$",maxLength:100}},required:["channel","timestamp","name"],additionalProperties:false}}];const fail=(code,message)=>businessError(code,message,"plugin");function params(input){if(input.body!==void 0||input.media!==void 0)throw Error("slack_actions_take_params_only");return input.params}function present(value){return value===void 0?void 0:Array.isArray(value)?value.join(","):String(value)}function providerError(error){const name=String(error??"unknown_error");if(["invalid_auth","not_authed","token_revoked","token_expired","account_inactive"].includes(name))return fail("failed_precondition","Slack authorization is no longer valid.");if(["missing_scope","not_allowed_token_type","no_permission","access_denied","restricted_action"].includes(name))return fail("permission_denied","Slack refused the required permission for this Action.");if(["channel_not_found","message_not_found","file_not_found","user_not_found"].includes(name))return fail("not_found","Slack could not find the requested resource.");if(["invalid_arguments","invalid_arg_name","invalid_array_arg","invalid_charset"].includes(name))return fail("invalid_argument","Slack rejected the Action parameters.");if(name==="ratelimited")return fail("resource_exhausted","Slack rate-limited this Action.");return fail("unavailable","Slack did not complete this Action.")}export function createSlackActions(resolveGrant,transport=fetch){async function call(method,p,required,signal){const grant=await resolveGrant(signal);if(!("ok"in grant))return grant;if(required.some(scope=>!grant.ok.scopes.includes(scope)))return fail("permission_denied","Reconnect Slack with the scopes required by "+method+".");signal=grant.ok.signal??signal;const checked=await grant.ok.check?.(signal);if(checked&&!("ok"in checked))return checked;const post=method.startsWith("chat.")||method.startsWith("reactions.")||["conversations.open","conversations.create","conversations.archive"].includes(method),url=new URL(API+method),body=new URLSearchParams;for(const[key,value]of Object.entries(p)){const valueText=present(value);if(valueText!==void 0)(post?body:url.searchParams).set(key.replace(/[A-Z]/g,c=>"_"+c.toLowerCase()),valueText)}try{const response=await readJson(url.href,{method:post?"POST":"GET",headers:{Authorization:"Bearer "+grant.ok.accessToken,...post?{"Content-Type":"application/x-www-form-urlencoded"}:{}},...post?{body:body.toString()}:{},signal},transport);if(response.ok!==true)return providerError(response.error);const final=await grant.ok.check?.(signal);return final&&!("ok"in final)?final:ok(response)}catch{return fail(signal.aborted?"aborted":"unavailable","Slack Action request did not complete.")}}async function download(file,signal){if(typeof file!=="string"||!file)return fail("invalid_argument","An exact Slack file id is required.");const grant=await resolveGrant(signal);if(!("ok"in grant))return grant;if(!grant.ok.scopes.includes("files:read"))return fail("permission_denied","Reconnect Slack with files:read.");const metadata=await call("files.info",{file},["files:read"],signal);if(!("ok"in metadata))return metadata;const row=metadata.ok.file;if(!row||typeof row!=="object"||Array.isArray(row))return fail("data_loss","Slack returned malformed file metadata.");const urlText=row.url_private_download??row.url_private;if(typeof urlText!=="string")return fail("failed_precondition","This Slack file has no downloadable content URL.");signal=grant.ok.signal??signal;const checked=await grant.ok.check?.(signal);if(checked&&!("ok"in checked))return checked;const url=new URL(urlText);if(url.protocol!=="https:"||!(url.hostname==="files.slack.com"||url.hostname.endsWith(".slack.com")))return fail("data_loss","Slack returned an untrusted file URL.");try{const response=await transport(url.href,{headers:{Authorization:"Bearer "+grant.ok.accessToken},redirect:"error",signal:AbortSignal.any([signal,AbortSignal.timeout(45e3)])});if(!response.ok)return providerError(response.status===404?"file_not_found":response.status===403?"no_permission":"download_failed");const reader=response.body?.getReader();if(!reader)return fail("data_loss","Slack file response had no body.");const chunks=[];let bytes=0;for(;;){const next=await reader.read();if(next.done)break;bytes+=next.value.length;if(bytes>1024*1024){await reader.cancel();return fail("resource_exhausted","Slack file exceeds the 1 MiB L1 response limit.")}chunks.push(next.value)}const final=await grant.ok.check?.(signal);if(final&&!("ok"in final))return final;return ok({file,row,bytes,mime:response.headers.get("content-type")??"application/octet-stream",content:Buffer.concat(chunks).toString("base64"),encoding:"base64"})}catch{return fail(signal.aborted?"aborted":"unavailable","Slack file download did not complete.")}}return{catalog(){return ok({source:SOURCE,total:methods.length,methods:methods.map(({inputSchema:_,scopes,...row})=>({...row,level:1,requiredScopes:[...scopes]}))})},method(name){const row=methods.find(method=>method.name===name);return row?ok({...structuredClone(row),level:1}):fail("not_found",`Slack has no Action ${String(name).slice(0,100)}.`)},async invoke(name,input,options={}){const row=methods.find(method=>method.name===name);if(!row)return fail("not_found",`Slack has no Action ${String(name).slice(0,100)}.`);const signal=options.signal??new AbortController().signal;if(signal.aborted)return fail("aborted","Slack Action was cancelled.");try{const p=params(input);if(name==="slack.files.download")return download(p.file,signal);const method=name==="slack.identity"?"auth.test":name==="slack.messages.search"?"search.messages":name.slice("slack.".length);return call(method,p,row.scopes,signal)}catch(error){return fail("invalid_argument",error instanceof Error?error.message:"Invalid Slack Action input.")}}}}
|
|
1
|
+
import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{actionNotApplied,actionOutcome}from"@zortexhq/plugin-connector-core/api";import{readJson}from"./http.js";const SOURCE="slack",API="https://slack.com/api/";const text={type:"string",minLength:1,maxLength:4e4};const id={type:"string",minLength:1,maxLength:255};const cursor={type:"string",minLength:1,maxLength:2048};const limit={type:"integer",minimum:1,maximum:200};const timestamp={type:"string",pattern:"^[0-9]+(?:\\.[0-9]+)?$",maxLength:32};const methods=[{name:"slack.identity",description:"Read the authorized Slack workspace and user identity.",httpMethod:"GET",effect:"read",scopes:[],inputSchema:{type:"object",properties:{},additionalProperties:false}},{name:"slack.messages.search",description:"Search messages visible to the authorized Slack user.",httpMethod:"GET",effect:"read",scopes:["search:read"],inputSchema:{type:"object",properties:{query:text,count:{type:"integer",minimum:1,maximum:100},page:{type:"integer",minimum:1,maximum:100}},required:["query"],additionalProperties:false}},{name:"slack.conversations.list",description:"List public channels, private channels, DMs, and multi-person DMs visible to the authorized user.",httpMethod:"GET",effect:"read",scopes:["channels:read","groups:read","im:read","mpim:read"],inputSchema:{type:"object",properties:{types:{type:"string",enum:["public_channel,private_channel,mpim,im","public_channel","private_channel","mpim","im"]},limit,cursor,excludeArchived:{type:"boolean"}},additionalProperties:false}},{name:"slack.conversations.history",description:"Read a bounded page of messages from one authorized conversation.",httpMethod:"GET",effect:"read",scopes:["channels:history","groups:history","im:history","mpim:history"],inputSchema:{type:"object",properties:{channel:id,limit,cursor,oldest:timestamp,latest:timestamp,inclusive:{type:"boolean"}},required:["channel"],additionalProperties:false}},{name:"slack.conversations.replies",description:"Read a bounded thread, including its parent and replies.",httpMethod:"GET",effect:"read",scopes:["channels:history","groups:history","im:history","mpim:history"],inputSchema:{type:"object",properties:{channel:id,ts:timestamp,limit,cursor,oldest:timestamp,latest:timestamp,inclusive:{type:"boolean"}},required:["channel","ts"],additionalProperties:false}},{name:"slack.conversations.members",description:"List the members of one authorized conversation.",httpMethod:"GET",effect:"read",scopes:["channels:read","groups:read","im:read","mpim:read"],inputSchema:{type:"object",properties:{channel:id,limit,cursor},required:["channel"],additionalProperties:false}},{name:"slack.users.list",description:"List workspace members visible to the authorized Slack user.",httpMethod:"GET",effect:"read",scopes:["users:read"],inputSchema:{type:"object",properties:{limit,cursor,includeLocale:{type:"boolean"}},additionalProperties:false}},{name:"slack.reactions.get",description:"Read reactions on one message.",httpMethod:"GET",effect:"read",scopes:["reactions:read"],inputSchema:{type:"object",properties:{channel:id,timestamp,full:{type:"boolean"}},required:["channel","timestamp"],additionalProperties:false}},{name:"slack.files.info",description:"Read metadata for one Slack file.",httpMethod:"GET",effect:"read",scopes:["files:read"],inputSchema:{type:"object",properties:{file:id},required:["file"],additionalProperties:false}},{name:"slack.files.download",description:"Download one authorized Slack file up to 1 MiB and return its bytes as base64 without storing them in Vault.",httpMethod:"GET",effect:"read",scopes:["files:read"],inputSchema:{type:"object",properties:{file:id},required:["file"],additionalProperties:false}},{name:"slack.conversations.open",description:"Open or resume a DM or multi-person DM with exact workspace user ids.",httpMethod:"POST",effect:"write",scopes:["im:write","mpim:write"],inputSchema:{type:"object",properties:{users:{type:"array",items:id,minItems:1,maxItems:8,uniqueItems:true},returnIm:{type:"boolean"}},required:["users"],additionalProperties:false}},{name:"slack.conversations.create",description:"Create one public or private channel with an exact Slack channel name.",httpMethod:"POST",effect:"write",scopes:["channels:write","groups:write"],inputSchema:{type:"object",properties:{name:{type:"string",pattern:"^[a-z0-9_-]{1,80}$"},isPrivate:{type:"boolean"}},required:["name","isPrivate"],additionalProperties:false}},{name:"slack.conversations.archive",description:"Archive one exact public or private Slack channel.",httpMethod:"POST",effect:"write",scopes:["channels:write","groups:write"],inputSchema:{type:"object",properties:{channel:id},required:["channel"],additionalProperties:false}},{name:"slack.chat.postMessage",description:"Post one message to an exact authorized conversation.",httpMethod:"POST",effect:"write",scopes:["chat:write"],inputSchema:{type:"object",properties:{channel:id,text,threadTs:timestamp},required:["channel","text"],additionalProperties:false}},{name:"slack.chat.delete",description:"Delete one exact message created by the authorized user.",httpMethod:"POST",effect:"write",scopes:["chat:write"],inputSchema:{type:"object",properties:{channel:id,ts:timestamp},required:["channel","ts"],additionalProperties:false}},{name:"slack.reactions.add",description:"Add one emoji reaction to an exact message.",httpMethod:"POST",effect:"write",scopes:["reactions:write"],inputSchema:{type:"object",properties:{channel:id,timestamp,name:{type:"string",pattern:"^[A-Za-z0-9_+\\-]+$",maxLength:100}},required:["channel","timestamp","name"],additionalProperties:false}},{name:"slack.reactions.remove",description:"Remove one emoji reaction added by the authorized user.",httpMethod:"POST",effect:"write",scopes:["reactions:write"],inputSchema:{type:"object",properties:{channel:id,timestamp,name:{type:"string",pattern:"^[A-Za-z0-9_+\\-]+$",maxLength:100}},required:["channel","timestamp","name"],additionalProperties:false}}];const fail=(code,message)=>businessError(code,message,"plugin");function params(input){if(input.body!==void 0||input.media!==void 0)throw Error("slack_actions_take_params_only");return input.params}function present(value){return value===void 0?void 0:Array.isArray(value)?value.join(","):String(value)}function providerError(error){const name=String(error??"unknown_error");if(["invalid_auth","not_authed","token_revoked","token_expired","account_inactive"].includes(name))return fail("failed_precondition","Slack authorization is no longer valid.");if(["missing_scope","not_allowed_token_type","no_permission","access_denied","restricted_action"].includes(name))return fail("permission_denied","Slack refused the required permission for this Action.");if(["channel_not_found","message_not_found","file_not_found","user_not_found"].includes(name))return fail("not_found","Slack could not find the requested resource.");if(["invalid_arguments","invalid_arg_name","invalid_array_arg","invalid_charset"].includes(name))return fail("invalid_argument","Slack rejected the Action parameters.");if(name==="ratelimited")return fail("resource_exhausted","Slack rate-limited this Action.");return fail("unavailable","Slack did not complete this Action.")}export function createSlackActions(resolveGrant,transport=fetch){async function call(method,p,required,signal,dispatch=()=>{}){const grant=await resolveGrant(signal);if(!("ok"in grant))return grant;if(required.some(scope=>!grant.ok.scopes.includes(scope)))return fail("permission_denied","Reconnect Slack with the scopes required by "+method+".");signal=grant.ok.signal??signal;const checked=await grant.ok.check?.(signal);if(checked&&!("ok"in checked))return checked;const post=method.startsWith("chat.")||method.startsWith("reactions.")||["conversations.open","conversations.create","conversations.archive"].includes(method),url=new URL(API+method),body=new URLSearchParams;for(const[key,value]of Object.entries(p)){const valueText=present(value);if(valueText!==void 0)(post?body:url.searchParams).set(key.replace(/[A-Z]/g,c=>"_"+c.toLowerCase()),valueText)}try{if(post)dispatch();const response=await readJson(url.href,{method:post?"POST":"GET",headers:{Authorization:"Bearer "+grant.ok.accessToken,...post?{"Content-Type":"application/x-www-form-urlencoded"}:{}},...post?{body:body.toString()}:{},signal},transport);if(response.ok!==true)return providerError(response.error);const final=await grant.ok.check?.(signal);return final&&!("ok"in final)?final:ok(response)}catch{return fail(signal.aborted?"aborted":"unavailable","Slack Action request did not complete.")}}async function download(file,signal){if(typeof file!=="string"||!file)return fail("invalid_argument","An exact Slack file id is required.");const grant=await resolveGrant(signal);if(!("ok"in grant))return grant;if(!grant.ok.scopes.includes("files:read"))return fail("permission_denied","Reconnect Slack with files:read.");const metadata=await call("files.info",{file},["files:read"],signal);if(!("ok"in metadata))return metadata;const row=metadata.ok.file;if(!row||typeof row!=="object"||Array.isArray(row))return fail("data_loss","Slack returned malformed file metadata.");const urlText=row.url_private_download??row.url_private;if(typeof urlText!=="string")return fail("failed_precondition","This Slack file has no downloadable content URL.");signal=grant.ok.signal??signal;const checked=await grant.ok.check?.(signal);if(checked&&!("ok"in checked))return checked;const url=new URL(urlText);if(url.protocol!=="https:"||!(url.hostname==="files.slack.com"||url.hostname.endsWith(".slack.com")))return fail("data_loss","Slack returned an untrusted file URL.");try{const response=await transport(url.href,{headers:{Authorization:"Bearer "+grant.ok.accessToken},redirect:"error",signal:AbortSignal.any([signal,AbortSignal.timeout(45e3)])});if(!response.ok)return providerError(response.status===404?"file_not_found":response.status===403?"no_permission":"download_failed");const reader=response.body?.getReader();if(!reader)return fail("data_loss","Slack file response had no body.");const chunks=[];let bytes=0;for(;;){const next=await reader.read();if(next.done)break;bytes+=next.value.length;if(bytes>1024*1024){await reader.cancel();return fail("resource_exhausted","Slack file exceeds the 1 MiB L1 response limit.")}chunks.push(next.value)}const final=await grant.ok.check?.(signal);if(final&&!("ok"in final))return final;return ok({file,row,bytes,mime:response.headers.get("content-type")??"application/octet-stream",content:Buffer.concat(chunks).toString("base64"),encoding:"base64"})}catch{return fail(signal.aborted?"aborted":"unavailable","Slack file download did not complete.")}}return{catalogSnapshot(){return{revision:"installed-v1",complete:true,actions:methods.map(row=>({...row,level:1}))}},catalog(){return ok({source:SOURCE,total:methods.length,methods:methods.map(({inputSchema:_,scopes,...row})=>({...row,level:1,requiredScopes:[...scopes]}))})},method(name){const row=methods.find(method=>method.name===name);return row?ok({...structuredClone(row),level:1}):fail("not_found",`Slack has no Action ${String(name).slice(0,100)}.`)},async invoke(name,input,options={}){let dispatched=false;const execute=async()=>{const row=methods.find(method=>method.name===name);if(!row)return fail("not_found",`Slack has no Action ${String(name).slice(0,100)}.`);const signal=options.signal??new AbortController().signal;if(signal.aborted)return fail("aborted","Slack Action was cancelled.");try{const p=params(input);if(name==="slack.files.download")return download(p.file,signal);const method=name==="slack.identity"?"auth.test":name==="slack.messages.search"?"search.messages":name.slice("slack.".length);return call(method,p,row.scopes,signal,()=>{dispatched=true})}catch(error){return fail("invalid_argument",error instanceof Error?error.message:"Invalid Slack Action input.")}};const result=await execute().catch(()=>fail("unavailable","Slack Action did not complete."));return dispatched?actionOutcome(result,"unknown"):actionNotApplied(result)}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{connectionState}from"@zortexhq/plugin-connector-core/api";import{readJson}from"./http.js";import{randomUUID}from"node:crypto";import{createSlackSelectedReader}from"./selected-read.js";import{createSlackActions}from"./actions.js";const CLIENT_ID="11967214494119.12069222086932";export const SLACK_SCOPE=["search:read","channels:read","groups:read","im:read","mpim:read","channels:history","groups:history","im:history","mpim:history","reactions:read","reactions:write","files:read","users:read","chat:write","channels:write","groups:write","im:write","mpim:write"].join(",");function wait(task,signal){return new Promise((resolve,reject)=>{const cancelled=()=>{signal.removeEventListener("abort",cancelled);reject(signal.reason??Error("Slack operation cancelled."))};signal.addEventListener("abort",cancelled,{once:true});task.then(value=>{signal.removeEventListener("abort",cancelled);resolve(value)},error=>{signal.removeEventListener("abort",cancelled);reject(error)});if(signal.aborted)cancelled()})}export function createSlackProvider({vault,enrollment,transport=fetch}){const info={source:"slack",label:"Slack",group:"Connector / \u804A\u5929",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["searchable_messages"],limitations:["search_api_limits"]}};let closed=false,closing;const stop=new AbortController,reader=createSlackSelectedReader(vault,transport),reused=new Map,pending=new Set;const fail=(code,message)=>businessError(code,message,"plugin");function track(task){pending.add(task);void task.then(()=>pending.delete(task),()=>pending.delete(task));return task}function connected(account){const job={id:randomUUID(),source:"slack",state:"connected",startedAt:new Date().toISOString(),account};reused.set(job.id,job);if(reused.size>32)reused.delete(reused.keys().next().value);return ok({...job})}async function grant(caller){if(closed)return businessError("unavailable","Slack source is inactive.","plugin");const signal=AbortSignal.any([caller,stop.signal]);const authorized=await reader.authorization(signal);if(!("ok"in authorized))return authorized;const{credential,check}=authorized.ok;try{const before=await check();if(!("ok"in before))return before;const identity=await readJson("https://slack.com/api/auth.test",{headers:{Authorization:"Bearer "+credential.accessToken},signal:authorized.ok.signal},transport);if(identity.ok!==true||identity.bot_id!==void 0||typeof identity.team_id!=="string"||typeof identity.user_id!=="string"||identity.team_id+":"+identity.user_id!==authorized.ok.accountId)return businessError("permission_denied","Slack native account does not match the selected connection.","auth");const after=await check();return"ok"in after?ok({accessToken:credential.accessToken,scopes:credential.scopes,check,signal:authorized.ok.signal,bindingId:authorized.ok.bindingId,account:authorized.ok.account}):after}catch{return businessError(signal.aborted?"aborted":"unavailable","Slack authorization could not be verified.","auth")}}async function connect(options,signal){const expected=options.expectedBinding?{...options.expectedBinding}:void 0;if(expected?.kind==="legacy-source"&&expected.source!=="slack")return fail("invalid_argument","Slack account selection names another source.");if(options.automatic!==false){const connection=await vault.connection("slack");if(!("ok"in connection))return connection;if(signal.aborted)return fail("aborted","Slack connection was stopped.");if(expected?.kind==="binding"){if(!vault.bindingCustody)return fail("failed_precondition","Slack requires verified account custody.");const resolved=await vault.bindingCustody.resolve({kind:"legacy-source",source:"slack"});if(!("ok"in resolved))return resolved;if(resolved.ok.kind!=="resolved"||resolved.ok.binding.id!==expected.bindingId)return fail("failed_precondition","Slack account selection does not match the existing grant.")}if(connection.ok){const authorized2=await grant(signal);if(!("ok"in authorized2))return authorized2;if(signal.aborted)return fail("aborted","Slack connection was stopped.");if(expected?.kind==="binding"&&authorized2.ok.bindingId!==expected.bindingId)return fail("failed_precondition","Slack account selection changed during authorization reuse.");return connected(authorized2.ok.account)}}if(signal.aborted)return fail("aborted","Slack connection was stopped.");const enrolled=await enrollment.pkce(info,{clientId:process.env.ZORTEX_SLACK_CLIENT_ID||CLIENT_ID,authorizeUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",scope:SLACK_SCOPE,driver:"slack"},async(token,signal2)=>{const user=token.authed_user??token;if(token.ok!==true||typeof user.access_token!=="string")throw Error("Slack denied authorization.");const profile=await readJson("https://slack.com/api/auth.test",{headers:{Authorization:"Bearer "+user.access_token},signal:signal2},transport);const nativeId=value=>typeof value==="string"&&value.length<=128&&/^[a-z0-9]+$/i.test(value);if(profile.ok!==true||!nativeId(profile.team_id)||!nativeId(profile.user_id))throw Error("Slack account not confirmed.");const scopes=String(user.scope??token.scope??"").split(",").filter(Boolean);if(SLACK_SCOPE.split(",").some(scope=>!scopes.includes(scope)))throw Error("Required Slack Action scope missing.");const accountId=profile.team_id+":"+profile.user_id;return{account:accountId,accountId,credential:{accessToken:user.access_token,...user.refresh_token?{refreshToken:user.refresh_token}:{},clientId:process.env.ZORTEX_SLACK_CLIENT_ID||CLIENT_ID,expiresAt:user.expires_in?Date.now()+Number(user.expires_in)*1e3:0,scopes}}},{...options,signal,...expected?{expectedBinding:expected}:{}});if("ok"in enrolled||!("err"in enrolled)||enrolled.err.code!=="failed_precondition"||signal.aborted)return enrolled;const saved=await vault.connection("slack");if(!("ok"in saved)||saved.ok?.state!=="connected")return enrolled;const authorized=await grant(signal);return"ok"in authorized&&!signal.aborted?connected(authorized.ok.account):enrolled}const actions=createSlackActions(grant,transport);const service={info,actions:{...actions,async invoke(name,input,options={}){if(closed)return fail("unavailable","Slack source is inactive.");const signal=AbortSignal.any([stop.signal,AbortSignal.timeout(45e3),...options.signal?[options.signal]:[]]);
|
|
1
|
+
import{actionNotApplied,withActionExecution}from"@zortexhq/plugin-connector-core/api";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{connectionState}from"@zortexhq/plugin-connector-core/api";import{readJson}from"./http.js";import{randomUUID}from"node:crypto";import{createSlackSelectedReader}from"./selected-read.js";import{createSlackActions}from"./actions.js";const CLIENT_ID="11967214494119.12069222086932";export const SLACK_SCOPE=["search:read","channels:read","groups:read","im:read","mpim:read","channels:history","groups:history","im:history","mpim:history","reactions:read","reactions:write","files:read","users:read","chat:write","channels:write","groups:write","im:write","mpim:write"].join(",");function wait(task,signal){return new Promise((resolve,reject)=>{const cancelled=()=>{signal.removeEventListener("abort",cancelled);reject(signal.reason??Error("Slack operation cancelled."))};signal.addEventListener("abort",cancelled,{once:true});task.then(value=>{signal.removeEventListener("abort",cancelled);resolve(value)},error=>{signal.removeEventListener("abort",cancelled);reject(error)});if(signal.aborted)cancelled()})}export function createSlackProvider({vault,enrollment,transport=fetch}){const info={source:"slack",label:"Slack",group:"Connector / \u804A\u5929",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["searchable_messages"],limitations:["search_api_limits"]}};let closed=false,closing;const stop=new AbortController,reader=createSlackSelectedReader(vault,transport),reused=new Map,pending=new Set;const fail=(code,message)=>businessError(code,message,"plugin");function track(task){pending.add(task);void task.then(()=>pending.delete(task),()=>pending.delete(task));return task}function connected(account){const job={id:randomUUID(),source:"slack",state:"connected",startedAt:new Date().toISOString(),account};reused.set(job.id,job);if(reused.size>32)reused.delete(reused.keys().next().value);return ok({...job})}async function grant(caller){if(closed)return businessError("unavailable","Slack source is inactive.","plugin");const signal=AbortSignal.any([caller,stop.signal]);const authorized=await reader.authorization(signal);if(!("ok"in authorized))return authorized;const{credential,check}=authorized.ok;try{const before=await check();if(!("ok"in before))return before;const identity=await readJson("https://slack.com/api/auth.test",{headers:{Authorization:"Bearer "+credential.accessToken},signal:authorized.ok.signal},transport);if(identity.ok!==true||identity.bot_id!==void 0||typeof identity.team_id!=="string"||typeof identity.user_id!=="string"||identity.team_id+":"+identity.user_id!==authorized.ok.accountId)return businessError("permission_denied","Slack native account does not match the selected connection.","auth");const after=await check();return"ok"in after?ok({accessToken:credential.accessToken,scopes:credential.scopes,check,signal:authorized.ok.signal,bindingId:authorized.ok.bindingId,account:authorized.ok.account}):after}catch{return businessError(signal.aborted?"aborted":"unavailable","Slack authorization could not be verified.","auth")}}async function connect(options,signal){const expected=options.expectedBinding?{...options.expectedBinding}:void 0;if(expected?.kind==="legacy-source"&&expected.source!=="slack")return fail("invalid_argument","Slack account selection names another source.");if(options.automatic!==false){const connection=await vault.connection("slack");if(!("ok"in connection))return connection;if(signal.aborted)return fail("aborted","Slack connection was stopped.");if(expected?.kind==="binding"){if(!vault.bindingCustody)return fail("failed_precondition","Slack requires verified account custody.");const resolved=await vault.bindingCustody.resolve({kind:"legacy-source",source:"slack"});if(!("ok"in resolved))return resolved;if(resolved.ok.kind!=="resolved"||resolved.ok.binding.id!==expected.bindingId)return fail("failed_precondition","Slack account selection does not match the existing grant.")}if(connection.ok){const authorized2=await grant(signal);if(!("ok"in authorized2))return authorized2;if(signal.aborted)return fail("aborted","Slack connection was stopped.");if(expected?.kind==="binding"&&authorized2.ok.bindingId!==expected.bindingId)return fail("failed_precondition","Slack account selection changed during authorization reuse.");return connected(authorized2.ok.account)}}if(signal.aborted)return fail("aborted","Slack connection was stopped.");const enrolled=await enrollment.pkce(info,{clientId:process.env.ZORTEX_SLACK_CLIENT_ID||CLIENT_ID,authorizeUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",scope:SLACK_SCOPE,driver:"slack"},async(token,signal2)=>{const user=token.authed_user??token;if(token.ok!==true||typeof user.access_token!=="string")throw Error("Slack denied authorization.");const profile=await readJson("https://slack.com/api/auth.test",{headers:{Authorization:"Bearer "+user.access_token},signal:signal2},transport);const nativeId=value=>typeof value==="string"&&value.length<=128&&/^[a-z0-9]+$/i.test(value);if(profile.ok!==true||!nativeId(profile.team_id)||!nativeId(profile.user_id))throw Error("Slack account not confirmed.");const scopes=String(user.scope??token.scope??"").split(",").filter(Boolean);if(SLACK_SCOPE.split(",").some(scope=>!scopes.includes(scope)))throw Error("Required Slack Action scope missing.");const accountId=profile.team_id+":"+profile.user_id;return{account:accountId,accountId,credential:{accessToken:user.access_token,...user.refresh_token?{refreshToken:user.refresh_token}:{},clientId:process.env.ZORTEX_SLACK_CLIENT_ID||CLIENT_ID,expiresAt:user.expires_in?Date.now()+Number(user.expires_in)*1e3:0,scopes}}},{...options,signal,...expected?{expectedBinding:expected}:{}});if("ok"in enrolled||!("err"in enrolled)||enrolled.err.code!=="failed_precondition"||signal.aborted)return enrolled;const saved=await vault.connection("slack");if(!("ok"in saved)||saved.ok?.state!=="connected")return enrolled;const authorized=await grant(signal);return"ok"in authorized&&!signal.aborted?connected(authorized.ok.account):enrolled}const actions=createSlackActions(grant,transport);const service={info,actions:{...actions,async invoke(name,input,options={}){if(closed)return actionNotApplied(fail("unavailable","Slack source is inactive."));const signal=AbortSignal.any([stop.signal,AbortSignal.timeout(45e3),...options.signal?[options.signal]:[]]);const task=track(actions.invoke(name,input,{...options,signal}));try{return withActionExecution(await wait(task,signal),task)}catch{return withActionExecution(fail(signal.aborted?"aborted":"unavailable","Slack Action did not complete."),task)}}},status:()=>connectionState(vault,info),job:id=>reused.has(id)?ok({...reused.get(id)}):enrollment.job(id),cancelJob:id=>enrollment.cancelJob(id),async connect(options={}){if(closed)return fail("unavailable","Slack source is inactive.");const signal=AbortSignal.any([stop.signal,...options.signal?[options.signal]:[]]);try{return await wait(track(connect(options,signal)),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Slack connection did not complete.")}},read:reader.read,close(){if(closing)return closing;closed=true;stop.abort();enrollment.cancelSource?.("slack");closing=Promise.all([reader.close(),(async()=>{while(pending.size)await Promise.allSettled([...pending])})()]).then(()=>{});return closing}};return service}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";const id={type:"string",minLength:1,maxLength:2048},top={type:"integer",minimum:1,maximum:100},object={type:"object",minProperties:1,maxProperties:64};const methods=[{name:"teams.identity",description:"Read the authorized Microsoft identity.",httpMethod:"GET",effect:"read",scopes:["User.Read"],inputSchema:{type:"object",properties:{},additionalProperties:false}},{name:"teams.teams.list",description:"List joined teams.",httpMethod:"GET",effect:"read",scopes:["Team.ReadBasic.All"],inputSchema:{type:"object",properties:{top},additionalProperties:false}},{name:"teams.channels.list",description:"List channels in one team.",httpMethod:"GET",effect:"read",scopes:["Channel.ReadBasic.All"],inputSchema:{type:"object",properties:{teamId:id,top},required:["teamId"],additionalProperties:false}},{name:"teams.members.list",description:"List members of one team.",httpMethod:"GET",effect:"read",scopes:["TeamMember.Read.All"],inputSchema:{type:"object",properties:{teamId:id,top},required:["teamId"],additionalProperties:false}},{name:"teams.chats.list",description:"List chats.",httpMethod:"GET",effect:"read",scopes:["Chat.ReadBasic"],inputSchema:{type:"object",properties:{top},additionalProperties:false}},{name:"teams.chat.messages.list",description:"List messages in one chat.",httpMethod:"GET",effect:"read",scopes:["Chat.Read"],inputSchema:{type:"object",properties:{chatId:id,top},required:["chatId"],additionalProperties:false}},{name:"teams.chat.messages.get",description:"Read one chat message.",httpMethod:"GET",effect:"read",scopes:["Chat.Read"],inputSchema:{type:"object",properties:{chatId:id,messageId:id},required:["chatId","messageId"],additionalProperties:false}},{name:"teams.chat.messages.create",description:"Create a chat message.",httpMethod:"POST",effect:"write",scopes:["ChatMessage.Send"],inputSchema:{type:"object",properties:{chatId:id,message:object},required:["chatId","message"],additionalProperties:false}},{name:"teams.chat.messages.update",description:"Update one chat message authored by the account.",httpMethod:"PATCH",effect:"write",scopes:["Chat.ReadWrite"],inputSchema:{type:"object",properties:{chatId:id,messageId:id,message:object},required:["chatId","messageId","message"],additionalProperties:false}},{name:"teams.channel.messages.list",description:"List root messages in one channel.",httpMethod:"GET",effect:"read",scopes:["ChannelMessage.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,top},required:["teamId","channelId"],additionalProperties:false}},{name:"teams.channel.messages.get",description:"Read one channel message.",httpMethod:"GET",effect:"read",scopes:["ChannelMessage.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,messageId:id},required:["teamId","channelId","messageId"],additionalProperties:false}},{name:"teams.channel.replies.list",description:"List replies to one channel message.",httpMethod:"GET",effect:"read",scopes:["ChannelMessage.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,messageId:id,top},required:["teamId","channelId","messageId"],additionalProperties:false}},{name:"teams.channel.messages.create",description:"Create a root channel message.",httpMethod:"POST",effect:"write",scopes:["ChannelMessage.Send"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,message:object},required:["teamId","channelId","message"],additionalProperties:false}},{name:"teams.channel.files.folder",description:"Read the SharePoint folder backing one channel.",httpMethod:"GET",effect:"read",scopes:["Files.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id},required:["teamId","channelId"],additionalProperties:false}},{name:"teams.meeting.recordings.list",description:"List recordings for one online meeting.",httpMethod:"GET",effect:"read",scopes:["OnlineMeetingRecording.Read.All"],inputSchema:{type:"object",properties:{userId:id,meetingId:id,top},required:["userId","meetingId"],additionalProperties:false}},{name:"teams.meeting.transcripts.list",description:"List transcripts for one online meeting.",httpMethod:"GET",effect:"read",scopes:["OnlineMeetingTranscript.Read.All"],inputSchema:{type:"object",properties:{userId:id,meetingId:id,top},required:["userId","meetingId"],additionalProperties:false}},{name:"teams.meeting.transcripts.content",description:"Read one meeting transcript as text.",httpMethod:"GET",effect:"read",scopes:["OnlineMeetingTranscript.Read.All"],inputSchema:{type:"object",properties:{userId:id,meetingId:id,transcriptId:id},required:["userId","meetingId","transcriptId"],additionalProperties:false}}];const fail=(code,message)=>businessError(code,message,"plugin");const params=input=>input&&typeof input==="object"&&!Array.isArray(input)&&input.params&&typeof input.params==="object"&&!Array.isArray(input.params)?input.params:{};const segment=value=>{if(typeof value!=="string"||!value||value.length>2048)throw Error("invalid_identifier");return encodeURIComponent(value)};const bounded=value=>{const json=JSON.stringify(value);if(json.length>1e6)throw Error("response_too_large");return value};function hasScope(granted,required){const accepted=required==="Chat.ReadBasic"?["Chat.ReadBasic","Chat.Read","Chat.ReadWrite"]:required==="Chat.Read"?["Chat.Read","Chat.ReadWrite"]:[required];return accepted.some(value=>granted.includes(value)||granted.includes("https://graph.microsoft.com/"+value))}export function createTeamsActions(resolveGrant,clientFactory){return{catalog(){return ok({source:"teams",total:methods.length,methods:methods.map(({inputSchema:_,scopes:__,...row})=>({...row,level:1}))})},method(name){const row=methods.find(method=>method.name===name);return row?ok({...structuredClone(row),level:1}):fail("not_found",`Teams has no action ${String(name).slice(0,100)}.`)},async invoke(name,input,options){try{const row=methods.find(method2=>method2.name===name);if(!row)return fail("not_found",`Teams has no action ${String(name).slice(0,100)}.`);let signal=options?.signal??new AbortController().signal;const grant=await resolveGrant(signal);if(!("ok"in grant))return grant;if(row.scopes.some(scope=>!hasScope(grant.ok.scopes,scope)))return fail("permission_denied","Reconnect Teams with the scopes required by this Action.");const p=params(input);let path="/me",method="get",body;if(name==="teams.teams.list")path="/me/joinedTeams";else if(name==="teams.channels.list")path=`/teams/${segment(p.teamId)}/channels`;else if(name==="teams.members.list")path=`/teams/${segment(p.teamId)}/members`;else if(name==="teams.chats.list")path="/me/chats";else if(name==="teams.chat.messages.list")path=`/chats/${segment(p.chatId)}/messages`;else if(name==="teams.chat.messages.get")path=`/chats/${segment(p.chatId)}/messages/${segment(p.messageId)}`;else if(name==="teams.chat.messages.create"){path=`/chats/${segment(p.chatId)}/messages`;method="post";body=p.message}else if(name==="teams.chat.messages.update"){path=`/chats/${segment(p.chatId)}/messages/${segment(p.messageId)}`;method="patch";body=p.message}else if(name==="teams.channel.messages.list")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages`;else if(name==="teams.channel.messages.get")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages/${segment(p.messageId)}`;else if(name==="teams.channel.replies.list")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages/${segment(p.messageId)}/replies`;else if(name==="teams.channel.messages.create"){path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages`;method="post";body=p.message}else if(name==="teams.channel.files.folder")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/filesFolder`;else if(name==="teams.meeting.recordings.list")path=`/users/${segment(p.userId)}/onlineMeetings/${segment(p.meetingId)}/recordings`;else if(name==="teams.meeting.transcripts.list")path=`/users/${segment(p.userId)}/onlineMeetings/${segment(p.meetingId)}/transcripts`;else if(name==="teams.meeting.transcripts.content")path=`/users/${segment(p.userId)}/onlineMeetings/${segment(p.meetingId)}/transcripts/${segment(p.transcriptId)}/content`;signal=grant.ok.signal??signal;const checked=await grant.ok.check?.(signal);if(checked&&!("ok"in checked))return checked;let request=clientFactory(grant.ok.accessToken,signal).api(path);if(p.top!==void 0)request=request.top(Math.min(100,Math.max(1,Number(p.top))));const
|
|
1
|
+
import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{actionNotApplied,actionOutcome}from"@zortexhq/plugin-connector-core/api";const id={type:"string",minLength:1,maxLength:2048},top={type:"integer",minimum:1,maximum:100},object={type:"object",minProperties:1,maxProperties:64};const methods=[{name:"teams.identity",description:"Read the authorized Microsoft identity.",httpMethod:"GET",effect:"read",scopes:["User.Read"],inputSchema:{type:"object",properties:{},additionalProperties:false}},{name:"teams.teams.list",description:"List joined teams.",httpMethod:"GET",effect:"read",scopes:["Team.ReadBasic.All"],inputSchema:{type:"object",properties:{top},additionalProperties:false}},{name:"teams.channels.list",description:"List channels in one team.",httpMethod:"GET",effect:"read",scopes:["Channel.ReadBasic.All"],inputSchema:{type:"object",properties:{teamId:id,top},required:["teamId"],additionalProperties:false}},{name:"teams.members.list",description:"List members of one team.",httpMethod:"GET",effect:"read",scopes:["TeamMember.Read.All"],inputSchema:{type:"object",properties:{teamId:id,top},required:["teamId"],additionalProperties:false}},{name:"teams.chats.list",description:"List chats.",httpMethod:"GET",effect:"read",scopes:["Chat.ReadBasic"],inputSchema:{type:"object",properties:{top},additionalProperties:false}},{name:"teams.chat.messages.list",description:"List messages in one chat.",httpMethod:"GET",effect:"read",scopes:["Chat.Read"],inputSchema:{type:"object",properties:{chatId:id,top},required:["chatId"],additionalProperties:false}},{name:"teams.chat.messages.get",description:"Read one chat message.",httpMethod:"GET",effect:"read",scopes:["Chat.Read"],inputSchema:{type:"object",properties:{chatId:id,messageId:id},required:["chatId","messageId"],additionalProperties:false}},{name:"teams.chat.messages.create",description:"Create a chat message.",httpMethod:"POST",effect:"write",scopes:["ChatMessage.Send"],inputSchema:{type:"object",properties:{chatId:id,message:object},required:["chatId","message"],additionalProperties:false}},{name:"teams.chat.messages.update",description:"Update one chat message authored by the account.",httpMethod:"PATCH",effect:"write",scopes:["Chat.ReadWrite"],inputSchema:{type:"object",properties:{chatId:id,messageId:id,message:object},required:["chatId","messageId","message"],additionalProperties:false}},{name:"teams.channel.messages.list",description:"List root messages in one channel.",httpMethod:"GET",effect:"read",scopes:["ChannelMessage.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,top},required:["teamId","channelId"],additionalProperties:false}},{name:"teams.channel.messages.get",description:"Read one channel message.",httpMethod:"GET",effect:"read",scopes:["ChannelMessage.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,messageId:id},required:["teamId","channelId","messageId"],additionalProperties:false}},{name:"teams.channel.replies.list",description:"List replies to one channel message.",httpMethod:"GET",effect:"read",scopes:["ChannelMessage.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,messageId:id,top},required:["teamId","channelId","messageId"],additionalProperties:false}},{name:"teams.channel.messages.create",description:"Create a root channel message.",httpMethod:"POST",effect:"write",scopes:["ChannelMessage.Send"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,message:object},required:["teamId","channelId","message"],additionalProperties:false}},{name:"teams.channel.files.folder",description:"Read the SharePoint folder backing one channel.",httpMethod:"GET",effect:"read",scopes:["Files.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id},required:["teamId","channelId"],additionalProperties:false}},{name:"teams.meeting.recordings.list",description:"List recordings for one online meeting.",httpMethod:"GET",effect:"read",scopes:["OnlineMeetingRecording.Read.All"],inputSchema:{type:"object",properties:{userId:id,meetingId:id,top},required:["userId","meetingId"],additionalProperties:false}},{name:"teams.meeting.transcripts.list",description:"List transcripts for one online meeting.",httpMethod:"GET",effect:"read",scopes:["OnlineMeetingTranscript.Read.All"],inputSchema:{type:"object",properties:{userId:id,meetingId:id,top},required:["userId","meetingId"],additionalProperties:false}},{name:"teams.meeting.transcripts.content",description:"Read one meeting transcript as text.",httpMethod:"GET",effect:"read",scopes:["OnlineMeetingTranscript.Read.All"],inputSchema:{type:"object",properties:{userId:id,meetingId:id,transcriptId:id},required:["userId","meetingId","transcriptId"],additionalProperties:false}}];const fail=(code,message)=>businessError(code,message,"plugin");const params=input=>input&&typeof input==="object"&&!Array.isArray(input)&&input.params&&typeof input.params==="object"&&!Array.isArray(input.params)?input.params:{};const segment=value=>{if(typeof value!=="string"||!value||value.length>2048)throw Error("invalid_identifier");return encodeURIComponent(value)};const bounded=value=>{const json=JSON.stringify(value);if(json.length>1e6)throw Error("response_too_large");return value};function hasScope(granted,required){const accepted=required==="Chat.ReadBasic"?["Chat.ReadBasic","Chat.Read","Chat.ReadWrite"]:required==="Chat.Read"?["Chat.Read","Chat.ReadWrite"]:[required];return accepted.some(value=>granted.includes(value)||granted.includes("https://graph.microsoft.com/"+value))}export function createTeamsActions(resolveGrant,clientFactory){return{catalogSnapshot(){return{revision:"installed-v1",complete:true,actions:methods.map(row=>({...row,level:1}))}},catalog(){return ok({source:"teams",total:methods.length,methods:methods.map(({inputSchema:_,scopes:__,...row})=>({...row,level:1}))})},method(name){const row=methods.find(method=>method.name===name);return row?ok({...structuredClone(row),level:1}):fail("not_found",`Teams has no action ${String(name).slice(0,100)}.`)},async invoke(name,input,options){let dispatched=false;const execute=async()=>{try{const row=methods.find(method2=>method2.name===name);if(!row)return fail("not_found",`Teams has no action ${String(name).slice(0,100)}.`);let signal=options?.signal??new AbortController().signal;const grant=await resolveGrant(signal);if(!("ok"in grant))return grant;if(row.scopes.some(scope=>!hasScope(grant.ok.scopes,scope)))return fail("permission_denied","Reconnect Teams with the scopes required by this Action.");const p=params(input);let path="/me",method="get",body;if(name==="teams.teams.list")path="/me/joinedTeams";else if(name==="teams.channels.list")path=`/teams/${segment(p.teamId)}/channels`;else if(name==="teams.members.list")path=`/teams/${segment(p.teamId)}/members`;else if(name==="teams.chats.list")path="/me/chats";else if(name==="teams.chat.messages.list")path=`/chats/${segment(p.chatId)}/messages`;else if(name==="teams.chat.messages.get")path=`/chats/${segment(p.chatId)}/messages/${segment(p.messageId)}`;else if(name==="teams.chat.messages.create"){path=`/chats/${segment(p.chatId)}/messages`;method="post";body=p.message}else if(name==="teams.chat.messages.update"){path=`/chats/${segment(p.chatId)}/messages/${segment(p.messageId)}`;method="patch";body=p.message}else if(name==="teams.channel.messages.list")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages`;else if(name==="teams.channel.messages.get")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages/${segment(p.messageId)}`;else if(name==="teams.channel.replies.list")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages/${segment(p.messageId)}/replies`;else if(name==="teams.channel.messages.create"){path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages`;method="post";body=p.message}else if(name==="teams.channel.files.folder")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/filesFolder`;else if(name==="teams.meeting.recordings.list")path=`/users/${segment(p.userId)}/onlineMeetings/${segment(p.meetingId)}/recordings`;else if(name==="teams.meeting.transcripts.list")path=`/users/${segment(p.userId)}/onlineMeetings/${segment(p.meetingId)}/transcripts`;else if(name==="teams.meeting.transcripts.content")path=`/users/${segment(p.userId)}/onlineMeetings/${segment(p.meetingId)}/transcripts/${segment(p.transcriptId)}/content`;signal=grant.ok.signal??signal;const checked=await grant.ok.check?.(signal);if(checked&&!("ok"in checked))return checked;let request=clientFactory(grant.ok.accessToken,signal).api(path);if(p.top!==void 0)request=request.top(Math.min(100,Math.max(1,Number(p.top))));if(method!=="get")dispatched=true;const result2=method==="get"?await request.get():method==="post"?await request.post(body):await request.patch(body);const final=await grant.ok.check?.(signal);return final&&!("ok"in final)?final:ok(bounded(result2))}catch(error){const invalid=error instanceof Error&&error.message==="invalid_identifier";return fail(options?.signal?.aborted?"aborted":invalid?"invalid_argument":"unavailable",invalid?"Teams Action requires valid resource identifiers.":"Microsoft Graph Teams Action did not complete.")}};const result=await execute();return dispatched?actionOutcome(result,"unknown"):actionNotApplied(result)}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{acquiredReadCapability,unreviewedActionContent}from"@zortexhq/plugin-connector-core/api";import{Client,RetryHandlerOptions}from"@microsoft/microsoft-graph-client";import{randomUUID}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{captureSelectedAccount,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{createTeamsActions}from"./actions.js";import{MICROSOFT_AUTHORITY,TEAMS_SCOPE,TEAMS_SCOPES,credentialExpiring,requestMicrosoftToken,teamsClientId}from"./token.js";const defaultClientFactory=(accessToken,signal)=>{const client=Client.init({authProvider:done=>done(null,accessToken),fetchOptions:{signal}});const retry=new RetryHandlerOptions(void 0,void 0,(_delay,_attempt,request,options)=>(typeof request==="string"?options?.method:request.method)==="GET");return{api:path=>client.api(path).middlewareOptions([retry])}};function scopePresent(scopes,required){return scopes.includes(required)||scopes.includes("https://graph.microsoft.com/"+required)}const validToken=value=>typeof value==="string"&&value.length>0&&value.length<=16384&&!/[\s\u0000-\u001f\u007f-\u009f]/u.test(value);const validScopes=value=>Array.isArray(value)&&value.length>0&&value.length<=64&&value.every(scope=>typeof scope==="string"&&/^[\x21-\x7e]{1,512}$/u.test(scope));const sameScopes=(left,right)=>JSON.stringify([...new Set(left)].sort())===JSON.stringify([...new Set(right)].sort());function wait(task,signal){return new Promise((resolve,reject)=>{const cancelled=()=>{signal.removeEventListener("abort",cancelled);reject(signal.reason??Error("Teams operation cancelled."))};signal.addEventListener("abort",cancelled,{once:true});task.then(value=>{signal.removeEventListener("abort",cancelled);resolve(value)},error=>{signal.removeEventListener("abort",cancelled);reject(error)});if(signal.aborted)cancelled()})}export function createTeamsProvider({vault,enrollment,transport=fetch,clientFactory=defaultClientFactory}){const info={content:[acquiredReadCapability(["plugins/connector-teams/README.md"]),unreviewedActionContent(["plugins/connector-teams/README.md"])],source:"teams",label:"Microsoft Teams",group:"Connector / Microsoft",auth:"oauth-browser"},stop=new AbortController;let closed=false,closing;const clientId=teamsClientId();const pending=new Set,connectedJobs=new Map;const fail=(code,message)=>businessError(code,message,"plugin");function track(task){pending.add(task);void task.then(()=>pending.delete(task),()=>pending.delete(task));return task}function authorized(snapshot,accountId){const{binding,grant:grant2,resource,material}=snapshot;if(binding.identity.source!=="teams"||binding.identity.issuer!=="microsoft"||binding.provider!=="microsoft"||binding.identity.subject!==accountId||binding.state!=="connected"||grant2.bindingId!==binding.id||grant2.purpose!=="L1"||grant2.audience!=="microsoft"||grant2.state!=="active"||resource.id!==oauthCredentialResourceId(binding.id)||resource.bindingId!==binding.id||resource.kind!=="oauth"||resource.owner.kind!=="resident"||material.kind!=="oauth")return fail("failed_precondition","Teams requires one verified native resident OAuth binding and L1 grant.");const credential=material.credential;if(!validScopes(grant2.scopes)||!validScopes(credential.scopes)||!sameScopes(grant2.scopes,credential.scopes))return fail("permission_denied","Teams credential scopes do not match the selected grant.");if(!validToken(credential.accessToken)||typeof credential.clientId!=="string"||!/^[\x21-\x7e]{1,512}$/u.test(credential.clientId)||!Number.isFinite(credential.expiresAt)||credential.expiresAt<=0||credential.expiresAt>864e13||credential.refreshToken!==void 0&&!validToken(credential.refreshToken))return fail("failed_precondition","Teams credential material is invalid; reconnect this source.");return ok(credential)}async function resolveGrant(signal){const selected=await captureSelectedAccount(vault,"teams",signal);if(!("ok"in selected))return selected;const authority=selected.ok;if(!vault.bindingCustody)return fail("failed_precondition","Teams operations require verified account custody.");const custody=vault.bindingCustody,resolution=await custody.resolve({kind:"legacy-source",source:"teams"});if(!("ok"in resolution))return resolution;if(resolution.ok.kind!=="resolved")return fail("failed_precondition","Select one verified Teams account binding.");const found=await custody.credentialSnapshot(oauthCredentialResourceId(resolution.ok.binding.id),{purpose:"L1",audience:"microsoft"});if(!("ok"in found))return found;let snapshot=found.ok,allowed=authorized(snapshot,authority.accountId);if(!("ok"in allowed))return allowed;async function fence(expected,active,requireFresh=true){const checked=await authority.check(active);if(!("ok"in checked))return checked;const current=await custody.resolve({kind:"legacy-source",source:"teams"});if(!("ok"in current))return current;if(current.ok.kind!=="resolved"||current.ok.binding.id!==expected.binding.id||current.ok.binding.revision!==expected.binding.revision)return fail("failed_precondition","Teams account selection changed during the operation.");const resource=await custody.resource(expected.resource.id);if(!("ok"in resource))return resource;if(resource.ok?.revision!==expected.resource.revision||resource.ok.owner.kind!=="resident")return fail("failed_precondition","Teams credential authority changed during the operation.");const credential=authorized(expected,authority.accountId);if(!("ok"in credential))return credential;if(requireFresh&&credential.ok.expiresAt<=Date.now())return fail("failed_precondition","Teams authorization expired during the operation.");return authority.check(active)}try{if(credentialExpiring(allowed.ok)){if(!allowed.ok.refreshToken)return fail("failed_precondition","Teams authorization expired; reconnect this source.");const before2=await fence(snapshot,signal,false);if(!("ok"in before2))return before2;const ownerSignal=AbortSignal.any([stop.signal,AbortSignal.timeout(45e3)]);const renewed=await track(custody.refreshResource(snapshot,{kind:"resident"},async current=>{const material=authorized(current,authority.accountId);if(!("ok"in material))return material;const checked=await fence(current,ownerSignal,false);if(!("ok"in checked))return checked;if(!material.ok.refreshToken)return fail("failed_precondition","Teams authorization expired; reconnect this source.");try{ownerSignal.throwIfAborted();const requestedAt=Date.now();const response=await wait(track(requestMicrosoftToken(transport,material.ok.clientId,{grant_type:"refresh_token",refresh_token:material.ok.refreshToken,scope:material.ok.scopes.join(" ")},ownerSignal)),ownerSignal),reply=response.body;const scopes=reply.scope===void 0?material.ok.scopes:typeof reply.scope==="string"&&reply.scope.length<=8192?reply.scope.trim().split(/\s+/u):[],expiresAt=requestedAt+Number(reply.expires_in)*1e3;if(response.status<200||response.status>=300||!validToken(reply.access_token)||typeof reply.token_type!=="string"||reply.token_type.toLowerCase()!=="bearer"||typeof reply.expires_in!=="number"||!Number.isFinite(reply.expires_in)||reply.expires_in<=0||!Number.isFinite(expiresAt)||expiresAt>864e13||expiresAt<=Date.now()||!validScopes(scopes)||!sameScopes(scopes,current.grant.scopes)||reply.refresh_token!==void 0&&!validToken(reply.refresh_token))return fail("failed_precondition","Teams refresh did not preserve token type, scope and expiry; reconnect this source.");const identity2=await wait(track(clientFactory(reply.access_token,ownerSignal).api("/me").select("id").get()),ownerSignal);if(identity2.id!==authority.accountId)return fail("permission_denied","Teams refreshed token does not match the selected native account.");const unchanged=await fence(current,ownerSignal,false);if(!("ok"in unchanged))return unchanged;if(expiresAt<=Date.now())return fail("failed_precondition","Teams refreshed access expired before custody completed.");return ok({kind:"oauth",credential:{...material.ok,accessToken:reply.access_token,...reply.refresh_token!==void 0?{refreshToken:reply.refresh_token}:{},expiresAt,scopes:[...material.ok.scopes]}})}catch{return fail("failed_precondition","Teams refresh did not complete; its rotating outcome must not be replayed.")}}));if(!("ok"in renewed))return renewed;snapshot=renewed.ok;allowed=authorized(snapshot,authority.accountId);if(!("ok"in allowed))return allowed}const before=await fence(snapshot,signal);if(!("ok"in before))return before;const identity=await clientFactory(allowed.ok.accessToken,signal).api("/me").select("id").get();if(identity.id!==authority.accountId)return businessError("permission_denied","Teams native account does not match the selected connection.","auth");const after=await fence(snapshot,signal);return"ok"in after?ok({accessToken:allowed.ok.accessToken,scopes:allowed.ok.scopes,check:(active=signal)=>fence(snapshot,active),signal,bindingId:snapshot.binding.id,account:snapshot.binding.account}):after}catch{return businessError(signal.aborted?"aborted":"unavailable","Teams authorization could not be verified.","auth")}}async function grant(caller){if(closed)return fail("unavailable","Teams source is inactive.");const signal=AbortSignal.any([caller,stop.signal,AbortSignal.timeout(45e3)]);try{return await wait(track(resolveGrant(signal)),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Teams account authority could not be confirmed.")}}async function connect(options,signal){const expected=options.expectedBinding?{...options.expectedBinding}:void 0;if(expected?.kind==="legacy-source"&&expected.source!=="teams")return fail("invalid_argument","Teams account selection names another source.");if(options.automatic!==false){const existing=await vault.connection("teams");if(!("ok"in existing))return existing;if(signal.aborted)return fail("aborted","Teams connection was stopped.");if(expected?.kind==="binding"){if(!vault.bindingCustody)return fail("failed_precondition","Teams requires verified account custody.");const selected=await vault.bindingCustody.resolve({kind:"legacy-source",source:"teams"});if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved"||selected.ok.binding.id!==expected.bindingId)return fail("failed_precondition","Teams account selection does not match the existing grant.")}if(existing.ok){const resolved=await grant(signal);if(!("ok"in resolved))return resolved;if(signal.aborted)return fail("aborted","Teams connection was stopped.");if(expected?.kind==="binding"&&resolved.ok.bindingId!==expected.bindingId)return fail("failed_precondition","Teams account selection changed during authorization reuse.");const job={id:randomUUID(),source:"teams",state:"connected",startedAt:new Date().toISOString(),account:resolved.ok.account};connectedJobs.set(job.id,job);if(connectedJobs.size>32)connectedJobs.delete(connectedJobs.keys().next().value);return ok({...job})}}if(signal.aborted)return fail("aborted","Teams connection was stopped.");if(!enrollment)return fail("unavailable","Connector enrollment is not installed.");return enrollment.pkce(info,{clientId,authorizeUrl:MICROSOFT_AUTHORITY+"authorize?prompt=select_account",tokenUrl:MICROSOFT_AUTHORITY+"token",scope:TEAMS_SCOPE,redirectPath:"/",provider:"microsoft",driver:"microsoft"},async(result,signal2)=>{if(!result.access_token||!Number.isFinite(result.expires_in))throw Error("Microsoft authorization failed.");const scopes=String(result.scope??"").split(" ").filter(Boolean);for(const required of TEAMS_SCOPES.filter(scope=>scope!=="offline_access"))if(!scopePresent(scopes,required))throw Error("Required Teams Action scope missing: "+required);const identity=await clientFactory(result.access_token,signal2).api("/me").select("id,displayName,mail,userPrincipalName").get();if(!identity.id||!(identity.mail||identity.userPrincipalName))throw Error("Microsoft account unconfirmed.");return{account:identity.mail||identity.userPrincipalName,accountId:identity.id,credential:{accessToken:result.access_token,...result.refresh_token?{refreshToken:result.refresh_token}:{},clientId,expiresAt:Date.now()+Number(result.expires_in)*1e3,scopes}}},{...options,signal,...expected?{expectedBinding:expected}:{}})}async function readSelected(request,signal){const resolved=await grant(signal);if(!("ok"in resolved))return resolved;if(!scopePresent(resolved.ok.scopes,"Chat.Read")&&!scopePresent(resolved.ok.scopes,"Chat.ReadWrite"))return fail("permission_denied","The selected Teams grant does not include chat message read access.");const nativeId=value=>typeof value==="string"&&value.length>0&&value.length<=2048&&value===value.trim()&&!/[\u0000-\u001f\u007f-\u009f]/u.test(value);try{const client=clientFactory(resolved.ok.accessToken,signal),chats=await client.api("/me/chats").top(25).get();if(!Array.isArray(chats?.value)||chats.value.length>25||chats.value.some(chat=>!chat||!nativeId(chat.id)))return fail("data_loss","Teams returned a malformed chat page.");const records=[],limit=request.limit??1,query=request.query?.toLowerCase(),since=request.since?Date.parse(request.since):-Infinity,until=request.until?Date.parse(request.until):Infinity;for(const chat of chats.value){if(records.length>=limit)break;const checked2=await resolved.ok.check?.(signal);if(checked2&&!("ok"in checked2))return checked2;const count=Math.min(50,limit),page=await client.api(`/chats/${encodeURIComponent(chat.id)}/messages`).top(count).get();if(!Array.isArray(page?.value)||page.value.length>count||page.value.some(row=>!row||!nativeId(row.id)||typeof row.body?.content!=="string"||typeof(row.createdDateTime??row.lastModifiedDateTime)!=="string"||!Number.isFinite(Date.parse(row.createdDateTime??row.lastModifiedDateTime))))return fail("data_loss","Teams returned malformed messages.");for(const row of page.value){const content=row.body.content,ts=row.createdDateTime??row.lastModifiedDateTime,time=Date.parse(ts);if(time<since||time>until||query&&!content.toLowerCase().includes(query))continue;records.push({source:"teams",sourceId:chat.id+":"+row.id,kind:"teams-message",ts,body:content,fields:{...row,chatId:chat.id}});if(records.length>=limit)break}}const checked=await resolved.ok.check?.(signal);return checked&&!("ok"in checked)?checked:readResult("teams",records)}catch{return businessError(signal.aborted?"aborted":"unavailable","Microsoft Graph Teams query failed; no empty result was assumed.","plugin")}}const actions=createTeamsActions(grant,clientFactory);const operationSignal=caller=>AbortSignal.any([stop.signal,AbortSignal.timeout(45e3),...caller?[caller]:[]]);const service={info,actions:{...actions,async invoke(name,input,options={}){if(closed)return fail("unavailable","Teams source is inactive.");const signal=operationSignal(options.signal);try{return await wait(track(actions.invoke(name,input,{...options,signal})),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Teams Action did not complete.")}}},status:()=>connectionState(vault,info),job:id=>connectedJobs.has(id)?ok({...connectedJobs.get(id)}):enrollment?enrollment.job(id):fail("not_found","Teams authorization job not found."),cancelJob:id=>connectedJobs.has(id)?ok({id,cleanup:"confirmed"}):enrollment?.cancelJob(id)??fail("not_found","Teams authorization job not found."),async connect(options={}){if(closed)return fail("unavailable","Teams source is inactive.");const signal=operationSignal(options.signal);try{return await wait(track(connect(options,signal)),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Teams connection did not complete.")}},async read(request,options={}){if(closed)return fail("unavailable","Teams source is inactive.");const invalid=validateRead(request);if(invalid)return invalid;const signal=operationSignal(options.signal);try{return await wait(track(readSelected({...request},signal)),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Teams selected read did not complete.")}},close(){if(closing)return closing;closed=true;stop.abort();enrollment?.cancelSource?.("teams");closing=(async()=>{while(pending.size)await Promise.allSettled([...pending])})();return closing}};return service}
|
|
1
|
+
import{actionNotApplied,withActionExecution}from"@zortexhq/plugin-connector-core/api";import{acquiredReadCapability,unreviewedActionContent}from"@zortexhq/plugin-connector-core/api";import{Client,RetryHandlerOptions}from"@microsoft/microsoft-graph-client";import{randomUUID}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{captureSelectedAccount,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{createTeamsActions}from"./actions.js";import{MICROSOFT_AUTHORITY,TEAMS_SCOPE,TEAMS_SCOPES,credentialExpiring,requestMicrosoftToken,teamsClientId}from"./token.js";const defaultClientFactory=(accessToken,signal)=>{const client=Client.init({authProvider:done=>done(null,accessToken),fetchOptions:{signal}});const retry=new RetryHandlerOptions(void 0,void 0,(_delay,_attempt,request,options)=>(typeof request==="string"?options?.method:request.method)==="GET");return{api:path=>client.api(path).middlewareOptions([retry])}};function scopePresent(scopes,required){return scopes.includes(required)||scopes.includes("https://graph.microsoft.com/"+required)}const validToken=value=>typeof value==="string"&&value.length>0&&value.length<=16384&&!/[\s\u0000-\u001f\u007f-\u009f]/u.test(value);const validScopes=value=>Array.isArray(value)&&value.length>0&&value.length<=64&&value.every(scope=>typeof scope==="string"&&/^[\x21-\x7e]{1,512}$/u.test(scope));const sameScopes=(left,right)=>JSON.stringify([...new Set(left)].sort())===JSON.stringify([...new Set(right)].sort());function wait(task,signal){return new Promise((resolve,reject)=>{const cancelled=()=>{signal.removeEventListener("abort",cancelled);reject(signal.reason??Error("Teams operation cancelled."))};signal.addEventListener("abort",cancelled,{once:true});task.then(value=>{signal.removeEventListener("abort",cancelled);resolve(value)},error=>{signal.removeEventListener("abort",cancelled);reject(error)});if(signal.aborted)cancelled()})}export function createTeamsProvider({vault,enrollment,transport=fetch,clientFactory=defaultClientFactory}){const info={content:[acquiredReadCapability(["plugins/connector-teams/README.md"]),unreviewedActionContent(["plugins/connector-teams/README.md"])],source:"teams",label:"Microsoft Teams",group:"Connector / Microsoft",auth:"oauth-browser"},stop=new AbortController;let closed=false,closing;const clientId=teamsClientId();const pending=new Set,connectedJobs=new Map;const fail=(code,message)=>businessError(code,message,"plugin");function track(task){pending.add(task);void task.then(()=>pending.delete(task),()=>pending.delete(task));return task}function authorized(snapshot,accountId){const{binding,grant:grant2,resource,material}=snapshot;if(binding.identity.source!=="teams"||binding.identity.issuer!=="microsoft"||binding.provider!=="microsoft"||binding.identity.subject!==accountId||binding.state!=="connected"||grant2.bindingId!==binding.id||grant2.purpose!=="L1"||grant2.audience!=="microsoft"||grant2.state!=="active"||resource.id!==oauthCredentialResourceId(binding.id)||resource.bindingId!==binding.id||resource.kind!=="oauth"||resource.owner.kind!=="resident"||material.kind!=="oauth")return fail("failed_precondition","Teams requires one verified native resident OAuth binding and L1 grant.");const credential=material.credential;if(!validScopes(grant2.scopes)||!validScopes(credential.scopes)||!sameScopes(grant2.scopes,credential.scopes))return fail("permission_denied","Teams credential scopes do not match the selected grant.");if(!validToken(credential.accessToken)||typeof credential.clientId!=="string"||!/^[\x21-\x7e]{1,512}$/u.test(credential.clientId)||!Number.isFinite(credential.expiresAt)||credential.expiresAt<=0||credential.expiresAt>864e13||credential.refreshToken!==void 0&&!validToken(credential.refreshToken))return fail("failed_precondition","Teams credential material is invalid; reconnect this source.");return ok(credential)}async function resolveGrant(signal){const selected=await captureSelectedAccount(vault,"teams",signal);if(!("ok"in selected))return selected;const authority=selected.ok;if(!vault.bindingCustody)return fail("failed_precondition","Teams operations require verified account custody.");const custody=vault.bindingCustody,resolution=await custody.resolve({kind:"legacy-source",source:"teams"});if(!("ok"in resolution))return resolution;if(resolution.ok.kind!=="resolved")return fail("failed_precondition","Select one verified Teams account binding.");const found=await custody.credentialSnapshot(oauthCredentialResourceId(resolution.ok.binding.id),{purpose:"L1",audience:"microsoft"});if(!("ok"in found))return found;let snapshot=found.ok,allowed=authorized(snapshot,authority.accountId);if(!("ok"in allowed))return allowed;async function fence(expected,active,requireFresh=true){const checked=await authority.check(active);if(!("ok"in checked))return checked;const current=await custody.resolve({kind:"legacy-source",source:"teams"});if(!("ok"in current))return current;if(current.ok.kind!=="resolved"||current.ok.binding.id!==expected.binding.id||current.ok.binding.revision!==expected.binding.revision)return fail("failed_precondition","Teams account selection changed during the operation.");const resource=await custody.resource(expected.resource.id);if(!("ok"in resource))return resource;if(resource.ok?.revision!==expected.resource.revision||resource.ok.owner.kind!=="resident")return fail("failed_precondition","Teams credential authority changed during the operation.");const credential=authorized(expected,authority.accountId);if(!("ok"in credential))return credential;if(requireFresh&&credential.ok.expiresAt<=Date.now())return fail("failed_precondition","Teams authorization expired during the operation.");return authority.check(active)}try{if(credentialExpiring(allowed.ok)){if(!allowed.ok.refreshToken)return fail("failed_precondition","Teams authorization expired; reconnect this source.");const before2=await fence(snapshot,signal,false);if(!("ok"in before2))return before2;const ownerSignal=AbortSignal.any([stop.signal,AbortSignal.timeout(45e3)]);const renewed=await track(custody.refreshResource(snapshot,{kind:"resident"},async current=>{const material=authorized(current,authority.accountId);if(!("ok"in material))return material;const checked=await fence(current,ownerSignal,false);if(!("ok"in checked))return checked;if(!material.ok.refreshToken)return fail("failed_precondition","Teams authorization expired; reconnect this source.");try{ownerSignal.throwIfAborted();const requestedAt=Date.now();const response=await wait(track(requestMicrosoftToken(transport,material.ok.clientId,{grant_type:"refresh_token",refresh_token:material.ok.refreshToken,scope:material.ok.scopes.join(" ")},ownerSignal)),ownerSignal),reply=response.body;const scopes=reply.scope===void 0?material.ok.scopes:typeof reply.scope==="string"&&reply.scope.length<=8192?reply.scope.trim().split(/\s+/u):[],expiresAt=requestedAt+Number(reply.expires_in)*1e3;if(response.status<200||response.status>=300||!validToken(reply.access_token)||typeof reply.token_type!=="string"||reply.token_type.toLowerCase()!=="bearer"||typeof reply.expires_in!=="number"||!Number.isFinite(reply.expires_in)||reply.expires_in<=0||!Number.isFinite(expiresAt)||expiresAt>864e13||expiresAt<=Date.now()||!validScopes(scopes)||!sameScopes(scopes,current.grant.scopes)||reply.refresh_token!==void 0&&!validToken(reply.refresh_token))return fail("failed_precondition","Teams refresh did not preserve token type, scope and expiry; reconnect this source.");const identity2=await wait(track(clientFactory(reply.access_token,ownerSignal).api("/me").select("id").get()),ownerSignal);if(identity2.id!==authority.accountId)return fail("permission_denied","Teams refreshed token does not match the selected native account.");const unchanged=await fence(current,ownerSignal,false);if(!("ok"in unchanged))return unchanged;if(expiresAt<=Date.now())return fail("failed_precondition","Teams refreshed access expired before custody completed.");return ok({kind:"oauth",credential:{...material.ok,accessToken:reply.access_token,...reply.refresh_token!==void 0?{refreshToken:reply.refresh_token}:{},expiresAt,scopes:[...material.ok.scopes]}})}catch{return fail("failed_precondition","Teams refresh did not complete; its rotating outcome must not be replayed.")}}));if(!("ok"in renewed))return renewed;snapshot=renewed.ok;allowed=authorized(snapshot,authority.accountId);if(!("ok"in allowed))return allowed}const before=await fence(snapshot,signal);if(!("ok"in before))return before;const identity=await clientFactory(allowed.ok.accessToken,signal).api("/me").select("id").get();if(identity.id!==authority.accountId)return businessError("permission_denied","Teams native account does not match the selected connection.","auth");const after=await fence(snapshot,signal);return"ok"in after?ok({accessToken:allowed.ok.accessToken,scopes:allowed.ok.scopes,check:(active=signal)=>fence(snapshot,active),signal,bindingId:snapshot.binding.id,account:snapshot.binding.account}):after}catch{return businessError(signal.aborted?"aborted":"unavailable","Teams authorization could not be verified.","auth")}}async function grant(caller){if(closed)return actionNotApplied(fail("unavailable","Teams source is inactive."));const signal=AbortSignal.any([caller,stop.signal,AbortSignal.timeout(45e3)]);try{return await wait(track(resolveGrant(signal)),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Teams account authority could not be confirmed.")}}async function connect(options,signal){const expected=options.expectedBinding?{...options.expectedBinding}:void 0;if(expected?.kind==="legacy-source"&&expected.source!=="teams")return fail("invalid_argument","Teams account selection names another source.");if(options.automatic!==false){const existing=await vault.connection("teams");if(!("ok"in existing))return existing;if(signal.aborted)return fail("aborted","Teams connection was stopped.");if(expected?.kind==="binding"){if(!vault.bindingCustody)return fail("failed_precondition","Teams requires verified account custody.");const selected=await vault.bindingCustody.resolve({kind:"legacy-source",source:"teams"});if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved"||selected.ok.binding.id!==expected.bindingId)return fail("failed_precondition","Teams account selection does not match the existing grant.")}if(existing.ok){const resolved=await grant(signal);if(!("ok"in resolved))return resolved;if(signal.aborted)return fail("aborted","Teams connection was stopped.");if(expected?.kind==="binding"&&resolved.ok.bindingId!==expected.bindingId)return fail("failed_precondition","Teams account selection changed during authorization reuse.");const job={id:randomUUID(),source:"teams",state:"connected",startedAt:new Date().toISOString(),account:resolved.ok.account};connectedJobs.set(job.id,job);if(connectedJobs.size>32)connectedJobs.delete(connectedJobs.keys().next().value);return ok({...job})}}if(signal.aborted)return fail("aborted","Teams connection was stopped.");if(!enrollment)return fail("unavailable","Connector enrollment is not installed.");return enrollment.pkce(info,{clientId,authorizeUrl:MICROSOFT_AUTHORITY+"authorize?prompt=select_account",tokenUrl:MICROSOFT_AUTHORITY+"token",scope:TEAMS_SCOPE,redirectPath:"/",provider:"microsoft",driver:"microsoft"},async(result,signal2)=>{if(!result.access_token||!Number.isFinite(result.expires_in))throw Error("Microsoft authorization failed.");const scopes=String(result.scope??"").split(" ").filter(Boolean);for(const required of TEAMS_SCOPES.filter(scope=>scope!=="offline_access"))if(!scopePresent(scopes,required))throw Error("Required Teams Action scope missing: "+required);const identity=await clientFactory(result.access_token,signal2).api("/me").select("id,displayName,mail,userPrincipalName").get();if(!identity.id||!(identity.mail||identity.userPrincipalName))throw Error("Microsoft account unconfirmed.");return{account:identity.mail||identity.userPrincipalName,accountId:identity.id,credential:{accessToken:result.access_token,...result.refresh_token?{refreshToken:result.refresh_token}:{},clientId,expiresAt:Date.now()+Number(result.expires_in)*1e3,scopes}}},{...options,signal,...expected?{expectedBinding:expected}:{}})}async function readSelected(request,signal){const resolved=await grant(signal);if(!("ok"in resolved))return resolved;if(!scopePresent(resolved.ok.scopes,"Chat.Read")&&!scopePresent(resolved.ok.scopes,"Chat.ReadWrite"))return fail("permission_denied","The selected Teams grant does not include chat message read access.");const nativeId=value=>typeof value==="string"&&value.length>0&&value.length<=2048&&value===value.trim()&&!/[\u0000-\u001f\u007f-\u009f]/u.test(value);try{const client=clientFactory(resolved.ok.accessToken,signal),chats=await client.api("/me/chats").top(25).get();if(!Array.isArray(chats?.value)||chats.value.length>25||chats.value.some(chat=>!chat||!nativeId(chat.id)))return fail("data_loss","Teams returned a malformed chat page.");const records=[],limit=request.limit??1,query=request.query?.toLowerCase(),since=request.since?Date.parse(request.since):-Infinity,until=request.until?Date.parse(request.until):Infinity;for(const chat of chats.value){if(records.length>=limit)break;const checked2=await resolved.ok.check?.(signal);if(checked2&&!("ok"in checked2))return checked2;const count=Math.min(50,limit),page=await client.api(`/chats/${encodeURIComponent(chat.id)}/messages`).top(count).get();if(!Array.isArray(page?.value)||page.value.length>count||page.value.some(row=>!row||!nativeId(row.id)||typeof row.body?.content!=="string"||typeof(row.createdDateTime??row.lastModifiedDateTime)!=="string"||!Number.isFinite(Date.parse(row.createdDateTime??row.lastModifiedDateTime))))return fail("data_loss","Teams returned malformed messages.");for(const row of page.value){const content=row.body.content,ts=row.createdDateTime??row.lastModifiedDateTime,time=Date.parse(ts);if(time<since||time>until||query&&!content.toLowerCase().includes(query))continue;records.push({source:"teams",sourceId:chat.id+":"+row.id,kind:"teams-message",ts,body:content,fields:{...row,chatId:chat.id}});if(records.length>=limit)break}}const checked=await resolved.ok.check?.(signal);return checked&&!("ok"in checked)?checked:readResult("teams",records)}catch{return businessError(signal.aborted?"aborted":"unavailable","Microsoft Graph Teams query failed; no empty result was assumed.","plugin")}}const actions=createTeamsActions(grant,clientFactory);const operationSignal=caller=>AbortSignal.any([stop.signal,AbortSignal.timeout(45e3),...caller?[caller]:[]]);const service={info,actions:{...actions,async invoke(name,input,options={}){if(closed)return fail("unavailable","Teams source is inactive.");const signal=operationSignal(options.signal);const task=track(actions.invoke(name,input,{...options,signal}));try{return withActionExecution(await wait(task,signal),task)}catch{return withActionExecution(fail(signal.aborted?"aborted":"unavailable","Teams Action did not complete."),task)}}},status:()=>connectionState(vault,info),job:id=>connectedJobs.has(id)?ok({...connectedJobs.get(id)}):enrollment?enrollment.job(id):fail("not_found","Teams authorization job not found."),cancelJob:id=>connectedJobs.has(id)?ok({id,cleanup:"confirmed"}):enrollment?.cancelJob(id)??fail("not_found","Teams authorization job not found."),async connect(options={}){if(closed)return fail("unavailable","Teams source is inactive.");const signal=operationSignal(options.signal);try{return await wait(track(connect(options,signal)),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Teams connection did not complete.")}},async read(request,options={}){if(closed)return fail("unavailable","Teams source is inactive.");const invalid=validateRead(request);if(invalid)return invalid;const signal=operationSignal(options.signal);try{return await wait(track(readSelected({...request},signal)),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Teams selected read did not complete.")}},close(){if(closing)return closing;closed=true;stop.abort();enrollment?.cancelSource?.("teams");closing=(async()=>{while(pending.size)await Promise.allSettled([...pending])})();return closing}};return service}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BufferJSON,initAuthCreds,proto}from"baileys";export function sessionStore(serialized,changed){let creds=initAuthCreds();let keys={};if(serialized){const parsed=JSON.parse(serialized,BufferJSON.reviver);if(!parsed?.creds||typeof parsed.keys!=="object")throw new Error("invalid_session");creds=parsed.creds;keys=parsed.keys}const state={creds,keys:{async get(type,ids){const data={};for(const id of ids){let value=keys[type]?.[id];if(value===void 0)continue;if(type==="app-state-sync-key")value=proto.Message.AppStateSyncKeyData.fromObject(value);data[id]=value}return data},async set(data){for(const[type,entries]of Object.entries(data)){const bucket=keys[type]??={};for(const[id,value]of Object.entries(entries??{})){if(value===null||value===void 0)delete bucket[id];else bucket[id]=value}}changed()}}};return{state,serialize:()=>JSON.stringify({creds:state.creds,keys},BufferJSON.replacer)}}
|
|
1
|
+
import{BufferJSON,initAuthCreds,proto}from"baileys";export function sessionStore(serialized,changed){let creds=initAuthCreds();let keys={};if(serialized){const parsed=JSON.parse(serialized,BufferJSON.reviver);if(!parsed?.creds||typeof parsed.keys!=="object")throw new Error("invalid_session");creds=parsed.creds;keys=parsed.keys}const state={creds,keys:{async get(type,ids){const data={};for(const id of ids){let value=keys[type]?.[id];if(value===void 0)continue;if(type==="app-state-sync-key")value=proto.Message.AppStateSyncKeyData.fromObject(value);data[id]=value}return data},async set(data){for(const[type,entries]of Object.entries(data)){const bucket=keys[type]??={};for(const[id,value]of Object.entries(entries??{})){if(value===null||value===void 0)delete bucket[id];else bucket[id]=value}}await changed()}}};return{state,serialize:()=>JSON.stringify({creds:state.creds,keys},BufferJSON.replacer)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{acquiredReadCapability,unreviewedActionContent}from"@zortexhq/plugin-connector-core/api";import{randomUUID}from"node:crypto";import makeWASocket,{Browsers,DisconnectReason,fetchLatestBaileysVersion,jidDecode}from"baileys";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{sessionStore}from"./auth-state.js";import{toRecords}from"./messages.js";import{openPairingPage}from"./pairing-page.js";import{TransientMessageBuffer,TRANSIENT_MESSAGE_LIMIT}from"./transient-buffer.js";export const SOURCE="whatsapp-web";const silent={level:"silent",child:()=>silent,trace(){},debug(){},info(){},warn(){},error(){},fatal(){}};async function defaultSocket(auth,fullHistory){const version=await Promise.race([fetchLatestBaileysVersion().then(r=>r.version).catch(()=>void 0),new Promise(resolve=>setTimeout(resolve,5e3))]);return makeWASocket({auth,logger:silent,browser:Browsers.macOS("Chrome"),syncFullHistory:fullHistory,markOnlineOnConnect:false,...version?{version}:{}})}const statusCode=update=>update.lastDisconnect?.error?.output?.statusCode;function nativeAccount(socket){const identity=jidDecode(socket?.user?.id);return identity?.server==="s.whatsapp.net"&&/^[1-9][0-9]{4,19}$/u.test(identity.user)?identity.user:void 0}export function createWhatsappProvider({vault,socket,pairingPage=openPairingPage,openUrl=openConnectionUrl,payloadRetention="cache",pairingTimeoutMs=18e4,resumeTimeoutMs=2e4,historyTimeoutMs=3e4}){if(!["cache","transient"].includes(payloadRetention)||[pairingTimeoutMs,resumeTimeoutMs,historyTimeoutMs].some(ms=>!Number.isInteger(ms)||ms<1||ms>6e5))throw Error("Invalid WhatsApp retention or timeout configuration.");const transient=payloadRetention==="transient",makeSocket=socket??(auth=>defaultSocket(auth,!transient));const info={content:[acquiredReadCapability(["plugins/connector-whatsapp/README.md"]),unreviewedActionContent(["plugins/connector-whatsapp/README.md"])],source:SOURCE,label:"WhatsApp",group:"Connector / Chat",auth:"native-browser"};const jobs=new Map,names=new Map,buffer=new TransientMessageBuffer,pairings=new Set;const initializing=new Set;let live,resuming,closed=false,closing;let writes=Promise.resolve(),persistTimer;const fail=(code,message)=>businessError(code,message,"plugin");const enqueue=task=>{writes=writes.then(task,task).catch(()=>void 0);return writes};const track=task=>{initializing.add(task);void task.then(()=>initializing.delete(task),()=>initializing.delete(task));return task};const notify=entry=>{for(const wake of entry.waiters)wake()};const owned=(entry,sock=entry.socket)=>!closed&&!entry.stopped&&live===entry&&entry.socket===sock;function remember(jid,name){if(!jid||jid.length>512||!name)return;names.delete(jid);names.set(jid,name.slice(0,256));if(names.size>2e3)names.delete(names.keys().next().value)}function stopLive(entry){entry.stopped=true;entry.online=false;entry.resolveOpen(false);notify(entry);entry.socket?.end();if(live===entry){live=void 0;buffer.clear();names.clear()}}function waitUntil(entry,predicate,timeout,signal){if(predicate())return Promise.resolve(true);if(signal?.aborted||closed||entry.stopped)return Promise.resolve(false);return new Promise(resolve=>{const finish=value=>{clearTimeout(timer);entry.waiters.delete(wake);signal?.removeEventListener("abort",abort);resolve(value)};const wake=()=>{if(predicate())finish(true);else if(closed||entry.stopped)finish(false)};const abort=()=>finish(false),timer=setTimeout(()=>finish(false),timeout);entry.waiters.add(wake);signal?.addEventListener("abort",abort,{once:true});wake()})}async function captureAuthority(accountId){const custody=vault.bindingCustody;if(!custody)return transient?fail("failed_precondition","Transient WhatsApp requires durable native account custody."):ok(void 0);const selected=await custody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved")return fail("failed_precondition","WhatsApp needs one explicit native account binding.");const current=await custody.credentialSnapshot(oauthCredentialResourceId(selected.ok.binding.id),{purpose:"L1",audience:SOURCE});if(!("ok"in current))return current;const value=current.ok;if(value.binding.identity.source!==SOURCE||value.binding.identity.issuer!==SOURCE||value.binding.identity.subject!==accountId||value.binding.identity.tenant!==null||value.material.kind!=="oauth"||value.resource.kind!=="oauth"||value.resource.owner.kind!=="resident"||value.material.credential.clientId!=="whatsapp-linked-device"||!value.grant.scopes.includes("messages.read"))return fail("permission_denied","WhatsApp session custody does not match the selected native account.");return ok({binding:value.binding,grant:value.grant,resource:value.resource})}async function checkAuthority(entry){if(!entry.accountId||nativeAccount(entry.socket)!==entry.accountId)return fail("failed_precondition","WhatsApp signed-in account changed. Reconnect the selected account.");const current=await captureAuthority(entry.accountId);if(!("ok"in current))return current;const expected=entry.authority,latest=current.ok;if(expected&&(!latest||latest.binding.id!==expected.binding.id||latest.binding.revision!==expected.binding.revision||latest.grant.id!==expected.grant.id||latest.grant.revision!==expected.grant.revision||latest.grant.scopeEpoch!==expected.grant.scopeEpoch||latest.resource.id!==expected.resource.id))return fail("permission_denied","WhatsApp account permission changed while the operation was pending.");return ok(latest)}async function persistNow(entry){if(!entry.accountId||!entry.online||entry.stopped)return;const allowed=await checkAuthority(entry);if(!("ok"in allowed)){stopLive(entry);return}if(entry.stopped||!entry.online)return;const credential={accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]};const saved=allowed.ok&&vault.bindingCustody?await vault.bindingCustody.compareAndSwapResource({...allowed.ok.resource,updatedAt:new Date().toISOString()},{kind:"oauth",credential},allowed.ok.resource.revision):await vault.updateCredential(SOURCE,credential);if(!("ok"in saved))stopLive(entry)}function persist(entry){if(!owned(entry)||!entry.accountId)return;clearTimeout(persistTimer);persistTimer=setTimeout(()=>{void enqueue(()=>persistNow(entry))},1e3);persistTimer.unref?.()}function store(entry,sock,messages,history=false){if(!owned(entry,sock)||!entry.accountId||nativeAccount(sock)!==entry.accountId||transient&&!entry.online)return;if(transient){for(const message of messages)for(const record of toRecords(entry.accountId,[message],jid=>names.get(jid)))buffer.add(record);if(history||messages.length>0)entry.historyArrived=true;notify(entry);return}const records=toRecords(entry.accountId,messages,jid=>names.get(jid));for(let i=0;i<records.length;i+=100){const batch=records.slice(i,i+100);void enqueue(async()=>{if(!await entry.open||!owned(entry,sock))return;const allowed=await checkAuthority(entry);if(!("ok"in allowed)){stopLive(entry);return}await cache(vault,SOURCE,batch);entry.historyArrived=true;notify(entry)})}}async function markLoggedOut(entry){if(!entry.accountId)return;if(vault.bindingCustody&&entry.authority){const current=await vault.bindingCustody.binding(entry.authority.binding.id);if("ok"in current&¤t.ok?.revision===entry.authority.binding.revision)await vault.bindingCustody.compareAndSwapBinding({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},current.ok.revision)}else{const current=await vault.connection(SOURCE);if("ok"in current&¤t.ok?.accountId===entry.accountId)await vault.saveConnection({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},{accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]})}}async function start(stateStore,accountId,authority,onView,onOpen,onFailure){if(closed)throw Error("inactive");let resolveOpen;const open=new Promise(resolve=>{resolveOpen=resolve});const current={store:stateStore,open,resolveOpen,...accountId?{accountId}:{},...authority?{authority}:{},online:false,stopped:false,historyArrived:false,needsPairing:false,waiters:new Set};live=current;buffer.clear();names.clear();let restarts=0,generation=0;const failed=code=>{current.failure=code;stopLive(current);onFailure?.(code)};const connect=async()=>{if(!owned(current))return;const attempt=++generation,previous=current.socket;delete current.socket;previous?.end();const sock=await track(makeSocket(current.store.state));if(!owned(current)||attempt!==generation){sock.end();return}current.socket=sock;sock.ev.on("creds.update",()=>{if(owned(current,sock))persist(current)});sock.ev.on("connection.update",update=>{if(!owned(current,sock))return;if(update.qr){current.needsPairing=true;onView?.({state:"qr",qr:update.qr});notify(current)}if(update.connection==="open"){const linked=nativeAccount(sock);if(!linked||current.accountId&¤t.accountId!==linked){failed("account_changed");return}current.accountId=linked;void(async()=>{const completed=await onOpen?.(current);if(!owned(current,sock))return;const captured=current.authority?await checkAuthority(current):await captureAuthority(linked);if(!("ok"in captured)){failed("account_permission_changed");return}if(!owned(current,sock))return;if(!current.authority)current.authority=captured.ok;current.online=true;current.needsPairing=false;restarts=0;resolveOpen(true);notify(current);completed?.()})().catch(()=>failed("pairing_unavailable"))}if(update.connection==="close"){current.online=false;notify(current);const code=statusCode(update);if(code===DisconnectReason.loggedOut){current.needsPairing=true;void enqueue(()=>markLoggedOut(current));failed("qr_scan_required");return}if(code!==DisconnectReason.connectionReplaced&&restarts++<5){void connect().catch(()=>failed("connection_unavailable"));return}failed("connection_unavailable")}});sock.ev.on("messaging-history.set",({chats,contacts,messages})=>{if(!owned(current,sock))return;for(const chat of chats)remember(chat.id,chat.name);for(const contact of contacts)remember(contact.id,contact.name??contact.notify);store(current,sock,messages,true)});sock.ev.on("chats.upsert",chats=>{if(owned(current,sock))for(const chat of chats)remember(chat.id,chat.name)});sock.ev.on("contacts.upsert",contacts=>{if(owned(current,sock))for(const contact of contacts)remember(contact.id,contact.name??contact.notify)});sock.ev.on("messages.upsert",({messages})=>{if(!owned(current,sock))return;for(const message of messages)if(!message.key.fromMe)remember(message.key.remoteJid,message.key.remoteJid?.endsWith("@g.us")?void 0:message.pushName);store(current,sock,messages)})};try{await connect()}catch(error){failed("connection_unavailable");throw error}return current}async function resume(){if(live&&!live.stopped)return live;if(resuming)return resuming;resuming=(async()=>{const connection=await vault.connection(SOURCE);if(!("ok"in connection))throw Error("account_permission_changed");if(connection.ok?.state!=="connected"||!connection.ok.accountId)return void 0;const grant=await vault.credential(SOURCE);if(!("ok"in grant))throw Error("account_permission_changed");const authority=await captureAuthority(connection.ok.accountId);if(!("ok"in authority))throw Error("account_permission_changed");const restored=sessionStore(grant.ok.accessToken,()=>{if(live)persist(live)});return start(restored,connection.ok.accountId,authority.ok)})();try{return await resuming}finally{resuming=void 0}}function cleanPairing(pair2){clearTimeout(pair2.timer);pair2.removeAbort?.();pair2.page?.close();pairings.delete(pair2)}function failPairing(pair2,code,message){if(pair2.job.state==="waiting-user"){pair2.job.state="failed";pair2.job.error={code,message};delete pair2.job.authorizationUrl;delete pair2.job.instructions;pair2.stop.abort();pair2.page?.update({state:"failed",message});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live)}cleanPairing(pair2)}function cancelPairing(pair2){if(pair2.job.state==="waiting-user")pair2.job.state="cancelled";delete pair2.job.authorizationUrl;delete pair2.job.instructions;delete pair2.job.error;pair2.stop.abort();pair2.page?.update({state:"failed",message:"WhatsApp connection was cancelled."});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live);cleanPairing(pair2)}async function pair(job,options,expectedAccountId){if(closed)throw Error("inactive");const owner={job,stop:new AbortController};pairings.add(owner);const abort=()=>failPairing(owner,"aborted","WhatsApp connection was cancelled.");options.signal?.addEventListener("abort",abort,{once:true});owner.removeAbort=()=>options.signal?.removeEventListener("abort",abort);try{owner.page=await pairingPage();if(closed||options.signal?.aborted||owner.stop.signal.aborted){abort();return}job.authorizationUrl=owner.page.url;job.instructions="Open the QR code page, then use WhatsApp on your phone: Settings \u2192 Linked devices \u2192 Link a device. The connection continues automatically after scanning.";job.error={code:"qr_scan_required",message:"Scan the WhatsApp QR code with your phone."};owner.timer=setTimeout(()=>failPairing(owner,"pairing_timeout","WhatsApp QR was not scanned before it expired."),pairingTimeoutMs);owner.timer.unref?.();const fresh=sessionStore(void 0,()=>{if(owner.entry)persist(owner.entry)});if(live)stopLive(live);owner.entry=await start(fresh,expectedAccountId,void 0,view=>{if(job.state==="waiting-user")owner.page?.update(view)},async current=>{if(job.state==="connected"&&!closed)return;if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)throw Error("aborted");const saved=await vault.saveConnection({source:SOURCE,provider:SOURCE,account:current.socket?.user?.name?.slice(0,256)||"WhatsApp",accountId:current.accountId,scopes:["messages.read"],state:"connected",updatedAt:new Date().toISOString()},{accessToken:current.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]},{signal:owner.stop.signal});if(!("ok"in saved))throw Error("custody_failed");return()=>{if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)return;clearTimeout(owner.timer);owner.removeAbort?.();job.state="connected";job.account=saved.ok.account;delete job.instructions;delete job.authorizationUrl;delete job.error;owner.page?.update({state:"connected"});owner.timer=setTimeout(()=>cleanPairing(owner),1e4);owner.timer.unref?.()}},code=>failPairing(owner,code,code==="account_changed"?"The scanned WhatsApp account does not match the selected account.":"WhatsApp pairing did not complete."));if(owner.stop.signal.aborted)stopLive(owner.entry);if(!options.automatic&&options.manualPresentation!=="return-url"&&job.state==="waiting-user")await openUrl(owner.page.url)}catch{failPairing(owner,"pairing_unavailable","WhatsApp pairing page or connection could not start.")}}return{info,...transient?{}:{requiresPersistentPayloads:true},status:()=>connectionState(vault,info),job(id){const job=jobs.get(id);return job?ok({...job}):fail("not_found","WhatsApp connection job not found.")},cancelJob(id){const job=jobs.get(id);if(!job)return ok({id,cleanup:"confirmed"});const pairing=[...pairings].find(owner=>owner.job===job);if(pairing)cancelPairing(pairing);else if(job.state==="waiting-user")job.state="cancelled";delete job.authorizationUrl;delete job.instructions;return ok({id,cleanup:[...pairings].some(owner=>owner.job===job)?"pending":"confirmed"})},async connect(options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");const running=[...jobs.values()].find(job2=>job2.state==="waiting-user");if(running)return ok({...running});for(const[id,job2]of jobs)if(jobs.size>=32&&job2.state!=="waiting-user")jobs.delete(id);const job={id:randomUUID(),source:SOURCE,state:"waiting-user",startedAt:new Date().toISOString()};jobs.set(job.id,job);try{const selected=await vault.connection(SOURCE);if(!("ok"in selected))return selected;if(selected.ok&&!selected.ok.accountId)return fail("failed_precondition","WhatsApp needs a verified native account binding.");if(options.expectedBinding?.kind==="legacy-source"&&options.expectedBinding.source!==SOURCE)return fail("invalid_argument","WhatsApp account selection names another source.");if(options.expectedBinding?.kind==="binding"){const binding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in binding)||binding.ok.kind!=="resolved"||binding.ok.binding.id!==options.expectedBinding.bindingId)return fail("failed_precondition","WhatsApp account selection does not match this linked device.")}if(closed)return fail("unavailable","WhatsApp source is inactive.");const resumed=await track(resume());if(resumed){await waitUntil(resumed,()=>resumed.online||resumed.needsPairing,resumeTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");if(resumed.online){const allowed=await checkAuthority(resumed);if(!("ok"in allowed))return allowed;job.state="connected";if(selected.ok)job.account=selected.ok.account;return ok({...job})}if(!resumed.needsPairing){job.state="failed";job.error={code:resumed.failure??"connection_unavailable",message:resumed.failure==="account_changed"?"WhatsApp signed in as a different account.":"The existing WhatsApp session did not reconnect."};return ok({...job})}}if(options.automatic&&!transient){job.state="failed";job.error={code:"qr_scan_required",message:"WhatsApp needs one QR scan from the phone; connect it explicitly."};return ok({...job})}if(options.automatic&&selected.ok?.accountId&&vault.bindingCustody){const selectedBinding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if("ok"in selectedBinding&&selectedBinding.ok.kind==="resolved"){const grant=await vault.bindingCustody.grantForBinding(selectedBinding.ok.binding.id,"L1",SOURCE);if(!("ok"in grant))return grant;if(grant.ok?.state==="revoked")return fail("permission_denied","WhatsApp access was revoked. Reconnect explicitly to grant it again.")}}await track(pair(job,options,selected.ok?.accountId))}catch{job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp session permission or connection could not be verified."}}finally{if(job.state==="waiting-user"&&![...pairings].some(owner=>owner.job===job)){job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp did not start an owned connection job."}}}return ok({...job})},async read(request,options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");const invalid=validateRead(request);if(invalid)return invalid;if(request.fileId!==void 0)return fail("invalid_argument","WhatsApp message reads support limit, query and time filters; file download is not supported.");if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const connection=await vault.connection(SOURCE);if(!("ok"in connection))return connection;if(connection.ok?.state!=="connected"||!connection.ok.accountId)return fail("unauthenticated","Connect WhatsApp by scanning its QR code first.");const session=await track(resume()).catch(()=>void 0);const online=session?await waitUntil(session,()=>session.online,resumeTimeoutMs,options.signal):false;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const warnings=[];let records;if(transient){if(!online||!session)return fail("unavailable","WhatsApp is offline; transient reads need the selected live session.");const allowed=await checkAuthority(session);if(!("ok"in allowed)){stopLive(session);return allowed}await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");if(!owned(session)||!session.online)return fail("unavailable","WhatsApp session ended before the message read.");const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(!session.historyArrived)return fail("unavailable","No live WhatsApp message batch has arrived for this session yet. Retry after the phone finishes linking or a message arrives.");records=buffer.snapshot();warnings.push(`This live session retains at most ${TRANSIENT_MESSAGE_LIMIT} messages and 4 MiB in memory. Messages are not saved and are cleared on restart.`)}else{if(!online)warnings.push("WhatsApp is offline right now; showing messages already saved in the Vault.");if(online&&session&&!session.historyArrived){const stored2=await vault.records(SOURCE,1);if(!("ok"in stored2)||!stored2.ok.length)await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal)}await writes;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const stored=await vault.records(SOURCE,100);if(!("ok"in stored))return stored;records=stored.ok.map(row=>row.data);if(request.query||request.since||request.until)warnings.push("Filters apply to the 100 most recent saved messages; use SQL search over z_records for older history.")}const since=request.since?Date.parse(request.since):-Infinity,until=request.until?Date.parse(request.until):Infinity,query=request.query?.toLowerCase();records=records.filter(record=>record.sourceId?.startsWith(connection.ok.accountId+":")).filter(record=>{const at=Date.parse(record.ts??"");return at>=since&&at<=until}).filter(record=>!query||`${record.body} ${record.fields?.chat??""}`.toLowerCase().includes(query)).slice(0,request.limit??1);if(transient&&session){const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(closed||!owned(session)||options.signal?.aborted)return fail("aborted","WhatsApp read was cancelled before delivery.")}return readResult(SOURCE,records,warnings)},close(){if(closing)return closing;closing=(async()=>{closed=true;clearTimeout(persistTimer);for(const owner of[...pairings]){if(owner.job.state==="waiting-user")failPairing(owner,"aborted","WhatsApp source was closed.");else cleanPairing(owner)}await Promise.allSettled([...initializing]);await writes;if(live){const current=live;await persistNow(current).catch(()=>void 0);stopLive(current)}buffer.clear();names.clear()})();return closing}}}
|
|
1
|
+
import{acquiredReadCapability,unreviewedActionContent}from"@zortexhq/plugin-connector-core/api";import{randomUUID}from"node:crypto";import makeWASocket,{Browsers,DisconnectReason,fetchLatestBaileysVersion,jidDecode}from"baileys";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{sessionStore}from"./auth-state.js";import{toRecords}from"./messages.js";import{openPairingPage}from"./pairing-page.js";import{TransientMessageBuffer,TRANSIENT_MESSAGE_LIMIT}from"./transient-buffer.js";export const SOURCE="whatsapp-web";const silent={level:"silent",child:()=>silent,trace(){},debug(){},info(){},warn(){},error(){},fatal(){}};async function defaultSocket(auth,fullHistory){const version=await Promise.race([fetchLatestBaileysVersion().then(r=>r.version).catch(()=>void 0),new Promise(resolve=>setTimeout(resolve,5e3))]);return makeWASocket({auth,logger:silent,browser:Browsers.macOS("Chrome"),syncFullHistory:fullHistory,markOnlineOnConnect:false,...version?{version}:{}})}const statusCode=update=>update.lastDisconnect?.error?.output?.statusCode;function nativeAccount(socket){const identity=jidDecode(socket?.user?.id);return identity?.server==="s.whatsapp.net"&&/^[1-9][0-9]{4,19}$/u.test(identity.user)?identity.user:void 0}export function createWhatsappProvider({vault,socket,pairingPage=openPairingPage,openUrl=openConnectionUrl,payloadRetention="cache",pairingTimeoutMs=18e4,resumeTimeoutMs=2e4,historyTimeoutMs=3e4}){if(!["cache","transient"].includes(payloadRetention)||[pairingTimeoutMs,resumeTimeoutMs,historyTimeoutMs].some(ms=>!Number.isInteger(ms)||ms<1||ms>6e5))throw Error("Invalid WhatsApp retention or timeout configuration.");const transient=payloadRetention==="transient",makeSocket=socket??(auth=>defaultSocket(auth,!transient));const info={content:[acquiredReadCapability(["plugins/connector-whatsapp/README.md"]),unreviewedActionContent(["plugins/connector-whatsapp/README.md"])],source:SOURCE,label:"WhatsApp",group:"Connector / Chat",auth:"native-browser"};const jobs=new Map,names=new Map,buffer=new TransientMessageBuffer,pairings=new Set;const initializing=new Set;let live,resuming,closed=false,closing;let writes=Promise.resolve();const fail=(code,message)=>businessError(code,message,"plugin");const enqueue=task=>{writes=writes.then(task,task).catch(()=>void 0);return writes};const track=task=>{initializing.add(task);void task.then(()=>initializing.delete(task),()=>initializing.delete(task));return task};const notify=entry=>{for(const wake of entry.waiters)wake()};const owned=(entry,sock=entry.socket)=>!closed&&!entry.stopped&&live===entry&&entry.socket===sock;function remember(jid,name){if(!jid||jid.length>512||!name)return;names.delete(jid);names.set(jid,name.slice(0,256));if(names.size>2e3)names.delete(names.keys().next().value)}function stopLive(entry){entry.stopped=true;entry.online=false;entry.resolveOpen(false);notify(entry);entry.socket?.end();if(live===entry){live=void 0;buffer.clear();names.clear()}}function waitUntil(entry,predicate,timeout,signal){if(predicate())return Promise.resolve(true);if(signal?.aborted||closed||entry.stopped)return Promise.resolve(false);return new Promise(resolve=>{const finish=value=>{clearTimeout(timer);entry.waiters.delete(wake);signal?.removeEventListener("abort",abort);resolve(value)};const wake=()=>{if(predicate())finish(true);else if(closed||entry.stopped)finish(false)};const abort=()=>finish(false),timer=setTimeout(()=>finish(false),timeout);entry.waiters.add(wake);signal?.addEventListener("abort",abort,{once:true});wake()})}async function captureAuthority(accountId,expectedCredential){const custody=vault.bindingCustody;if(!custody)return transient?fail("failed_precondition","Transient WhatsApp requires durable native account custody."):ok(void 0);const selected=await custody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved")return fail("failed_precondition","WhatsApp needs one explicit native account binding.");const current=await custody.credentialSnapshot(oauthCredentialResourceId(selected.ok.binding.id),{purpose:"L1",audience:SOURCE});if(!("ok"in current))return current;const value=current.ok;if(value.binding.identity.source!==SOURCE||value.binding.identity.issuer!==SOURCE||value.binding.identity.subject!==accountId||value.binding.identity.tenant!==null||value.material.kind!=="oauth"||value.resource.kind!=="oauth"||value.resource.owner.kind!=="resident"||value.material.credential.clientId!=="whatsapp-linked-device"||!value.grant.scopes.includes("messages.read"))return fail("permission_denied","WhatsApp session custody does not match the selected native account.");if(expectedCredential!==void 0&&value.material.credential.accessToken!==expectedCredential)return fail("failed_precondition","WhatsApp session changed while its stored credentials were being loaded.");return ok({binding:value.binding,grant:value.grant,resource:value.resource})}async function checkAuthority(entry,initializing2=false){if(!entry.accountId||nativeAccount(entry.socket)!==entry.accountId&&!(initializing2&&entry.durable&&entry.socket?.user?.id===void 0))return fail("failed_precondition","WhatsApp signed-in account changed. Reconnect the selected account.");const current=await captureAuthority(entry.accountId);if(!("ok"in current))return current;const expected=entry.authority,latest=current.ok;if(expected&&(!latest||latest.binding.id!==expected.binding.id||latest.binding.revision!==expected.binding.revision||latest.grant.id!==expected.grant.id||latest.grant.revision!==expected.grant.revision||latest.grant.scopeEpoch!==expected.grant.scopeEpoch||latest.resource.id!==expected.resource.id))return fail("permission_denied","WhatsApp account permission changed while the operation was pending.");return ok(latest)}async function persistNow(entry){if(!entry.accountId||!entry.durable||entry.stopped||live!==entry)throw Error("WhatsApp session no longer owns its stored credentials.");const allowed=await checkAuthority(entry,true);if(!("ok"in allowed))throw Error("WhatsApp session permission changed before persistence.");if(entry.stopped||live!==entry)throw Error("WhatsApp session ended before persistence.");if(entry.authority&&allowed.ok?.resource.revision!==entry.authority.resource.revision)throw Error("WhatsApp stored session was replaced by another owner.");const credential={accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]};const saved=allowed.ok&&vault.bindingCustody?await vault.bindingCustody.compareAndSwapResource({...allowed.ok.resource,updatedAt:new Date().toISOString()},{kind:"oauth",credential},allowed.ok.resource.revision):await vault.updateCredential(SOURCE,credential);if(!("ok"in saved))throw Error("WhatsApp session persistence failed.");if(entry.authority&&allowed.ok&&vault.bindingCustody)entry.authority={...entry.authority,resource:saved.ok};const current=await checkAuthority(entry,true);if(!("ok"in current)||entry.stopped||live!==entry||entry.authority&¤t.ok?.resource.revision!==entry.authority.resource.revision)throw Error("WhatsApp session permission changed during persistence.")}function persist(entry){if(!owned(entry))return Promise.reject(Error("WhatsApp session is no longer active."));if(!entry.durable)return Promise.resolve();const saved=entry.sessionWrites.then(()=>persistNow(entry));entry.sessionWrites=saved.catch(()=>{entry.failure="session_persistence_failed";stopLive(entry)});return track(saved)}function store(entry,sock,messages,history=false){if(!owned(entry,sock)||!entry.accountId||nativeAccount(sock)!==entry.accountId||transient&&!entry.online)return;if(transient){for(const message of messages)for(const record of toRecords(entry.accountId,[message],jid=>names.get(jid)))buffer.add(record);if(history||messages.length>0)entry.historyArrived=true;notify(entry);return}const records=toRecords(entry.accountId,messages,jid=>names.get(jid));for(let i=0;i<records.length;i+=100){const batch=records.slice(i,i+100);void enqueue(async()=>{if(!await entry.open||!owned(entry,sock))return;const allowed=await checkAuthority(entry);if(!("ok"in allowed)){stopLive(entry);return}await cache(vault,SOURCE,batch);entry.historyArrived=true;notify(entry)})}}async function markLoggedOut(entry){if(!entry.accountId)return;if(vault.bindingCustody&&entry.authority){const current=await vault.bindingCustody.binding(entry.authority.binding.id);if("ok"in current&¤t.ok?.revision===entry.authority.binding.revision)await vault.bindingCustody.compareAndSwapBinding({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},current.ok.revision)}else{const current=await vault.connection(SOURCE);if("ok"in current&¤t.ok?.accountId===entry.accountId)await vault.saveConnection({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},{accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]})}}async function start(serialized,accountId,authority,onView,onOpen,onFailure){if(closed)throw Error("inactive");let resolveOpen;const open=new Promise(resolve=>{resolveOpen=resolve});const current={store:sessionStore(serialized,()=>persist(current)),open,resolveOpen,...accountId?{accountId}:{},...authority?{authority}:{},online:false,stopped:false,historyArrived:false,needsPairing:false,waiters:new Set,durable:serialized!==void 0,sessionWrites:Promise.resolve()};live=current;buffer.clear();names.clear();let restarts=0,generation=0;const failed=code=>{current.failure=code;stopLive(current);onFailure?.(code)};const connect=async()=>{if(!owned(current))return;const attempt=++generation,previous=current.socket;delete current.socket;previous?.end();const ownsAttempt=()=>owned(current)&&attempt===generation;const auth={creds:current.store.state.creds,keys:{get:async(type,ids)=>{if(!ownsAttempt())throw Error("WhatsApp socket was replaced.");return current.store.state.keys.get(type,ids)},set:async data=>{if(!ownsAttempt())throw Error("WhatsApp socket was replaced.");await current.store.state.keys.set(data)}}};const sock=await track(makeSocket(auth));if(!owned(current)||attempt!==generation){sock.end();return}current.socket=sock;sock.ev.on("creds.update",()=>{if(owned(current,sock))void persist(current).catch(()=>{})});sock.ev.on("connection.update",update=>{if(!owned(current,sock))return;if(update.qr){current.needsPairing=true;onView?.({state:"qr",qr:update.qr});notify(current)}if(update.connection==="open"){const linked=nativeAccount(sock);if(!linked||current.accountId&¤t.accountId!==linked){failed("account_changed");return}current.accountId=linked;void(async()=>{const completed=await onOpen?.(current);if(!owned(current,sock))return;const captured=current.authority?await checkAuthority(current):await captureAuthority(linked,completed?.credential);if(!("ok"in captured)){failed("account_permission_changed");return}if(!owned(current,sock))return;if(!current.authority)current.authority=captured.ok;current.durable=true;await persist(current);if(!owned(current,sock))return;current.online=true;current.needsPairing=false;restarts=0;resolveOpen(true);notify(current);completed?.complete()})().catch(()=>failed("pairing_unavailable"))}if(update.connection==="close"){current.online=false;notify(current);const code=statusCode(update);if(code===DisconnectReason.loggedOut){current.needsPairing=true;void enqueue(()=>markLoggedOut(current));failed("qr_scan_required");return}if(code!==DisconnectReason.connectionReplaced&&restarts++<5){void connect().catch(()=>failed("connection_unavailable"));return}failed("connection_unavailable")}});sock.ev.on("messaging-history.set",({chats,contacts,messages})=>{if(!owned(current,sock))return;for(const chat of chats)remember(chat.id,chat.name);for(const contact of contacts)remember(contact.id,contact.name??contact.notify);store(current,sock,messages,true)});sock.ev.on("chats.upsert",chats=>{if(owned(current,sock))for(const chat of chats)remember(chat.id,chat.name)});sock.ev.on("contacts.upsert",contacts=>{if(owned(current,sock))for(const contact of contacts)remember(contact.id,contact.name??contact.notify)});sock.ev.on("messages.upsert",({messages})=>{if(!owned(current,sock))return;for(const message of messages)if(!message.key.fromMe)remember(message.key.remoteJid,message.key.remoteJid?.endsWith("@g.us")?void 0:message.pushName);store(current,sock,messages)})};try{await connect()}catch(error){failed("connection_unavailable");throw error}return current}async function resume(){if(live&&!live.stopped)return live;if(resuming)return resuming;resuming=(async()=>{const connection=await vault.connection(SOURCE);if(!("ok"in connection))throw Error("account_permission_changed");if(connection.ok?.state!=="connected"||!connection.ok.accountId)return void 0;const grant=await vault.credential(SOURCE);if(!("ok"in grant))throw Error("account_permission_changed");const authority=await captureAuthority(connection.ok.accountId,grant.ok.accessToken);if(!("ok"in authority))throw Error("account_permission_changed");return start(grant.ok.accessToken,connection.ok.accountId,authority.ok)})();try{return await resuming}finally{resuming=void 0}}function cleanPairing(pair2){clearTimeout(pair2.timer);pair2.removeAbort?.();pair2.page?.close();pairings.delete(pair2)}function failPairing(pair2,code,message){if(pair2.job.state==="waiting-user"){pair2.job.state="failed";pair2.job.error={code,message};delete pair2.job.authorizationUrl;delete pair2.job.instructions;pair2.stop.abort();pair2.page?.update({state:"failed",message});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live)}cleanPairing(pair2)}function cancelPairing(pair2){if(pair2.job.state==="waiting-user")pair2.job.state="cancelled";delete pair2.job.authorizationUrl;delete pair2.job.instructions;delete pair2.job.error;pair2.stop.abort();pair2.page?.update({state:"failed",message:"WhatsApp connection was cancelled."});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live);cleanPairing(pair2)}async function pair(job,options,expectedAccountId){if(closed)throw Error("inactive");const owner={job,stop:new AbortController};pairings.add(owner);const abort=()=>failPairing(owner,"aborted","WhatsApp connection was cancelled.");options.signal?.addEventListener("abort",abort,{once:true});owner.removeAbort=()=>options.signal?.removeEventListener("abort",abort);try{owner.page=await pairingPage();if(closed||options.signal?.aborted||owner.stop.signal.aborted){abort();return}job.authorizationUrl=owner.page.url;job.instructions="Open the QR code page, then use WhatsApp on your phone: Settings \u2192 Linked devices \u2192 Link a device. The connection continues automatically after scanning.";job.error={code:"qr_scan_required",message:"Scan the WhatsApp QR code with your phone."};owner.timer=setTimeout(()=>failPairing(owner,"pairing_timeout","WhatsApp QR was not scanned before it expired."),pairingTimeoutMs);owner.timer.unref?.();if(live)stopLive(live);owner.entry=await start(void 0,expectedAccountId,void 0,view=>{if(job.state==="waiting-user")owner.page?.update(view)},async current=>{if(job.state==="connected"&&!closed)return;if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)throw Error("aborted");const credential=current.store.serialize();const saved=await vault.saveConnection({source:SOURCE,provider:SOURCE,account:current.socket?.user?.name?.slice(0,256)||"WhatsApp",accountId:current.accountId,scopes:["messages.read"],state:"connected",updatedAt:new Date().toISOString()},{accessToken:credential,clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]},{signal:owner.stop.signal});if(!("ok"in saved))throw Error("custody_failed");return{credential,complete:()=>{if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)return;clearTimeout(owner.timer);owner.removeAbort?.();job.state="connected";job.account=saved.ok.account;delete job.instructions;delete job.authorizationUrl;delete job.error;owner.page?.update({state:"connected"});owner.timer=setTimeout(()=>cleanPairing(owner),1e4);owner.timer.unref?.()}}},code=>failPairing(owner,code,code==="account_changed"?"The scanned WhatsApp account does not match the selected account.":"WhatsApp pairing did not complete."));if(owner.stop.signal.aborted)stopLive(owner.entry);if(!options.automatic&&options.manualPresentation!=="return-url"&&job.state==="waiting-user")await openUrl(owner.page.url)}catch{failPairing(owner,"pairing_unavailable","WhatsApp pairing page or connection could not start.")}}return{info,...transient?{}:{requiresPersistentPayloads:true},status:()=>connectionState(vault,info),job(id){const job=jobs.get(id);return job?ok({...job}):fail("not_found","WhatsApp connection job not found.")},cancelJob(id){const job=jobs.get(id);if(!job)return ok({id,cleanup:"confirmed"});const pairing=[...pairings].find(owner=>owner.job===job);if(pairing)cancelPairing(pairing);else if(job.state==="waiting-user")job.state="cancelled";delete job.authorizationUrl;delete job.instructions;return ok({id,cleanup:[...pairings].some(owner=>owner.job===job)?"pending":"confirmed"})},async connect(options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");const running=[...jobs.values()].find(job2=>job2.state==="waiting-user");if(running)return ok({...running});for(const[id,job2]of jobs)if(jobs.size>=32&&job2.state!=="waiting-user")jobs.delete(id);const job={id:randomUUID(),source:SOURCE,state:"waiting-user",startedAt:new Date().toISOString()};jobs.set(job.id,job);try{const selected=await vault.connection(SOURCE);if(!("ok"in selected))return selected;if(selected.ok&&!selected.ok.accountId)return fail("failed_precondition","WhatsApp needs a verified native account binding.");if(options.expectedBinding?.kind==="legacy-source"&&options.expectedBinding.source!==SOURCE)return fail("invalid_argument","WhatsApp account selection names another source.");if(options.expectedBinding?.kind==="binding"){const binding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in binding)||binding.ok.kind!=="resolved"||binding.ok.binding.id!==options.expectedBinding.bindingId)return fail("failed_precondition","WhatsApp account selection does not match this linked device.")}if(closed)return fail("unavailable","WhatsApp source is inactive.");const resumed=await track(resume());if(resumed){await waitUntil(resumed,()=>resumed.online||resumed.needsPairing,resumeTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");if(resumed.online){const allowed=await checkAuthority(resumed);if(!("ok"in allowed))return allowed;job.state="connected";if(selected.ok)job.account=selected.ok.account;return ok({...job})}if(!resumed.needsPairing){job.state="failed";job.error={code:resumed.failure??"connection_unavailable",message:resumed.failure==="account_changed"?"WhatsApp signed in as a different account.":"The existing WhatsApp session did not reconnect."};return ok({...job})}}if(options.automatic&&!transient){job.state="failed";job.error={code:"qr_scan_required",message:"WhatsApp needs one QR scan from the phone; connect it explicitly."};return ok({...job})}if(options.automatic&&selected.ok?.accountId&&vault.bindingCustody){const selectedBinding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if("ok"in selectedBinding&&selectedBinding.ok.kind==="resolved"){const grant=await vault.bindingCustody.grantForBinding(selectedBinding.ok.binding.id,"L1",SOURCE);if(!("ok"in grant))return grant;if(grant.ok?.state==="revoked")return fail("permission_denied","WhatsApp access was revoked. Reconnect explicitly to grant it again.")}}await track(pair(job,options,selected.ok?.accountId))}catch{job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp session permission or connection could not be verified."}}finally{if(job.state==="waiting-user"&&![...pairings].some(owner=>owner.job===job)){job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp did not start an owned connection job."}}}return ok({...job})},async read(request,options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");const invalid=validateRead(request);if(invalid)return invalid;if(request.fileId!==void 0)return fail("invalid_argument","WhatsApp message reads support limit, query and time filters; file download is not supported.");if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const connection=await vault.connection(SOURCE);if(!("ok"in connection))return connection;if(connection.ok?.state!=="connected"||!connection.ok.accountId)return fail("unauthenticated","Connect WhatsApp by scanning its QR code first.");const session=await track(resume()).catch(()=>void 0);const online=session?await waitUntil(session,()=>session.online,resumeTimeoutMs,options.signal):false;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const warnings=[];let records;if(transient){if(!online||!session)return fail("unavailable","WhatsApp is offline; transient reads need the selected live session.");const allowed=await checkAuthority(session);if(!("ok"in allowed)){stopLive(session);return allowed}await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");if(!owned(session)||!session.online)return fail("unavailable","WhatsApp session ended before the message read.");const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(!session.historyArrived)return fail("unavailable","No live WhatsApp message batch has arrived for this session yet. Retry after the phone finishes linking or a message arrives.");records=buffer.snapshot();warnings.push(`This live session retains at most ${TRANSIENT_MESSAGE_LIMIT} messages and 4 MiB in memory. Messages are not saved and are cleared on restart.`)}else{if(!online)warnings.push("WhatsApp is offline right now; showing messages already saved in the Vault.");if(online&&session&&!session.historyArrived){const stored2=await vault.records(SOURCE,1);if(!("ok"in stored2)||!stored2.ok.length)await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal)}await writes;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const stored=await vault.records(SOURCE,100);if(!("ok"in stored))return stored;records=stored.ok.map(row=>row.data);if(request.query||request.since||request.until)warnings.push("Filters apply to the 100 most recent saved messages; use SQL search over z_records for older history.")}const since=request.since?Date.parse(request.since):-Infinity,until=request.until?Date.parse(request.until):Infinity,query=request.query?.toLowerCase();records=records.filter(record=>record.sourceId?.startsWith(connection.ok.accountId+":")).filter(record=>{const at=Date.parse(record.ts??"");return at>=since&&at<=until}).filter(record=>!query||`${record.body} ${record.fields?.chat??""}`.toLowerCase().includes(query)).slice(0,request.limit??1);if(transient&&session){const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(closed||!owned(session)||options.signal?.aborted)return fail("aborted","WhatsApp read was cancelled before delivery.")}return readResult(SOURCE,records,warnings)},close(){if(closing)return closing;closing=(async()=>{closed=true;for(const owner of[...pairings]){if(owner.job.state==="waiting-user")failPairing(owner,"aborted","WhatsApp source was closed.");else cleanPairing(owner)}await Promise.allSettled([...initializing]);await writes;if(live){const current=live;await persistNow(current).catch(()=>void 0);stopLive(current)}buffer.clear();names.clear()})();return closing}}}
|