@zortexhq/indra-v2.5 0.2.7 → 0.2.8
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 +6 -4
- package/dist/auto-sync.js +1 -1
- package/dist/connector-worker.js +1 -1
- package/dist/content-find.js +8 -2
- package/dist/gateway.js +1 -1
- package/dist/local-cloud-policy.js +1 -1
- package/dist/local-cloud.js +1 -1
- package/dist/mcp.js +1 -1
- package/dist/public-tool.js +1 -1
- 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 +1 -1
- package/dist/source-data.js +1 -0
- package/dist/supervised-sync.js +1 -1
- package/dist/worker-google-auth.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-calendar/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-drive/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-framework/dist/manifest.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-framework/dist/runtime.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/brokered.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/gmail-source.js +2 -2
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-history/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-slack/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
- package/node_modules/@zortexhq/plugin-device-auth/dist/authority.js +1 -1
- package/node_modules/@zortexhq/plugin-google-auth/dist/index.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/source-sync.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/current-records.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/record-rules.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +8 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/source-sync.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +1 -1
- package/node_modules/@zortexhq/rooktrail/dist/record-rules.js +1 -1
- package/node_modules/@zortexhq/rooktrail/dist/registry.js +1 -1
- package/package.json +6 -6
- package/release-provenance.json +21 -21
- package/update-manifest.json +125 -95
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{EXEC_RESPONSE_BODY_MAX_BYTES,isOk,ok,sha256Hex}from"./original-contracts.js";export function createGmailSourceModule(parts){const{connectorError,gateRefusal,googleErrorReasonV1,googleStatusOverrideV1,readByIdAnswerV1,webStatusErrorV1}=parts;const GMAIL_AUDIT_RECENT_QUERY="newer_than:3d";const GMAIL_MESSAGE_PULL_CAP=5e4;const GMAIL_CENSUS_MAX_PAGES=5e3;const GMAIL_THREAD_PAGE_BYTE_BUDGET=24*1024*1024;const GMAIL_DELETIONS_CAP=5e4;const GMAIL_HISTORY_MAX_PAGES=5e3;const GMAIL_ATTACHMENT_CONTENT_CAP=1024*1024;const GMAIL_ATTACHMENT_TRANSPORT_SAFE_BYTES=Math.floor((EXEC_RESPONSE_BODY_MAX_BYTES-16384)*3/4);const GMAIL_API_BASE="https://gmail.googleapis.com/gmail/v1";const GMAIL_BATCH_URL="https://gmail.googleapis.com/batch/gmail/v1";const GMAIL_BATCH_CHUNK_SIZE=50;const GMAIL_WAN_GATE="G1-outbound chokepoint \u2014 live WAN transport opens at C-P6-1; real-provider OAuth walks at C-P6-2 (G2)";const refuseWanTransport=()=>({ok:false,error:GMAIL_WAN_GATE});function buildAttachmentContent(mimeType,bytes,cap){if(bytes.length>cap)return{contentOmitted:"over-cap"};const mime=mimeType!==""?mimeType:"application/octet-stream";const b64=Buffer.from(bytes).toString("base64");return{sha256:sha256Hex(bytes),contentDataUri:`data:${mime};base64,${b64}`}}function chunkIds(ids,size){const chunks=[];for(let i=0;i<ids.length;i+=size)chunks.push(ids.slice(i,i+size));return chunks}function headerBodySplit(text,from=0){const crlf=text.indexOf("\r\n\r\n",from);const lf=text.indexOf("\n\n",from);if(crlf<0&&lf<0)return null;if(crlf>=0&&(lf<0||crlf<=lf))return{index:crlf,sepLen:4};return{index:lf,sepLen:2}}function splitMultipartMixed(body){const opening=/(?:^|\r?\n)--([^\r\n]+)\r?\n/.exec(body);if(opening===null)return null;const delimiter=`--${opening[1]}`;const parts2=[];for(const raw of body.split(delimiter).slice(1)){if(raw.startsWith("--"))break;const segment=raw.replace(/^\r?\n/,"");const split=headerBodySplit(segment);if(split===null)return null;const headers=segment.slice(0,split.index);const nested=segment.slice(split.index+split.sepLen);const id=/^Content-ID:\s*<?([^>\r\n]+)>?/im.exec(headers);const status=/^HTTP\/[\d.]+\s+(\d{3})/.exec(nested);const nestedSplit=headerBodySplit(nested);if(status===null||nestedSplit===null)return null;parts2.push({contentId:id?.[1]?.trim()??null,status:Number.parseInt(status[1],10),body:nested.slice(nestedSplit.index+nestedSplit.sepLen)})}return parts2.length===0?null:parts2}const GMAIL_METADATA_HEADERS=["From","To","Cc","Subject","Date"];const GMAIL_STARTER_MESSAGE_LIMIT=10;const GMAIL_STARTER_CONTENT_BYTES=1024*1024;function decodedBytes(part){if(part===void 0)return 0;const own=typeof part.body?.data==="string"?Buffer.from(part.body.data,"base64url").byteLength:0;return own+(part.parts??[]).reduce((total,child)=>total+decodedBytes(child),0)}function stripStarterBody(part){if(part===void 0)return void 0;const body=part.body===void 0?void 0:{...part.body.attachmentId===void 0?{}:{attachmentId:part.body.attachmentId},...part.body.size===void 0?{}:{size:part.body.size}};return{...part.partId===void 0?{}:{partId:part.partId},...part.mimeType===void 0?{}:{mimeType:part.mimeType},...part.filename===void 0?{}:{filename:part.filename},...part.headers===void 0?{}:{headers:part.headers.map(header=>({...header}))},...body===void 0?{}:{body},...part.parts===void 0?{}:{parts:part.parts.map(stripStarterBody)}}}function capStarterContent(messages,budget){let consumed=0;return messages.map(message=>{const bytes=decodedBytes(message.payload);if(consumed+bytes<=budget){consumed+=bytes;return message}return{...message,...message.payload===void 0?{}:{payload:stripStarterBody(message.payload)},starterContentOmitted:"starter-cap"}})}class HttpGmailSource{transport;authHeaders;cap;pageSize;attachmentCap;query;messageFormat;messageLimit;starterContentBytes;fetchAttachments;resolvedAccount=null;prefetch;threadPageByteBudget;constructor(transport,authHeaders,cap,pageSize,attachmentCap,query,messageFormat,messageLimit,starterContentBytes,fetchAttachments,prefetch,threadPageByteBudget=GMAIL_THREAD_PAGE_BYTE_BUDGET){this.threadPageByteBudget=threadPageByteBudget;this.transport=transport;this.authHeaders=authHeaders;this.cap=cap;this.pageSize=pageSize;this.attachmentCap=attachmentCap;this.query=query;this.messageFormat=messageFormat;this.messageLimit=messageLimit;this.starterContentBytes=starterContentBytes;this.fetchAttachments=fetchAttachments;this.prefetch=prefetch}batchRequest(ids,headersParam,headers){const boundary=sha256Hex(Buffer.from([...ids].sort().join("\0"),"utf8"));const body=ids.map(id=>{const path=`/gmail/v1/users/me/messages/${encodeURIComponent(id)}?format=${this.messageFormat}${headersParam}`;return`--${boundary}\r
|
|
1
|
+
import{EXEC_RESPONSE_BODY_MAX_BYTES,isOk,ok,sha256Hex}from"./original-contracts.js";export function createGmailSourceModule(parts){const{connectorError,gateRefusal,googleErrorReasonV1,googleStatusOverrideV1,readByIdAnswerV1,webStatusErrorV1}=parts;const GMAIL_AUDIT_RECENT_QUERY="newer_than:3d";const GMAIL_MESSAGE_PULL_CAP=5e4;const GMAIL_CENSUS_MAX_PAGES=5e3;const GMAIL_THREAD_PAGE_BYTE_BUDGET=24*1024*1024;const GMAIL_DELETIONS_CAP=5e4;const GMAIL_HISTORY_MAX_PAGES=5e3;const GMAIL_ATTACHMENT_CONTENT_CAP=1024*1024;const GMAIL_ATTACHMENT_TRANSPORT_SAFE_BYTES=Math.floor((EXEC_RESPONSE_BODY_MAX_BYTES-16384)*3/4);const GMAIL_API_BASE="https://gmail.googleapis.com/gmail/v1";const GMAIL_BATCH_URL="https://gmail.googleapis.com/batch/gmail/v1";const GMAIL_BATCH_CHUNK_SIZE=50;const GMAIL_WAN_GATE="G1-outbound chokepoint \u2014 live WAN transport opens at C-P6-1; real-provider OAuth walks at C-P6-2 (G2)";const refuseWanTransport=()=>({ok:false,error:GMAIL_WAN_GATE});function buildAttachmentContent(mimeType,bytes,cap){if(bytes.length>cap)return{contentOmitted:"over-cap"};const mime=mimeType!==""?mimeType:"application/octet-stream";const b64=Buffer.from(bytes).toString("base64");return{sha256:sha256Hex(bytes),contentDataUri:`data:${mime};base64,${b64}`}}function chunkIds(ids,size){const chunks=[];for(let i=0;i<ids.length;i+=size)chunks.push(ids.slice(i,i+size));return chunks}function headerBodySplit(text,from=0){const crlf=text.indexOf("\r\n\r\n",from);const lf=text.indexOf("\n\n",from);if(crlf<0&&lf<0)return null;if(crlf>=0&&(lf<0||crlf<=lf))return{index:crlf,sepLen:4};return{index:lf,sepLen:2}}function splitMultipartMixed(body){const opening=/(?:^|\r?\n)--([^\r\n]+)\r?\n/.exec(body);if(opening===null)return null;const delimiter=`--${opening[1]}`;const parts2=[];for(const raw of body.split(delimiter).slice(1)){if(raw.startsWith("--"))break;const segment=raw.replace(/^\r?\n/,"");const split=headerBodySplit(segment);if(split===null)return null;const headers=segment.slice(0,split.index);const nested=segment.slice(split.index+split.sepLen);const id=/^Content-ID:\s*<?([^>\r\n]+)>?/im.exec(headers);const status=/^HTTP\/[\d.]+\s+(\d{3})/.exec(nested);const nestedSplit=headerBodySplit(nested);if(status===null||nestedSplit===null)return null;parts2.push({contentId:id?.[1]?.trim()??null,status:Number.parseInt(status[1],10),body:nested.slice(nestedSplit.index+nestedSplit.sepLen)})}return parts2.length===0?null:parts2}const GMAIL_METADATA_HEADERS=["From","To","Cc","Subject","Date"];const GMAIL_STARTER_MESSAGE_LIMIT=10;const GMAIL_STARTER_CONTENT_BYTES=1024*1024;function decodedBytes(part){if(part===void 0)return 0;const own=typeof part.body?.data==="string"?Buffer.from(part.body.data,"base64url").byteLength:0;return own+(part.parts??[]).reduce((total,child)=>total+decodedBytes(child),0)}function stripStarterBody(part){if(part===void 0)return void 0;const body=part.body===void 0?void 0:{...part.body.attachmentId===void 0?{}:{attachmentId:part.body.attachmentId},...part.body.size===void 0?{}:{size:part.body.size}};return{...part.partId===void 0?{}:{partId:part.partId},...part.mimeType===void 0?{}:{mimeType:part.mimeType},...part.filename===void 0?{}:{filename:part.filename},...part.headers===void 0?{}:{headers:part.headers.map(header=>({...header}))},...body===void 0?{}:{body},...part.parts===void 0?{}:{parts:part.parts.map(stripStarterBody)}}}function capStarterContent(messages,budget){let consumed=0;return messages.map(message=>{const bytes=decodedBytes(message.payload);if(consumed+bytes<=budget){consumed+=bytes;return message}return{...message,...message.payload===void 0?{}:{payload:stripStarterBody(message.payload)},starterContentOmitted:"starter-cap"}})}class HttpGmailSource{transport;authHeaders;cap;pageSize;attachmentCap;query;selectedMessageIds;messageFormat;messageLimit;starterContentBytes;fetchAttachments;resolvedAccount=null;prefetch;threadPageByteBudget;constructor(transport,authHeaders,cap,pageSize,attachmentCap,query,selectedMessageIds,messageFormat,messageLimit,starterContentBytes,fetchAttachments,prefetch,threadPageByteBudget=GMAIL_THREAD_PAGE_BYTE_BUDGET){this.threadPageByteBudget=threadPageByteBudget;this.transport=transport;this.authHeaders=authHeaders;this.cap=cap;this.pageSize=pageSize;this.attachmentCap=attachmentCap;this.query=query;this.selectedMessageIds=selectedMessageIds;this.messageFormat=messageFormat;this.messageLimit=messageLimit;this.starterContentBytes=starterContentBytes;this.fetchAttachments=fetchAttachments;this.prefetch=prefetch}batchRequest(ids,headersParam,headers){const boundary=sha256Hex(Buffer.from([...ids].sort().join("\0"),"utf8"));const body=ids.map(id=>{const path=`/gmail/v1/users/me/messages/${encodeURIComponent(id)}?format=${this.messageFormat}${headersParam}`;return`--${boundary}\r
|
|
2
2
|
Content-Type: application/http\r
|
|
3
3
|
Content-ID: <${id}>\r
|
|
4
4
|
\r
|
|
5
5
|
GET ${path} HTTP/1.1\r
|
|
6
6
|
\r
|
|
7
7
|
`}).join("")+`--${boundary}--\r
|
|
8
|
-
`;return{url:GMAIL_BATCH_URL,headers:{...headers,"Content-Type":`multipart/mixed; boundary=${boundary}`},method:"POST",body}}hint(grant,ids,headersParam){if(this.prefetch===void 0||ids.length===0)return;const hdrs=this.authHeaders(grant);if(!isOk(hdrs))return;for(const chunk of chunkIds(ids,GMAIL_BATCH_CHUNK_SIZE)){this.prefetch([this.batchRequest(chunk,headersParam,hdrs.ok)])}}hintGets(grant,paths){if(this.prefetch===void 0||paths.length===0)return;const headers=this.authHeaders(grant);if(!isOk(headers))return;this.prefetch(paths.map(path=>({url:`${GMAIL_API_BASE}${path}`,headers:headers.ok,method:"GET"})))}static create(opts){return new HttpGmailSource(opts.transport??refuseWanTransport,opts.authHeaders,opts.cap??GMAIL_MESSAGE_PULL_CAP,opts.pageSize??100,opts.attachmentCap??GMAIL_ATTACHMENT_CONTENT_CAP,opts.query!==void 0&&opts.query.trim()!==""?opts.query.trim():void 0,opts.messageFormat??"full",opts.messageLimit??null,opts.starterContentBytes??null,opts.fetchAttachments??true,opts.prefetch,opts.threadPageByteBudget??GMAIL_THREAD_PAGE_BYTE_BUDGET)}get(grant,path,what){const hdrs=this.authHeaders(grant);if(!isOk(hdrs))return hdrs;const res=this.transport(`${GMAIL_API_BASE}${path}`,hdrs.ok);if(!res.ok){if(res.structuredError!==void 0)return{err:res.structuredError};if(res.error===GMAIL_WAN_GATE)return gateRefusal("gmail live WAN transport",GMAIL_WAN_GATE);return connectorError("unavailable",`gmail ${what} transport failure: ${res.error} \u2014 NEVER an empty success (FM-21)`,"transient")}return this.routeStatus(res.status,res.body,what)}routeStatus(status,body,what){if(status===200){try{return ok(JSON.parse(body))}catch{return connectorError("internal",`gmail ${what}: 200 body is not JSON \u2014 REST-surface drift (FM-19)`)}}return{err:webStatusErrorV1(status,{provider:"gmail",what,bodyOverride:googleStatusOverrideV1(body),...googleErrorReasonV1(body)===void 0?{}:{detail:googleErrorReasonV1(body)}})}}batchGetMessages(grant,ids,headersParam){const auth=this.authHeaders(grant);if(!isOk(auth))return auth;const request=this.batchRequest(ids,headersParam,auth.ok);const response=this.transport(request.url,request.headers,{method:request.method,body:request.body});if(!response.ok){if(response.structuredError!==void 0)return{err:response.structuredError};if(response.error===GMAIL_WAN_GATE)return gateRefusal("gmail live WAN transport",GMAIL_WAN_GATE);return connectorError("unavailable",`gmail messages.batchGet transport failure: ${response.error} \u2014 NEVER an empty success (FM-21)`,"transient")}if(response.status!==200)return this.routeStatus(response.status,response.body,"messages.batchGet");const parts2=splitMultipartMixed(response.body);if(parts2===null)return connectorError("internal","gmail messages.batchGet: malformed multipart response \u2014 REST-surface drift (FM-19)");const out=new Map;const throttled=[];for(const part of parts2){if(part.contentId===null)return connectorError("internal","gmail messages.batchGet: missing Content-ID \u2014 cannot correlate response (FM-19)");const contentId=part.contentId.replace(/^response-/,"");const id=ids.find(candidate=>contentId===candidate||contentId.endsWith(`/${candidate}`));if(id===void 0||out.has(id)||throttled.includes(id))return connectorError("internal",`gmail messages.batchGet: unexpected or duplicate Content-ID '${part.contentId}' (FM-19)`);const routed=this.routeStatus(part.status,part.body,"messages.get");if(!isOk(routed)){if("err"in routed&&routed.err.retryability==="throttling"){throttled.push(id);continue}return routed}out.set(id,routed.ok)}for(const id of throttled){const single=this.get(grant,`/users/me/messages/${encodeURIComponent(id)}?format=${this.messageFormat}${headersParam}`,"messages.get");if(!isOk(single))return single;out.set(id,single.ok)}for(const id of ids){if(!out.has(id))return connectorError("internal",`gmail messages.batchGet: response omitted message '${id}' (FM-19)`)}return ok(out)}account(grant){if(this.resolvedAccount!==null)return ok(this.resolvedAccount);const p=this.getProfile(grant);if(!isOk(p))return p;this.resolvedAccount=p.ok.emailAddress;return ok(this.resolvedAccount)}getProfile(grant){const r=this.get(grant,"/users/me/profile","getProfile");if(!isOk(r))return r;const o=r.ok;if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail getProfile: response is not an object \u2014 REST-surface drift (FM-19)")}const email=o.emailAddress;if(typeof email!=="string"||email===""){return connectorError("internal","gmail getProfile: emailAddress missing \u2014 cannot source the account epoch (REST-surface drift, FM-19)")}return ok(o)}enumerateAll(grant,path,listKey,what){const out=[];let pageToken=null;const seenPageTokens=new Set;let pages=0;for(;;){if(pages>=GMAIL_CENSUS_MAX_PAGES){return connectorError("resource_exhausted",`gmail ${what} census exceeded the ${GMAIL_CENSUS_MAX_PAGES}-page safety cap \u2014 refusing a partial census`,"non-retryable")}pages+=1;const sep=path.includes("?")?"&":"?";const searchable=path.includes("/messages")||path.includes("/threads");const q=`${sep}maxResults=500${searchable&&this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const r=this.get(grant,`${path}${q}`,what);if(!isOk(r))return r;const parsed=this.parseListIds(r.ok,listKey,what);if(!isOk(parsed))return parsed;for(const id of parsed.ok.ids)out.push(id);if(out.length>this.cap){return connectorError("resource_exhausted",`gmail ${what} enumeration exceeded the ${this.cap} cap \u2014 refusing a partial census (loud, never a silent truncation that would misreconcile FM-18); narrow the sync window`,"non-retryable")}if(parsed.ok.nextPageToken===null)return ok(out);if(seenPageTokens.has(parsed.ok.nextPageToken)){return connectorError("data_loss",`gmail ${what} census repeated a provider page token \u2014 refusing a partial census`,"non-retryable")}seenPageTokens.add(parsed.ok.nextPageToken);pageToken=parsed.ok.nextPageToken}}parseListIds(o,listKey,what){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal",`gmail ${what}: response is not an object \u2014 REST-surface drift (FM-19)`)}const raw=o[listKey];const ids=[];if(raw!==void 0){if(!Array.isArray(raw)){return connectorError("internal",`gmail ${what}: \`${listKey}\` is not an array \u2014 REST-surface drift (FM-19)`)}for(const row of raw){const id=row?.id;if(typeof id!=="string"||id===""){return connectorError("internal",`gmail ${what}: a row is missing a string \`id\` \u2014 REST-surface drift (FM-19)`)}ids.push(id)}}const next=o.nextPageToken;if(next!==void 0&&typeof next!=="string"){return connectorError("internal",`gmail ${what}: nextPageToken is not a string \u2014 REST-surface drift (FM-19)`)}return ok({ids,nextPageToken:typeof next==="string"&&next!==""?next:null})}parseIdList(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail messages.list: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const raw=rec.messages;const ids=[];if(raw!==void 0){if(!Array.isArray(raw)){return connectorError("internal","gmail messages.list: `messages` is not an array \u2014 REST-surface drift (FM-19)")}for(const m of raw){const id=m?.id;if(typeof id!=="string"||id===""){return connectorError("internal","gmail messages.list: a row is missing a string `id` \u2014 REST-surface drift (FM-19)")}const threadId=m.threadId;ids.push({id,...typeof threadId==="string"?{threadId}:{}})}}const next=rec.nextPageToken;if(next!==void 0&&typeof next!=="string"){return connectorError("internal","gmail messages.list: nextPageToken is not a string \u2014 REST-surface drift (FM-19)")}return ok({ids,nextPageToken:typeof next==="string"&&next!==""?next:null})}census(grant){const msgs=this.enumerateAll(grant,"/users/me/messages?includeSpamTrash=true","messages","messages.list");if(!isOk(msgs))return msgs;const labelsR=this.labels(grant);if(!isOk(labelsR))return labelsR;const threads=this.enumerateAll(grant,"/users/me/threads?includeSpamTrash=true","threads","threads.list");if(!isOk(threads))return threads;const drafts=this.enumerateAll(grant,"/users/me/drafts","drafts","drafts.list");if(!isOk(drafts))return drafts;return ok({messages:{total:msgs.ok.length},labels:{total:labelsR.ok.length},threads:{total:threads.ok.length},drafts:{total:drafts.ok.length}})}messagesPage(grant,pageToken,maxMessages){const acct=this.account(grant);if(!isOk(acct))return acct;if(this.messageLimit!==null&&pageToken!==null){return connectorError("invalid_argument","gmail starter source has one bounded page","non-retryable")}const wanted=this.messageLimit===null?maxMessages:maxMessages===void 0?this.messageLimit:Math.min(maxMessages,this.messageLimit);const pageSize=wanted===void 0?this.pageSize:Math.min(this.pageSize,wanted);const q=`maxResults=${pageSize}&includeSpamTrash=true${this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const listR=this.get(grant,`/users/me/messages?${q}`,"messages.list");if(!isOk(listR))return listR;const parsed=this.parseIdList(listR.ok);if(!isOk(parsed))return parsed;if(wanted!==void 0&&parsed.ok.ids.length>wanted){return connectorError("data_loss",`gmail messages.list returned ${parsed.ok.ids.length} IDs for a requested page size of ${wanted}`,"non-retryable")}const ids=(wanted===void 0?parsed.ok.ids:parsed.ok.ids.slice(0,wanted)).map(({id})=>id);const headersParam=this.messageFormat==="metadata"?GMAIL_METADATA_HEADERS.map(h=>`&metadataHeaders=${h}`).join(""):"";const messages=[];const attachments=[];this.hint(grant,ids,headersParam);const hydrated=this.hydrateMessages(grant,acct.ok,ids,false);if(!isOk(hydrated))return hydrated;messages.push(...hydrated.ok.messages);attachments.push(...hydrated.ok.attachments);return ok({messages:this.starterContentBytes===null?messages:capStarterContent(messages,this.starterContentBytes),attachments,nextPageToken:this.messageLimit===null?parsed.ok.nextPageToken:null})}messageCensus(grant){const ids=this.enumerateAll(grant,`/users/me/messages?includeSpamTrash=true${this.query===void 0?"":`&q=${encodeURIComponent(this.query)}`}`,"messages","messages.list");if(!isOk(ids))return ids;return ok(ids.ok.length)}hydrateMessages(grant,account,ids,skipGone){const headersParam=this.messageFormat==="metadata"?GMAIL_METADATA_HEADERS.map(h=>`&metadataHeaders=${h}`).join(""):"";const messages=[];const attachments=[];const keep=raw=>{const m=this.parseMessage(raw,account);if(!isOk(m))return m;messages.push(this.messageFormat==="metadata"?{...m.ok,starterContentOmitted:"fields-metadata"}:m.ok);if(this.messageFormat==="full"&&this.messageLimit===null&&this.fetchAttachments){const att=this.attachmentsFor(grant,m.ok);if(!isOk(att))return att;for(const a of att.ok)attachments.push(a)}return ok(true)};if(!skipGone){for(const chunk of chunkIds([...ids],GMAIL_BATCH_CHUNK_SIZE)){const batch=this.batchGetMessages(grant,chunk,headersParam);if(!isOk(batch))return batch;for(const id of chunk){const kept=keep(batch.ok.get(id));if(!isOk(kept))return kept}}return ok({messages,attachments})}for(const id of ids){const getR=this.get(grant,`/users/me/messages/${encodeURIComponent(id)}?format=${this.messageFormat}${headersParam}`,"messages.get");if(!isOk(getR)){if(skipGone&&getR.err.code==="not_found")continue;return getR}const m=this.parseMessage(getR.ok,account);if(!isOk(m))return m;messages.push(this.messageFormat==="metadata"?{...m.ok,starterContentOmitted:"fields-metadata"}:m.ok);if(this.messageFormat==="full"&&this.messageLimit===null&&this.fetchAttachments){const att=this.attachmentsFor(grant,m.ok);if(!isOk(att))return att;for(const a of att.ok)attachments.push(a)}}return ok({messages,attachments})}listMessageIdsPage(grant,scope,pageToken,maxPages){const base=this.query===void 0?scope==="recent"?GMAIL_AUDIT_RECENT_QUERY:void 0:scope==="recent"?`(${this.query}) ${GMAIL_AUDIT_RECENT_QUERY}`:this.query;const ids=[];let token=pageToken;for(let pages=0;pages<Math.max(1,maxPages);pages++){const r=this.get(grant,`/users/me/messages?includeSpamTrash=true&maxResults=500${base===void 0?"":`&q=${encodeURIComponent(base)}`}${token!==null?`&pageToken=${encodeURIComponent(token)}`:""}`,"messages.list");if(!isOk(r))return r;const parsed=this.parseListIds(r.ok,"messages","messages.list");if(!isOk(parsed))return parsed;for(const id of parsed.ok.ids)ids.push(id);token=parsed.ok.nextPageToken;if(token===null)break}return ok({ids,nextPageToken:token})}messageEvidence(grant,id){const hdrs=this.authHeaders(grant);if(!isOk(hdrs))return hdrs;const res=this.transport(`${GMAIL_API_BASE}/users/me/messages/${encodeURIComponent(id)}?format=minimal`,hdrs.ok);if(!res.ok){if(res.structuredError!==void 0)return{err:res.structuredError};if(res.error===GMAIL_WAN_GATE)return gateRefusal("gmail live WAN transport",GMAIL_WAN_GATE);return connectorError("unavailable",`gmail messages.get (audit evidence) transport failure: ${res.error} \u2014 never "not-found" (FM-21)`,"transient")}const answer=readByIdAnswerV1(res.status,{provider:"gmail",what:"messages.get (audit evidence)",bodyOverride:googleStatusOverrideV1(res.body),...googleErrorReasonV1(res.body)===void 0?{}:{detail:googleErrorReasonV1(res.body)}});if("err"in answer)return answer;if(answer.ok==="not-found")return ok("not-found");let body;try{body=JSON.parse(res.body)}catch{return connectorError("internal","gmail messages.get (audit evidence): 200 body is not JSON \u2014 REST-surface drift (FM-19)")}const labels=body!==null&&typeof body==="object"?body.labelIds:void 0;return ok(Array.isArray(labels)&&labels.includes("TRASH")?"trashed":"present")}messagesByIds(grant,ids){const acct=this.account(grant);if(!isOk(acct))return acct;return this.hydrateMessages(grant,acct.ok,ids,true)}messageChanges(grant,sinceHistoryId,maxMessages){const acct=this.account(grant);if(!isOk(acct))return acct;const changed=[];const seen=new Set;const deletions=[];const deletedIds=new Set;let pageToken=null;let pages=0;let lastRecord=null;let mailboxHistoryId=null;let more=false;walk:for(;;){const types=["messageAdded","labelAdded","labelRemoved","messageDeleted"].map(t=>`&historyTypes=${t}`).join("");const q=`startHistoryId=${encodeURIComponent(sinceHistoryId)}${types}&maxResults=500${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const r=this.get(grant,`/users/me/history?${q}`,"history.list");if(!isOk(r))return r;const parsed=this.parseHistoryChanges(r.ok);if(!isOk(parsed))return parsed;mailboxHistoryId=parsed.ok.historyId??mailboxHistoryId;for(const record of parsed.ok.records){const fresh=record.changed.filter(id=>!seen.has(id));if(changed.length>0&&changed.length+fresh.length>maxMessages){more=true;break walk}for(const id of fresh){seen.add(id);changed.push(id)}for(const id of record.deleted){deletedIds.add(id);deletions.push({account:acct.ok,id,atHistoryId:record.id})}lastRecord=record.id}if(++pages>GMAIL_HISTORY_MAX_PAGES){return connectorError("resource_exhausted",`gmail history.list pagination exceeded ${GMAIL_HISTORY_MAX_PAGES} pages \u2014 pageToken-cycle drift (FM-19)`,"non-retryable")}if(parsed.ok.nextPageToken===null)break;pageToken=parsed.ok.nextPageToken}const hydrated=this.hydrateMessages(grant,acct.ok,changed.filter(id=>!deletedIds.has(id)),true);if(!isOk(hydrated))return hydrated;return ok({...hydrated.ok,deletions,historyId:more?lastRecord:mailboxHistoryId??lastRecord,more})}parseHistoryChanges(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail history.list: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const records=[];if(rec.history!==void 0){if(!Array.isArray(rec.history))return connectorError("internal","gmail history.list: `history` is not an array \u2014 REST-surface drift (FM-19)");for(const record of rec.history){const id=record?.id;if(typeof id!=="string"||id==="")return connectorError("internal","gmail history.list: a history record is missing string `id` \u2014 REST-surface drift (FM-19)");const idsOf=key=>{const rows=record[key];if(rows===void 0)return ok([]);if(!Array.isArray(rows))return connectorError("internal",`gmail history.list: \`${key}\` is not an array \u2014 REST-surface drift (FM-19)`);const out=[];for(const row of rows){const mid=row?.message?.id;if(typeof mid!=="string"||mid==="")return connectorError("internal",`gmail history.list: a ${key} row is missing message.id \u2014 REST-surface drift (FM-19)`);out.push(mid)}return ok(out)};const added=idsOf("messagesAdded");const labelled=idsOf("labelsAdded");const unlabelled=idsOf("labelsRemoved");const deleted=idsOf("messagesDeleted");for(const part of[added,labelled,unlabelled,deleted])if(!isOk(part))return part;records.push({id,changed:[...added.ok,...labelled.ok,...unlabelled.ok],deleted:deleted.ok})}}const next=rec.nextPageToken;if(next!==void 0&&typeof next!=="string")return connectorError("internal","gmail history.list: nextPageToken is not a string \u2014 REST-surface drift (FM-19)");const hid=rec.historyId;return ok({records,nextPageToken:typeof next==="string"&&next!==""?next:null,historyId:typeof hid==="string"&&hid!==""?hid:null})}attachmentsFor(grant,m){const descriptors=this.collectAttachments(m.payload);const out=[];for(const d of descriptors){const base={account:m.account,messageId:m.id,...m.threadId!==void 0?{threadId:m.threadId}:{},partId:d.partId,attachmentId:d.attachmentId,filename:d.filename,mimeType:d.mimeType,size:d.size,...m.internalDate!==void 0?{internalDate:m.internalDate}:{}};if(d.size>this.attachmentCap||d.size>GMAIL_ATTACHMENT_TRANSPORT_SAFE_BYTES){out.push({...base,contentOmitted:"over-cap"});continue}const bodyR=this.get(grant,`/users/me/messages/${encodeURIComponent(m.id)}/attachments/${encodeURIComponent(d.attachmentId)}`,"messages.attachments.get");if(!isOk(bodyR))return bodyR;const parsed=this.parseAttachmentBody(bodyR.ok);if(!isOk(parsed))return parsed;const bytes=Buffer.from(parsed.ok.data,"base64url");const content=buildAttachmentContent(d.mimeType,bytes,this.attachmentCap);out.push({...base,size:bytes.length,...content})}return ok(out)}collectAttachments(payload){const out=[];const walk=(part,path)=>{const attId=part.body?.attachmentId;if(typeof attId==="string"&&attId!==""){const partId=typeof part.partId==="string"&&part.partId!==""?part.partId:path;out.push({partId,attachmentId:attId,filename:typeof part.filename==="string"?part.filename:"",mimeType:typeof part.mimeType==="string"?part.mimeType:"application/octet-stream",size:typeof part.body?.size==="number"?part.body.size:0})}const parts2=part.parts??[];for(let i=0;i<parts2.length;i++)walk(parts2[i],path===""?String(i):`${path}.${i}`)};if(payload!==void 0)walk(payload,"");return out}parseAttachmentBody(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail attachments.get: response is not an object \u2014 REST-surface drift (FM-19)")}const data=o.data;if(typeof data!=="string"){return connectorError("internal","gmail attachments.get: missing string `data` (the attachment bytes) \u2014 REST-surface drift (FM-19)")}const size=o.size;return ok({size:typeof size==="number"?size:0,data})}parseMessage(o,account){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail messages.get: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const id=rec["id"];if(typeof id!=="string"||id===""){return connectorError("internal","gmail messages.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)")}const historyId=rec["historyId"];if(typeof historyId!=="string"||historyId===""){return connectorError("internal",`gmail messages.get '${id}': missing string \`historyId\` (the upstream-version rev token) \u2014 REST-surface drift (FM-19)`)}return ok({...rec,account})}threadsByIds(grant,ids){const acct=this.account(grant);if(!isOk(acct))return acct;const threads=[];for(const id of ids){const getR=this.get(grant,`/users/me/threads/${encodeURIComponent(id)}?format=metadata`,"threads.get");if(!isOk(getR)){if(getR.err.code==="not_found")continue;return getR}const t=this.parseThread(getR.ok,acct.ok);if(!isOk(t))return t;threads.push(t.ok)}return ok({threads})}threadsPage(grant,pageToken){let pageIds;let consumed;let nextProviderPageToken;if(pageToken!==null&&typeof pageToken!=="string"){const continuation=this.validateThreadContinuation(pageToken);if(!isOk(continuation))return continuation;pageIds=continuation.ok.ids;consumed=continuation.ok.consumed;nextProviderPageToken=continuation.ok.nextProviderPageToken}else{consumed=0;const providerPageToken=pageToken;const q=`maxResults=${this.pageSize}&includeSpamTrash=true${this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${providerPageToken!==null?`&pageToken=${encodeURIComponent(providerPageToken)}`:""}`;const listR=this.get(grant,`/users/me/threads?${q}`,"threads.list");if(!isOk(listR))return listR;const parsed=this.parseListIds(listR.ok,"threads","threads.list");if(!isOk(parsed))return parsed;pageIds=parsed.ok.ids;nextProviderPageToken=parsed.ok.nextPageToken}const acct=this.account(grant);if(!isOk(acct))return acct;const threads=[];let pageBytes=0;let largestThreadBytes=0;for(let i=consumed;i<pageIds.length;i++){const id=pageIds[i];const getR=this.get(grant,`/users/me/threads/${encodeURIComponent(id)}?format=metadata`,"threads.get");if(!isOk(getR))return getR;const t=this.parseThread(getR.ok,acct.ok);if(!isOk(t))return t;threads.push(t.ok);const threadBytes=new TextEncoder().encode(JSON.stringify(getR.ok)).byteLength;pageBytes+=threadBytes;largestThreadBytes=Math.max(largestThreadBytes,threadBytes);const nextConsumed=i+1;if(pageBytes+largestThreadBytes>this.threadPageByteBudget&&nextConsumed<pageIds.length){return ok({threads,nextPageToken:{kind:"gmail-thread-page-v1",ids:[...pageIds],consumed:nextConsumed,nextProviderPageToken}})}}return ok({threads,nextPageToken:nextProviderPageToken})}validateThreadContinuation(value){if(value===null||typeof value!=="object"||Array.isArray(value)){return connectorError("invalid_argument","gmail threads continuation must be a stable page-identity object")}const row=value;if(row["kind"]!=="gmail-thread-page-v1"){return connectorError("invalid_argument","gmail threads continuation has an unknown version")}const ids=row["ids"];if(!Array.isArray(ids)||ids.length===0||ids.some(id=>typeof id!=="string"||id==="")){return connectorError("invalid_argument","gmail threads continuation ids must be a non-empty provider-id page")}const consumed=row["consumed"];if(!Number.isSafeInteger(consumed)||consumed<=0||consumed>=ids.length){return connectorError("invalid_argument",`gmail threads continuation boundary '${String(consumed)}' is outside its ${ids.length}-id stable page`)}const nextProviderPageToken=row["nextProviderPageToken"];if(nextProviderPageToken!==null&&typeof nextProviderPageToken!=="string"){return connectorError("invalid_argument","gmail threads continuation next provider token must be an opaque string or null")}return ok({kind:"gmail-thread-page-v1",ids:[...ids],consumed,nextProviderPageToken})}parseThread(o,account){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail threads.get: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const id=rec["id"];if(typeof id!=="string"||id===""){return connectorError("internal","gmail threads.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)")}const historyId=rec["historyId"];if(typeof historyId!=="string"||historyId===""){return connectorError("internal",`gmail threads.get '${id}': missing string \`historyId\` (the upstream-version rev token) \u2014 REST-surface drift (FM-19)`)}let messages;const rawMsgs=rec["messages"];if(rawMsgs!==void 0){if(!Array.isArray(rawMsgs)){return connectorError("internal",`gmail threads.get '${id}': \`messages\` is not an array \u2014 REST-surface drift (FM-19)`)}messages=[];for(const rm of rawMsgs){const pm=this.parseMessage(rm,account);if(!isOk(pm))return pm;messages.push(pm.ok)}}return ok({...rec,account,...messages!==void 0?{messages}:{}})}draftsPage(grant,pageToken){const acct=this.account(grant);if(!isOk(acct))return acct;const q=`maxResults=${this.pageSize}${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const listR=this.get(grant,`/users/me/drafts?${q}`,"drafts.list");if(!isOk(listR))return listR;const parsed=this.parseListIds(listR.ok,"drafts","drafts.list");if(!isOk(parsed))return parsed;const drafts=[];this.hintGets(grant,parsed.ok.ids.map(id=>`/users/me/drafts/${encodeURIComponent(id)}?format=full`));for(const id of parsed.ok.ids){const getR=this.get(grant,`/users/me/drafts/${encodeURIComponent(id)}?format=full`,"drafts.get");if(!isOk(getR))return getR;const d=this.parseDraft(getR.ok,acct.ok);if(!isOk(d))return d;drafts.push(d.ok)}return ok({drafts,nextPageToken:parsed.ok.nextPageToken})}parseDraft(o,account){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail drafts.get: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const id=rec["id"];if(typeof id!=="string"||id===""){return connectorError("internal","gmail drafts.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)")}const msg=this.parseMessage(rec["message"],account);if(!isOk(msg))return msg;return ok({...rec,account,id,message:msg.ok})}labels(grant){const acct=this.account(grant);if(!isOk(acct))return acct;const r=this.get(grant,"/users/me/labels","labels.list");if(!isOk(r))return r;const o=r.ok;if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail labels.list: response is not an object \u2014 REST-surface drift (FM-19)")}const raw=o.labels;if(raw===void 0)return ok([]);if(!Array.isArray(raw)){return connectorError("internal","gmail labels.list: `labels` is not an array \u2014 REST-surface drift (FM-19)")}const out=[];for(const l of raw){const id=l?.id;const name=l.name;if(typeof id!=="string"||id===""){return connectorError("internal","gmail labels.list: a label is missing a string `id` \u2014 REST-surface drift (FM-19)")}if(typeof name!=="string"){return connectorError("internal",`gmail labels.list: label '${id}' is missing a string \`name\` \u2014 REST-surface drift (FM-19)`)}out.push({...l,account:acct.ok})}return ok(out)}parseHistoryDeletions(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail history.list: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const rows=[];if(rec.history!==void 0){if(!Array.isArray(rec.history)){return connectorError("internal","gmail history.list: `history` is not an array \u2014 REST-surface drift (FM-19)")}for(const record of rec.history){const recordId=record?.id;if(typeof recordId!=="string"||recordId===""){return connectorError("internal","gmail history.list: a history record is missing string `id` \u2014 REST-surface drift (FM-19)")}const deleted=record?.messagesDeleted;if(deleted===void 0)continue;if(!Array.isArray(deleted)){return connectorError("internal","gmail history.list: `messagesDeleted` is not an array \u2014 REST-surface drift (FM-19)")}for(const row of deleted){const id=row?.message?.id;if(typeof id!=="string"||id===""){return connectorError("internal","gmail history.list: a messagesDeleted row is missing message.id \u2014 REST-surface drift (FM-19)")}rows.push({id,atHistoryId:recordId})}}}const next=rec.nextPageToken;if(next!==void 0&&typeof next!=="string"){return connectorError("internal","gmail history.list: nextPageToken is not a string \u2014 REST-surface drift (FM-19)")}return ok({rows,nextPageToken:typeof next==="string"&&next!==""?next:null})}messageDeletions(grant,sinceHistoryId){const acct=this.account(grant);if(!isOk(acct))return acct;const out=[];let pageToken=null;let pages=0;for(;;){const q=`startHistoryId=${encodeURIComponent(sinceHistoryId)}&historyTypes=messageDeleted${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const r=this.get(grant,`/users/me/history?${q}`,"history.list");if(!isOk(r))return r;const parsed=this.parseHistoryDeletions(r.ok);if(!isOk(parsed))return parsed;for(const row of parsed.ok.rows)out.push({account:acct.ok,id:row.id,atHistoryId:row.atHistoryId});if(out.length>GMAIL_DELETIONS_CAP){return connectorError("resource_exhausted",`gmail history.list deletions exceeded the ${GMAIL_DELETIONS_CAP} cap \u2014 refusing a partial sweep (loud, never a silent truncation)`,"non-retryable")}if(++pages>GMAIL_HISTORY_MAX_PAGES){return connectorError("resource_exhausted",`gmail history.list pagination exceeded ${GMAIL_HISTORY_MAX_PAGES} pages \u2014 pageToken-cycle drift (FM-19)`,"non-retryable")}if(parsed.ok.nextPageToken===null)return ok(out);pageToken=parsed.ok.nextPageToken}}}return{GMAIL_AUDIT_RECENT_QUERY,GMAIL_MESSAGE_PULL_CAP,GMAIL_CENSUS_MAX_PAGES,GMAIL_THREAD_PAGE_BYTE_BUDGET,GMAIL_DELETIONS_CAP,GMAIL_HISTORY_MAX_PAGES,GMAIL_ATTACHMENT_CONTENT_CAP,GMAIL_ATTACHMENT_TRANSPORT_SAFE_BYTES,GMAIL_API_BASE,GMAIL_BATCH_URL,GMAIL_BATCH_CHUNK_SIZE,GMAIL_WAN_GATE,refuseWanTransport,buildAttachmentContent,GMAIL_METADATA_HEADERS,GMAIL_STARTER_MESSAGE_LIMIT,GMAIL_STARTER_CONTENT_BYTES,capStarterContent,HttpGmailSource}}
|
|
8
|
+
`;return{url:GMAIL_BATCH_URL,headers:{...headers,"Content-Type":`multipart/mixed; boundary=${boundary}`},method:"POST",body}}hint(grant,ids,headersParam){if(this.prefetch===void 0||ids.length===0)return;const hdrs=this.authHeaders(grant);if(!isOk(hdrs))return;for(const chunk of chunkIds(ids,GMAIL_BATCH_CHUNK_SIZE)){this.prefetch([this.batchRequest(chunk,headersParam,hdrs.ok)])}}hintGets(grant,paths){if(this.prefetch===void 0||paths.length===0)return;const headers=this.authHeaders(grant);if(!isOk(headers))return;this.prefetch(paths.map(path=>({url:`${GMAIL_API_BASE}${path}`,headers:headers.ok,method:"GET"})))}static create(opts){return new HttpGmailSource(opts.transport??refuseWanTransport,opts.authHeaders,opts.cap??GMAIL_MESSAGE_PULL_CAP,opts.pageSize??100,opts.attachmentCap??GMAIL_ATTACHMENT_CONTENT_CAP,opts.query!==void 0&&opts.query.trim()!==""?opts.query.trim():void 0,opts.selectedMessageIds===void 0?void 0:[...new Set(opts.selectedMessageIds.filter(id=>typeof id==="string"&&id!==""))],opts.messageFormat??"full",opts.messageLimit??null,opts.starterContentBytes??null,opts.fetchAttachments??true,opts.prefetch,opts.threadPageByteBudget??GMAIL_THREAD_PAGE_BYTE_BUDGET)}get(grant,path,what){const hdrs=this.authHeaders(grant);if(!isOk(hdrs))return hdrs;const res=this.transport(`${GMAIL_API_BASE}${path}`,hdrs.ok);if(!res.ok){if(res.structuredError!==void 0)return{err:res.structuredError};if(res.error===GMAIL_WAN_GATE)return gateRefusal("gmail live WAN transport",GMAIL_WAN_GATE);return connectorError("unavailable",`gmail ${what} transport failure: ${res.error} \u2014 NEVER an empty success (FM-21)`,"transient")}return this.routeStatus(res.status,res.body,what)}routeStatus(status,body,what){if(status===200){try{return ok(JSON.parse(body))}catch{return connectorError("internal",`gmail ${what}: 200 body is not JSON \u2014 REST-surface drift (FM-19)`)}}return{err:webStatusErrorV1(status,{provider:"gmail",what,bodyOverride:googleStatusOverrideV1(body),...googleErrorReasonV1(body)===void 0?{}:{detail:googleErrorReasonV1(body)}})}}batchGetMessages(grant,ids,headersParam){const auth=this.authHeaders(grant);if(!isOk(auth))return auth;const request=this.batchRequest(ids,headersParam,auth.ok);const response=this.transport(request.url,request.headers,{method:request.method,body:request.body});if(!response.ok){if(response.structuredError!==void 0)return{err:response.structuredError};if(response.error===GMAIL_WAN_GATE)return gateRefusal("gmail live WAN transport",GMAIL_WAN_GATE);return connectorError("unavailable",`gmail messages.batchGet transport failure: ${response.error} \u2014 NEVER an empty success (FM-21)`,"transient")}if(response.status!==200)return this.routeStatus(response.status,response.body,"messages.batchGet");const parts2=splitMultipartMixed(response.body);if(parts2===null)return connectorError("internal","gmail messages.batchGet: malformed multipart response \u2014 REST-surface drift (FM-19)");const out=new Map;const throttled=[];for(const part of parts2){if(part.contentId===null)return connectorError("internal","gmail messages.batchGet: missing Content-ID \u2014 cannot correlate response (FM-19)");const contentId=part.contentId.replace(/^response-/,"");const id=ids.find(candidate=>contentId===candidate||contentId.endsWith(`/${candidate}`));if(id===void 0||out.has(id)||throttled.includes(id))return connectorError("internal",`gmail messages.batchGet: unexpected or duplicate Content-ID '${part.contentId}' (FM-19)`);const routed=this.routeStatus(part.status,part.body,"messages.get");if(!isOk(routed)){if("err"in routed&&routed.err.retryability==="throttling"){throttled.push(id);continue}return routed}out.set(id,routed.ok)}for(const id of throttled){const single=this.get(grant,`/users/me/messages/${encodeURIComponent(id)}?format=${this.messageFormat}${headersParam}`,"messages.get");if(!isOk(single))return single;out.set(id,single.ok)}for(const id of ids){if(!out.has(id))return connectorError("internal",`gmail messages.batchGet: response omitted message '${id}' (FM-19)`)}return ok(out)}account(grant){if(this.resolvedAccount!==null)return ok(this.resolvedAccount);const p=this.getProfile(grant);if(!isOk(p))return p;this.resolvedAccount=p.ok.emailAddress;return ok(this.resolvedAccount)}getProfile(grant){const r=this.get(grant,"/users/me/profile","getProfile");if(!isOk(r))return r;const o=r.ok;if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail getProfile: response is not an object \u2014 REST-surface drift (FM-19)")}const email=o.emailAddress;if(typeof email!=="string"||email===""){return connectorError("internal","gmail getProfile: emailAddress missing \u2014 cannot source the account epoch (REST-surface drift, FM-19)")}return ok(o)}enumerateAll(grant,path,listKey,what){const out=[];let pageToken=null;const seenPageTokens=new Set;let pages=0;for(;;){if(pages>=GMAIL_CENSUS_MAX_PAGES){return connectorError("resource_exhausted",`gmail ${what} census exceeded the ${GMAIL_CENSUS_MAX_PAGES}-page safety cap \u2014 refusing a partial census`,"non-retryable")}pages+=1;const sep=path.includes("?")?"&":"?";const searchable=path.includes("/messages")||path.includes("/threads");const q=`${sep}maxResults=500${searchable&&this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const r=this.get(grant,`${path}${q}`,what);if(!isOk(r))return r;const parsed=this.parseListIds(r.ok,listKey,what);if(!isOk(parsed))return parsed;for(const id of parsed.ok.ids)out.push(id);if(out.length>this.cap){return connectorError("resource_exhausted",`gmail ${what} enumeration exceeded the ${this.cap} cap \u2014 refusing a partial census (loud, never a silent truncation that would misreconcile FM-18); narrow the sync window`,"non-retryable")}if(parsed.ok.nextPageToken===null)return ok(out);if(seenPageTokens.has(parsed.ok.nextPageToken)){return connectorError("data_loss",`gmail ${what} census repeated a provider page token \u2014 refusing a partial census`,"non-retryable")}seenPageTokens.add(parsed.ok.nextPageToken);pageToken=parsed.ok.nextPageToken}}parseListIds(o,listKey,what){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal",`gmail ${what}: response is not an object \u2014 REST-surface drift (FM-19)`)}const raw=o[listKey];const ids=[];if(raw!==void 0){if(!Array.isArray(raw)){return connectorError("internal",`gmail ${what}: \`${listKey}\` is not an array \u2014 REST-surface drift (FM-19)`)}for(const row of raw){const id=row?.id;if(typeof id!=="string"||id===""){return connectorError("internal",`gmail ${what}: a row is missing a string \`id\` \u2014 REST-surface drift (FM-19)`)}ids.push(id)}}const next=o.nextPageToken;if(next!==void 0&&typeof next!=="string"){return connectorError("internal",`gmail ${what}: nextPageToken is not a string \u2014 REST-surface drift (FM-19)`)}return ok({ids,nextPageToken:typeof next==="string"&&next!==""?next:null})}parseIdList(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail messages.list: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const raw=rec.messages;const ids=[];if(raw!==void 0){if(!Array.isArray(raw)){return connectorError("internal","gmail messages.list: `messages` is not an array \u2014 REST-surface drift (FM-19)")}for(const m of raw){const id=m?.id;if(typeof id!=="string"||id===""){return connectorError("internal","gmail messages.list: a row is missing a string `id` \u2014 REST-surface drift (FM-19)")}const threadId=m.threadId;ids.push({id,...typeof threadId==="string"?{threadId}:{}})}}const next=rec.nextPageToken;if(next!==void 0&&typeof next!=="string"){return connectorError("internal","gmail messages.list: nextPageToken is not a string \u2014 REST-surface drift (FM-19)")}return ok({ids,nextPageToken:typeof next==="string"&&next!==""?next:null})}census(grant){const msgs=this.enumerateAll(grant,"/users/me/messages?includeSpamTrash=true","messages","messages.list");if(!isOk(msgs))return msgs;const labelsR=this.labels(grant);if(!isOk(labelsR))return labelsR;const threads=this.enumerateAll(grant,"/users/me/threads?includeSpamTrash=true","threads","threads.list");if(!isOk(threads))return threads;const drafts=this.enumerateAll(grant,"/users/me/drafts","drafts","drafts.list");if(!isOk(drafts))return drafts;return ok({messages:{total:msgs.ok.length},labels:{total:labelsR.ok.length},threads:{total:threads.ok.length},drafts:{total:drafts.ok.length}})}messagesPage(grant,pageToken,maxMessages){const acct=this.account(grant);if(!isOk(acct))return acct;if(this.selectedMessageIds!==void 0){if(pageToken!==null){return connectorError("invalid_argument","gmail exact-id source has one bounded page","non-retryable")}const ids2=maxMessages===void 0?[...this.selectedMessageIds]:this.selectedMessageIds.slice(0,maxMessages);const headersParam2=this.messageFormat==="metadata"?GMAIL_METADATA_HEADERS.map(h=>`&metadataHeaders=${h}`).join(""):"";this.hint(grant,ids2,headersParam2);const hydrated2=this.hydrateMessages(grant,acct.ok,ids2,true);if(!isOk(hydrated2))return hydrated2;return ok({messages:this.starterContentBytes===null?hydrated2.ok.messages:capStarterContent(hydrated2.ok.messages,this.starterContentBytes),attachments:[],nextPageToken:null})}if(this.messageLimit!==null&&pageToken!==null){return connectorError("invalid_argument","gmail starter source has one bounded page","non-retryable")}const wanted=this.messageLimit===null?maxMessages:maxMessages===void 0?this.messageLimit:Math.min(maxMessages,this.messageLimit);const pageSize=wanted===void 0?this.pageSize:Math.min(this.pageSize,wanted);const q=`maxResults=${pageSize}&includeSpamTrash=true${this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const listR=this.get(grant,`/users/me/messages?${q}`,"messages.list");if(!isOk(listR))return listR;const parsed=this.parseIdList(listR.ok);if(!isOk(parsed))return parsed;if(wanted!==void 0&&parsed.ok.ids.length>wanted){return connectorError("data_loss",`gmail messages.list returned ${parsed.ok.ids.length} IDs for a requested page size of ${wanted}`,"non-retryable")}const ids=(wanted===void 0?parsed.ok.ids:parsed.ok.ids.slice(0,wanted)).map(({id})=>id);const headersParam=this.messageFormat==="metadata"?GMAIL_METADATA_HEADERS.map(h=>`&metadataHeaders=${h}`).join(""):"";const messages=[];const attachments=[];this.hint(grant,ids,headersParam);const hydrated=this.hydrateMessages(grant,acct.ok,ids,false);if(!isOk(hydrated))return hydrated;messages.push(...hydrated.ok.messages);attachments.push(...hydrated.ok.attachments);return ok({messages:this.starterContentBytes===null?messages:capStarterContent(messages,this.starterContentBytes),attachments,nextPageToken:this.messageLimit===null?parsed.ok.nextPageToken:null})}messageCensus(grant){const ids=this.enumerateAll(grant,`/users/me/messages?includeSpamTrash=true${this.query===void 0?"":`&q=${encodeURIComponent(this.query)}`}`,"messages","messages.list");if(!isOk(ids))return ids;return ok(ids.ok.length)}hydrateMessages(grant,account,ids,skipGone){const headersParam=this.messageFormat==="metadata"?GMAIL_METADATA_HEADERS.map(h=>`&metadataHeaders=${h}`).join(""):"";const messages=[];const attachments=[];const keep=raw=>{const m=this.parseMessage(raw,account);if(!isOk(m))return m;messages.push(this.messageFormat==="metadata"?{...m.ok,starterContentOmitted:"fields-metadata"}:m.ok);if(this.messageFormat==="full"&&this.messageLimit===null&&this.fetchAttachments){const att=this.attachmentsFor(grant,m.ok);if(!isOk(att))return att;for(const a of att.ok)attachments.push(a)}return ok(true)};if(!skipGone){for(const chunk of chunkIds([...ids],GMAIL_BATCH_CHUNK_SIZE)){const batch=this.batchGetMessages(grant,chunk,headersParam);if(!isOk(batch))return batch;for(const id of chunk){const kept=keep(batch.ok.get(id));if(!isOk(kept))return kept}}return ok({messages,attachments})}for(const id of ids){const getR=this.get(grant,`/users/me/messages/${encodeURIComponent(id)}?format=${this.messageFormat}${headersParam}`,"messages.get");if(!isOk(getR)){if(skipGone&&getR.err.code==="not_found")continue;return getR}const m=this.parseMessage(getR.ok,account);if(!isOk(m))return m;messages.push(this.messageFormat==="metadata"?{...m.ok,starterContentOmitted:"fields-metadata"}:m.ok);if(this.messageFormat==="full"&&this.messageLimit===null&&this.fetchAttachments){const att=this.attachmentsFor(grant,m.ok);if(!isOk(att))return att;for(const a of att.ok)attachments.push(a)}}return ok({messages,attachments})}listMessageIdsPage(grant,scope,pageToken,maxPages){const base=this.query===void 0?scope==="recent"?GMAIL_AUDIT_RECENT_QUERY:void 0:scope==="recent"?`(${this.query}) ${GMAIL_AUDIT_RECENT_QUERY}`:this.query;const ids=[];let token=pageToken;for(let pages=0;pages<Math.max(1,maxPages);pages++){const r=this.get(grant,`/users/me/messages?includeSpamTrash=true&maxResults=500${base===void 0?"":`&q=${encodeURIComponent(base)}`}${token!==null?`&pageToken=${encodeURIComponent(token)}`:""}`,"messages.list");if(!isOk(r))return r;const parsed=this.parseListIds(r.ok,"messages","messages.list");if(!isOk(parsed))return parsed;for(const id of parsed.ok.ids)ids.push(id);token=parsed.ok.nextPageToken;if(token===null)break}return ok({ids,nextPageToken:token})}messageEvidence(grant,id){const hdrs=this.authHeaders(grant);if(!isOk(hdrs))return hdrs;const res=this.transport(`${GMAIL_API_BASE}/users/me/messages/${encodeURIComponent(id)}?format=minimal`,hdrs.ok);if(!res.ok){if(res.structuredError!==void 0)return{err:res.structuredError};if(res.error===GMAIL_WAN_GATE)return gateRefusal("gmail live WAN transport",GMAIL_WAN_GATE);return connectorError("unavailable",`gmail messages.get (audit evidence) transport failure: ${res.error} \u2014 never "not-found" (FM-21)`,"transient")}const answer=readByIdAnswerV1(res.status,{provider:"gmail",what:"messages.get (audit evidence)",bodyOverride:googleStatusOverrideV1(res.body),...googleErrorReasonV1(res.body)===void 0?{}:{detail:googleErrorReasonV1(res.body)}});if("err"in answer)return answer;if(answer.ok==="not-found")return ok("not-found");let body;try{body=JSON.parse(res.body)}catch{return connectorError("internal","gmail messages.get (audit evidence): 200 body is not JSON \u2014 REST-surface drift (FM-19)")}const labels=body!==null&&typeof body==="object"?body.labelIds:void 0;return ok(Array.isArray(labels)&&labels.includes("TRASH")?"trashed":"present")}messagesByIds(grant,ids){const acct=this.account(grant);if(!isOk(acct))return acct;return this.hydrateMessages(grant,acct.ok,ids,true)}messageChanges(grant,sinceHistoryId,maxMessages){const acct=this.account(grant);if(!isOk(acct))return acct;const changed=[];const seen=new Set;const deletions=[];const deletedIds=new Set;let pageToken=null;let pages=0;let lastRecord=null;let mailboxHistoryId=null;let more=false;walk:for(;;){const types=["messageAdded","labelAdded","labelRemoved","messageDeleted"].map(t=>`&historyTypes=${t}`).join("");const q=`startHistoryId=${encodeURIComponent(sinceHistoryId)}${types}&maxResults=500${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const r=this.get(grant,`/users/me/history?${q}`,"history.list");if(!isOk(r))return r;const parsed=this.parseHistoryChanges(r.ok);if(!isOk(parsed))return parsed;mailboxHistoryId=parsed.ok.historyId??mailboxHistoryId;for(const record of parsed.ok.records){const fresh=record.changed.filter(id=>!seen.has(id));if(changed.length>0&&changed.length+fresh.length>maxMessages){more=true;break walk}for(const id of fresh){seen.add(id);changed.push(id)}for(const id of record.deleted){deletedIds.add(id);deletions.push({account:acct.ok,id,atHistoryId:record.id})}lastRecord=record.id}if(++pages>GMAIL_HISTORY_MAX_PAGES){return connectorError("resource_exhausted",`gmail history.list pagination exceeded ${GMAIL_HISTORY_MAX_PAGES} pages \u2014 pageToken-cycle drift (FM-19)`,"non-retryable")}if(parsed.ok.nextPageToken===null)break;pageToken=parsed.ok.nextPageToken}const hydrated=this.hydrateMessages(grant,acct.ok,changed.filter(id=>!deletedIds.has(id)),true);if(!isOk(hydrated))return hydrated;return ok({...hydrated.ok,deletions,historyId:more?lastRecord:mailboxHistoryId??lastRecord,more})}parseHistoryChanges(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail history.list: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const records=[];if(rec.history!==void 0){if(!Array.isArray(rec.history))return connectorError("internal","gmail history.list: `history` is not an array \u2014 REST-surface drift (FM-19)");for(const record of rec.history){const id=record?.id;if(typeof id!=="string"||id==="")return connectorError("internal","gmail history.list: a history record is missing string `id` \u2014 REST-surface drift (FM-19)");const idsOf=key=>{const rows=record[key];if(rows===void 0)return ok([]);if(!Array.isArray(rows))return connectorError("internal",`gmail history.list: \`${key}\` is not an array \u2014 REST-surface drift (FM-19)`);const out=[];for(const row of rows){const mid=row?.message?.id;if(typeof mid!=="string"||mid==="")return connectorError("internal",`gmail history.list: a ${key} row is missing message.id \u2014 REST-surface drift (FM-19)`);out.push(mid)}return ok(out)};const added=idsOf("messagesAdded");const labelled=idsOf("labelsAdded");const unlabelled=idsOf("labelsRemoved");const deleted=idsOf("messagesDeleted");for(const part of[added,labelled,unlabelled,deleted])if(!isOk(part))return part;records.push({id,changed:[...added.ok,...labelled.ok,...unlabelled.ok],deleted:deleted.ok})}}const next=rec.nextPageToken;if(next!==void 0&&typeof next!=="string")return connectorError("internal","gmail history.list: nextPageToken is not a string \u2014 REST-surface drift (FM-19)");const hid=rec.historyId;return ok({records,nextPageToken:typeof next==="string"&&next!==""?next:null,historyId:typeof hid==="string"&&hid!==""?hid:null})}attachmentsFor(grant,m){const descriptors=this.collectAttachments(m.payload);const out=[];for(const d of descriptors){const base={account:m.account,messageId:m.id,...m.threadId!==void 0?{threadId:m.threadId}:{},partId:d.partId,attachmentId:d.attachmentId,filename:d.filename,mimeType:d.mimeType,size:d.size,...m.internalDate!==void 0?{internalDate:m.internalDate}:{}};if(d.size>this.attachmentCap||d.size>GMAIL_ATTACHMENT_TRANSPORT_SAFE_BYTES){out.push({...base,contentOmitted:"over-cap"});continue}const bodyR=this.get(grant,`/users/me/messages/${encodeURIComponent(m.id)}/attachments/${encodeURIComponent(d.attachmentId)}`,"messages.attachments.get");if(!isOk(bodyR))return bodyR;const parsed=this.parseAttachmentBody(bodyR.ok);if(!isOk(parsed))return parsed;const bytes=Buffer.from(parsed.ok.data,"base64url");const content=buildAttachmentContent(d.mimeType,bytes,this.attachmentCap);out.push({...base,size:bytes.length,...content})}return ok(out)}collectAttachments(payload){const out=[];const walk=(part,path)=>{const attId=part.body?.attachmentId;if(typeof attId==="string"&&attId!==""){const partId=typeof part.partId==="string"&&part.partId!==""?part.partId:path;out.push({partId,attachmentId:attId,filename:typeof part.filename==="string"?part.filename:"",mimeType:typeof part.mimeType==="string"?part.mimeType:"application/octet-stream",size:typeof part.body?.size==="number"?part.body.size:0})}const parts2=part.parts??[];for(let i=0;i<parts2.length;i++)walk(parts2[i],path===""?String(i):`${path}.${i}`)};if(payload!==void 0)walk(payload,"");return out}parseAttachmentBody(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail attachments.get: response is not an object \u2014 REST-surface drift (FM-19)")}const data=o.data;if(typeof data!=="string"){return connectorError("internal","gmail attachments.get: missing string `data` (the attachment bytes) \u2014 REST-surface drift (FM-19)")}const size=o.size;return ok({size:typeof size==="number"?size:0,data})}parseMessage(o,account){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail messages.get: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const id=rec["id"];if(typeof id!=="string"||id===""){return connectorError("internal","gmail messages.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)")}const historyId=rec["historyId"];if(typeof historyId!=="string"||historyId===""){return connectorError("internal",`gmail messages.get '${id}': missing string \`historyId\` (the upstream-version rev token) \u2014 REST-surface drift (FM-19)`)}return ok({...rec,account})}threadsByIds(grant,ids){const acct=this.account(grant);if(!isOk(acct))return acct;const threads=[];for(const id of ids){const getR=this.get(grant,`/users/me/threads/${encodeURIComponent(id)}?format=metadata`,"threads.get");if(!isOk(getR)){if(getR.err.code==="not_found")continue;return getR}const t=this.parseThread(getR.ok,acct.ok);if(!isOk(t))return t;threads.push(t.ok)}return ok({threads})}threadsPage(grant,pageToken){let pageIds;let consumed;let nextProviderPageToken;if(pageToken!==null&&typeof pageToken!=="string"){const continuation=this.validateThreadContinuation(pageToken);if(!isOk(continuation))return continuation;pageIds=continuation.ok.ids;consumed=continuation.ok.consumed;nextProviderPageToken=continuation.ok.nextProviderPageToken}else{consumed=0;const providerPageToken=pageToken;const q=`maxResults=${this.pageSize}&includeSpamTrash=true${this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${providerPageToken!==null?`&pageToken=${encodeURIComponent(providerPageToken)}`:""}`;const listR=this.get(grant,`/users/me/threads?${q}`,"threads.list");if(!isOk(listR))return listR;const parsed=this.parseListIds(listR.ok,"threads","threads.list");if(!isOk(parsed))return parsed;pageIds=parsed.ok.ids;nextProviderPageToken=parsed.ok.nextPageToken}const acct=this.account(grant);if(!isOk(acct))return acct;const threads=[];let pageBytes=0;let largestThreadBytes=0;for(let i=consumed;i<pageIds.length;i++){const id=pageIds[i];const getR=this.get(grant,`/users/me/threads/${encodeURIComponent(id)}?format=metadata`,"threads.get");if(!isOk(getR))return getR;const t=this.parseThread(getR.ok,acct.ok);if(!isOk(t))return t;threads.push(t.ok);const threadBytes=new TextEncoder().encode(JSON.stringify(getR.ok)).byteLength;pageBytes+=threadBytes;largestThreadBytes=Math.max(largestThreadBytes,threadBytes);const nextConsumed=i+1;if(pageBytes+largestThreadBytes>this.threadPageByteBudget&&nextConsumed<pageIds.length){return ok({threads,nextPageToken:{kind:"gmail-thread-page-v1",ids:[...pageIds],consumed:nextConsumed,nextProviderPageToken}})}}return ok({threads,nextPageToken:nextProviderPageToken})}validateThreadContinuation(value){if(value===null||typeof value!=="object"||Array.isArray(value)){return connectorError("invalid_argument","gmail threads continuation must be a stable page-identity object")}const row=value;if(row["kind"]!=="gmail-thread-page-v1"){return connectorError("invalid_argument","gmail threads continuation has an unknown version")}const ids=row["ids"];if(!Array.isArray(ids)||ids.length===0||ids.some(id=>typeof id!=="string"||id==="")){return connectorError("invalid_argument","gmail threads continuation ids must be a non-empty provider-id page")}const consumed=row["consumed"];if(!Number.isSafeInteger(consumed)||consumed<=0||consumed>=ids.length){return connectorError("invalid_argument",`gmail threads continuation boundary '${String(consumed)}' is outside its ${ids.length}-id stable page`)}const nextProviderPageToken=row["nextProviderPageToken"];if(nextProviderPageToken!==null&&typeof nextProviderPageToken!=="string"){return connectorError("invalid_argument","gmail threads continuation next provider token must be an opaque string or null")}return ok({kind:"gmail-thread-page-v1",ids:[...ids],consumed,nextProviderPageToken})}parseThread(o,account){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail threads.get: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const id=rec["id"];if(typeof id!=="string"||id===""){return connectorError("internal","gmail threads.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)")}const historyId=rec["historyId"];if(typeof historyId!=="string"||historyId===""){return connectorError("internal",`gmail threads.get '${id}': missing string \`historyId\` (the upstream-version rev token) \u2014 REST-surface drift (FM-19)`)}let messages;const rawMsgs=rec["messages"];if(rawMsgs!==void 0){if(!Array.isArray(rawMsgs)){return connectorError("internal",`gmail threads.get '${id}': \`messages\` is not an array \u2014 REST-surface drift (FM-19)`)}messages=[];for(const rm of rawMsgs){const pm=this.parseMessage(rm,account);if(!isOk(pm))return pm;messages.push(pm.ok)}}return ok({...rec,account,...messages!==void 0?{messages}:{}})}draftsPage(grant,pageToken){const acct=this.account(grant);if(!isOk(acct))return acct;const q=`maxResults=${this.pageSize}${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const listR=this.get(grant,`/users/me/drafts?${q}`,"drafts.list");if(!isOk(listR))return listR;const parsed=this.parseListIds(listR.ok,"drafts","drafts.list");if(!isOk(parsed))return parsed;const drafts=[];this.hintGets(grant,parsed.ok.ids.map(id=>`/users/me/drafts/${encodeURIComponent(id)}?format=full`));for(const id of parsed.ok.ids){const getR=this.get(grant,`/users/me/drafts/${encodeURIComponent(id)}?format=full`,"drafts.get");if(!isOk(getR))return getR;const d=this.parseDraft(getR.ok,acct.ok);if(!isOk(d))return d;drafts.push(d.ok)}return ok({drafts,nextPageToken:parsed.ok.nextPageToken})}parseDraft(o,account){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail drafts.get: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const id=rec["id"];if(typeof id!=="string"||id===""){return connectorError("internal","gmail drafts.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)")}const msg=this.parseMessage(rec["message"],account);if(!isOk(msg))return msg;return ok({...rec,account,id,message:msg.ok})}labels(grant){const acct=this.account(grant);if(!isOk(acct))return acct;const r=this.get(grant,"/users/me/labels","labels.list");if(!isOk(r))return r;const o=r.ok;if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail labels.list: response is not an object \u2014 REST-surface drift (FM-19)")}const raw=o.labels;if(raw===void 0)return ok([]);if(!Array.isArray(raw)){return connectorError("internal","gmail labels.list: `labels` is not an array \u2014 REST-surface drift (FM-19)")}const out=[];for(const l of raw){const id=l?.id;const name=l.name;if(typeof id!=="string"||id===""){return connectorError("internal","gmail labels.list: a label is missing a string `id` \u2014 REST-surface drift (FM-19)")}if(typeof name!=="string"){return connectorError("internal",`gmail labels.list: label '${id}' is missing a string \`name\` \u2014 REST-surface drift (FM-19)`)}out.push({...l,account:acct.ok})}return ok(out)}parseHistoryDeletions(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail history.list: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const rows=[];if(rec.history!==void 0){if(!Array.isArray(rec.history)){return connectorError("internal","gmail history.list: `history` is not an array \u2014 REST-surface drift (FM-19)")}for(const record of rec.history){const recordId=record?.id;if(typeof recordId!=="string"||recordId===""){return connectorError("internal","gmail history.list: a history record is missing string `id` \u2014 REST-surface drift (FM-19)")}const deleted=record?.messagesDeleted;if(deleted===void 0)continue;if(!Array.isArray(deleted)){return connectorError("internal","gmail history.list: `messagesDeleted` is not an array \u2014 REST-surface drift (FM-19)")}for(const row of deleted){const id=row?.message?.id;if(typeof id!=="string"||id===""){return connectorError("internal","gmail history.list: a messagesDeleted row is missing message.id \u2014 REST-surface drift (FM-19)")}rows.push({id,atHistoryId:recordId})}}}const next=rec.nextPageToken;if(next!==void 0&&typeof next!=="string"){return connectorError("internal","gmail history.list: nextPageToken is not a string \u2014 REST-surface drift (FM-19)")}return ok({rows,nextPageToken:typeof next==="string"&&next!==""?next:null})}messageDeletions(grant,sinceHistoryId){const acct=this.account(grant);if(!isOk(acct))return acct;const out=[];let pageToken=null;let pages=0;for(;;){const q=`startHistoryId=${encodeURIComponent(sinceHistoryId)}&historyTypes=messageDeleted${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const r=this.get(grant,`/users/me/history?${q}`,"history.list");if(!isOk(r))return r;const parsed=this.parseHistoryDeletions(r.ok);if(!isOk(parsed))return parsed;for(const row of parsed.ok.rows)out.push({account:acct.ok,id:row.id,atHistoryId:row.atHistoryId});if(out.length>GMAIL_DELETIONS_CAP){return connectorError("resource_exhausted",`gmail history.list deletions exceeded the ${GMAIL_DELETIONS_CAP} cap \u2014 refusing a partial sweep (loud, never a silent truncation)`,"non-retryable")}if(++pages>GMAIL_HISTORY_MAX_PAGES){return connectorError("resource_exhausted",`gmail history.list pagination exceeded ${GMAIL_HISTORY_MAX_PAGES} pages \u2014 pageToken-cycle drift (FM-19)`,"non-retryable")}if(parsed.ok.nextPageToken===null)return ok(out);pageToken=parsed.ok.nextPageToken}}}return{GMAIL_AUDIT_RECENT_QUERY,GMAIL_MESSAGE_PULL_CAP,GMAIL_CENSUS_MAX_PAGES,GMAIL_THREAD_PAGE_BYTE_BUDGET,GMAIL_DELETIONS_CAP,GMAIL_HISTORY_MAX_PAGES,GMAIL_ATTACHMENT_CONTENT_CAP,GMAIL_ATTACHMENT_TRANSPORT_SAFE_BYTES,GMAIL_API_BASE,GMAIL_BATCH_URL,GMAIL_BATCH_CHUNK_SIZE,GMAIL_WAN_GATE,refuseWanTransport,buildAttachmentContent,GMAIL_METADATA_HEADERS,GMAIL_STARTER_MESSAGE_LIMIT,GMAIL_STARTER_CONTENT_BYTES,capStarterContent,HttpGmailSource}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{validateRead,readResult,connectionState}from"@zortexhq/plugin-connector-core/api";import{createGmailActions}from"./actions.js";import{createBrokeredGmail}from"./brokered.js";export const name="zortex-gmail-original-provider",inject=["zortexConnectorHub","zortexOriginalAuthoring","zortexGoogleAuth","zortexVaultStore"];export function createGmailProvider({parts,provider=parts.createProviderRead(),auth,vault,files}){const info={source:"gmail",label:"Gmail",group:"Connector / Google",auth:"oauth-browser"},stop=new AbortController,pending=new Set;let closed=false;const unavailable=()=>businessError("unavailable","Gmail source is inactive.","plugin");const mcp=vault.credential?createGmailActions(auth,vault,files):void 0;const service={info,...mcp?{actions:mcp.actions}:{},status:()=>connectionState(vault,info),connect:options=>auth.connect("gmail",options),job:id=>auth.job(id),cancelJob:id=>auth.cancelJob(id),async read(input,options={}){if(closed)return unavailable();const invalid=validateRead(input);if(invalid)return invalid;const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;if(signal.aborted)return businessError("aborted","Gmail selected read was cancelled.","connector");const selected=await vault.connection("gmail");if(!("ok"in selected))return selected;if(!selected.ok||selected.ok.state!=="connected")return businessError("unauthenticated","Connect Gmail before reading messages.","auth");if(typeof selected.ok.accountId!=="string"||!selected.ok.accountId.trim())return businessError("failed_precondition","Select a verified native account before reading.","auth");const account=selected.ok.accountId,grant={id:"0"+createHash("sha256").update(account).digest("hex").slice(0,25).toUpperCase(),source:"gmail",scopes:selected.ok.scopes,expiresAt:"2036-01-01T00:00:00.000Z"};const guard=()=>closed||signal.aborted;const talon={grant,execute:()=>Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Resident Gmail reads require asynchronous custody."}),async executeAsync(g,request){if(g.id!==grant.id||g.source!=="gmail")return Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Gmail custody belongs to another source grant."});if(guard())return Original.errResult({code:"aborted",layer:"connector",retryability:"non-retryable",message:"Gmail selected read was stopped."});const contentType=Object.entries(request.headers).find(([key])=>key.toLowerCase()==="content-type")?.[1];const response=await auth.requestRaw("gmail",request.url,{method:request.method,...request.body?{body:Buffer.from(request.body).toString("utf8")}:{},...contentType?{contentType}:{},signal});if(guard())return Original.errResult({code:"aborted",layer:"connector",retryability:"non-retryable",message:"Gmail custody response arrived after cancellation."});const current=await vault.connection("gmail");if(!("ok"in current))return"err"in current?current:Original.errResult({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:"Gmail connection could not be confirmed."});if(current.ok?.state!=="connected"||current.ok.accountId!==account)return Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Gmail account changed while a selected read was active."});return"ok"in response?Original.ok({status:response.ok.status,headers:response.ok.headers,body:new TextEncoder().encode(response.ok.body)}):"err"in response?response:Original.errResult({code:"data_loss",layer:"connector",retryability:"non-retryable",message:"Gmail custody returned unconfirmed empty content."})},close:()=>Original.ok(void 0)};const query=[input.query??"in:inbox",input.since?"after:"+Math.floor(Date.parse(input.since)/1e3):"",input.until?"before:"+Math.floor(Date.parse(input.until)/1e3):""].filter(Boolean).join(" ");const
|
|
1
|
+
import{createHash}from"node:crypto";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{validateRead,readResult,connectionState}from"@zortexhq/plugin-connector-core/api";import{createGmailActions}from"./actions.js";import{createBrokeredGmail}from"./brokered.js";export const name="zortex-gmail-original-provider",inject=["zortexConnectorHub","zortexOriginalAuthoring","zortexGoogleAuth","zortexVaultStore"];const GMAIL_CANDIDATE_LIMIT=20,GMAIL_TEXT_LIMIT=32e3;const object=value=>value!==null&&typeof value==="object"&&!Array.isArray(value)?value:void 0;function headers(raw){const payload=object(raw.payload),rows=payload?.headers;if(!Array.isArray(rows))return new Map;return new Map(rows.flatMap(row=>{const item=object(row),name2=item?.name,value=item?.value;return typeof name2==="string"&&typeof value==="string"?[[name2.toLowerCase(),value]]:[]}))}function bounded(value){return value.length<=GMAIL_TEXT_LIMIT?value:value.slice(0,GMAIL_TEXT_LIMIT)+"\n[truncated]"}function candidateIds(drafts,query,limit){const terms=(query??"").toLocaleLowerCase().match(/[\p{L}\p{N}._+-]{2,}/gu)?.filter(term=>!["after","before","newer_than","older_than","in","label","from","to","subject"].includes(term))??[];return drafts.map((entry,index)=>{const raw=object(entry.draft.payload),id=raw?.id,head=raw?headers(raw):new Map,subject=head.get("subject")??"",searchable=`${subject} ${head.get("from")??""} ${entry.draft.body??""}`.toLocaleLowerCase(),score=terms.reduce((sum,term)=>sum+(subject.toLocaleLowerCase().includes(term)?3:0)+(searchable.includes(term)?1:0),0);return{id:typeof id==="string"?id:void 0,index,score}}).filter(row=>row.id!==void 0).sort((a,b)=>b.score-a.score||a.index-b.index).slice(0,limit).map(row=>row.id)}function recordFrom(entry){const proto=entry.draft,raw=object(proto.payload)??{},head=headers(raw),labelIds=Array.isArray(raw.labelIds)?raw.labelIds.filter(label=>typeof label==="string"):[],safeFields={subject:head.get("subject")??""};for(const key of["from","to","cc","date"]){const value=head.get(key);if(value)safeFields[key]=value}if(typeof raw.threadId==="string")safeFields.threadId=raw.threadId;if(typeof raw.snippet==="string"&&raw.snippet)safeFields.snippet=bounded(raw.snippet);if(labelIds.length)safeFields.labelIds=labelIds;return{source:"gmail",sourceId:entry.sourceId,stream:entry.stream,kind:entry.kind,ts:proto.ts,body:bounded(proto.body??""),fields:safeFields}}export function createGmailProvider({parts,provider=parts.createProviderRead(),auth,vault,files}){const info={source:"gmail",label:"Gmail",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"delta",retention:"durable",resources:["messages"],limitations:[]}},stop=new AbortController,pending=new Set;let closed=false;const unavailable=()=>businessError("unavailable","Gmail source is inactive.","plugin");const mcp=vault.credential?createGmailActions(auth,vault,files):void 0;const service={info,...mcp?{actions:mcp.actions}:{},status:()=>connectionState(vault,info),connect:options=>auth.connect("gmail",options),job:id=>auth.job(id),cancelJob:id=>auth.cancelJob(id),async read(input,options={}){if(closed)return unavailable();const invalid=validateRead(input);if(invalid)return invalid;const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;if(signal.aborted)return businessError("aborted","Gmail selected read was cancelled.","connector");const selected=await vault.connection("gmail");if(!("ok"in selected))return selected;if(!selected.ok||selected.ok.state!=="connected")return businessError("unauthenticated","Connect Gmail before reading messages.","auth");if(typeof selected.ok.accountId!=="string"||!selected.ok.accountId.trim())return businessError("failed_precondition","Select a verified native account before reading.","auth");const account=selected.ok.accountId,grant={id:"0"+createHash("sha256").update(account).digest("hex").slice(0,25).toUpperCase(),source:"gmail",scopes:selected.ok.scopes,expiresAt:"2036-01-01T00:00:00.000Z"};const guard=()=>closed||signal.aborted;const talon={grant,execute:()=>Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Resident Gmail reads require asynchronous custody."}),async executeAsync(g,request){if(g.id!==grant.id||g.source!=="gmail")return Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Gmail custody belongs to another source grant."});if(guard())return Original.errResult({code:"aborted",layer:"connector",retryability:"non-retryable",message:"Gmail selected read was stopped."});const contentType=Object.entries(request.headers).find(([key])=>key.toLowerCase()==="content-type")?.[1];const response=await auth.requestRaw("gmail",request.url,{method:request.method,...request.body?{body:Buffer.from(request.body).toString("utf8")}:{},...contentType?{contentType}:{},signal});if(guard())return Original.errResult({code:"aborted",layer:"connector",retryability:"non-retryable",message:"Gmail custody response arrived after cancellation."});const current=await vault.connection("gmail");if(!("ok"in current))return"err"in current?current:Original.errResult({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:"Gmail connection could not be confirmed."});if(current.ok?.state!=="connected"||current.ok.accountId!==account)return Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Gmail account changed while a selected read was active."});return"ok"in response?Original.ok({status:response.ok.status,headers:response.ok.headers,body:new TextEncoder().encode(response.ok.body)}):"err"in response?response:Original.errResult({code:"data_loss",layer:"connector",retryability:"non-retryable",message:"Gmail custody returned unconfirmed empty content."})},close:()=>Original.ok(void 0)};const query=[input.query??"in:inbox",input.since?"after:"+Math.floor(Date.parse(input.since)/1e3):"",input.until?"before:"+Math.floor(Date.parse(input.until)/1e3):""].filter(Boolean).join(" "),requested=input.limit??1,candidateLimit=Math.min(GMAIL_CANDIDATE_LIMIT,Math.max(10,requested*3));const metadata=createBrokeredGmail(parts,provider,{talon,query,retrievalLimit:candidateLimit,messageFormat:"metadata"});if(!Original.isOk(metadata))return metadata;let ids=[],metadataRedactions=0;try{const page=await metadata.ok.connector.pullAsync(grant,null,{remainingItems:candidateLimit});if(!Original.isOk(page))return page;if(guard())return businessError("aborted","Gmail selected read was stopped.","connector");const prepared=parts.prepareBatch(metadata.ok.connector,metadata.ok.connector.manifest,page.ok.items,{phase:"snapshot",syncRun:Original.ulid()});if(!Original.isOk(prepared))return prepared;if(prepared.ok.leaks.length)return businessError("permission_denied","The Gmail metadata rail contained token-bearing content; no records were returned.","auth");metadataRedactions=prepared.ok.redactions.length;ids=candidateIds(prepared.ok.drafts,input.query,requested)}finally{metadata.ok.close()}if(ids.length===0)return readResult("gmail",[],metadataRedactions?["Gmail metadata fields containing token-shaped content were redacted."]:[]);const content=createBrokeredGmail(parts,provider,{talon,selectedMessageIds:ids,retrievalLimit:ids.length,messageFormat:"full"});if(!Original.isOk(content))return content;try{const page=await content.ok.connector.pullAsync(grant,null,{remainingItems:ids.length});if(!Original.isOk(page))return page;if(guard())return businessError("aborted","Gmail selected read was stopped.","connector");const prepared=parts.prepareBatch(content.ok.connector,content.ok.connector.manifest,page.ok.items,{phase:"snapshot",syncRun:Original.ulid()});if(!Original.isOk(prepared))return prepared;if(prepared.ok.leaks.length)return businessError("permission_denied","The Gmail content rail contained token-bearing content; no records were returned.","auth");const records=prepared.ok.drafts.map(recordFrom);const current=await vault.connection("gmail");if(!("ok"in current))return current;if(guard())return businessError("aborted","Gmail selected read was stopped.","connector");if(current.ok?.state!=="connected"||current.ok.account!==selected.ok.account||current.ok.accountId!==account||!selected.ok.scopes.every(scope=>current.ok.scopes.includes(scope)))return businessError("permission_denied","Gmail authorization changed while a selected read was active.","auth");const warnings=[];if(metadataRedactions||prepared.ok.redactions.length)warnings.push("Gmail fields containing token-shaped content were redacted.");if(records.length<ids.length)warnings.push("One or more Gmail candidates changed or disappeared before their bounded text was read.");return readResult("gmail",records,warnings)}finally{content.ok.close()}},async close(){closed=true;stop.abort();await mcp?.close();await Promise.allSettled([...pending])}};return{...service,read(input,options){if(closed)return Promise.resolve(unavailable());if(pending.size)return Promise.resolve(businessError("resource_exhausted","Gmail has an active selected read.","connector"));const task=service.read(input,options).finally(()=>pending.delete(task));pending.add(task);return task}}}export async function apply(ctx,config={}){const provider=createGmailProvider({parts:ctx.zortexOriginalAuthoring,auth:ctx.zortexGoogleAuth,vault:ctx.zortexVaultStore,files:config}),withdraw=ctx.zortexConnectorHub.register(provider);return async()=>{withdraw();await provider.close()}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DatabaseSync}from"node:sqlite";import{lstat,realpath}from"node:fs/promises";import{homedir}from"node:os";import{join,isAbsolute,resolve}from"node:path";import{pathToFileURL}from"node:url";import{randomUUID,createHash}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{captureLocalReadAuthority,checkLocalReadAuthority,validateRead,readResult,cache}from"@zortexhq/plugin-connector-core/api";import{historySnapshot}from"./snapshot.js";const SCOPES=["history.read"],PROFILE=/^(Default|Profile \d{1,8})$/u;const sourceValid=source=>source==="google-chrome"||source==="microsoft-edge";const text=(value,max=4096)=>typeof value==="string"&&!!value&&value===value.trim()&&value.length<=max&&!/[\u0000-\u001f\u007f-\u009f]/u.test(value);function plain(value,keys){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error("Invalid native browser selection.");for(const key of Reflect.ownKeys(value)){const descriptor=Object.getOwnPropertyDescriptor(value,key);if(typeof key!=="string"||!keys.includes(key)||!descriptor.enumerable||!("value"in descriptor))throw Error("Invalid native browser selection.")}}export function defaultHistoryRoot(source){const vendor=source==="google-chrome"?"Google/Chrome":"Microsoft/Edge";return process.platform==="win32"?join(process.env.LOCALAPPDATA??homedir(),vendor,"User Data"):process.platform==="darwin"?join(homedir(),"Library/Application Support",vendor):join(homedir(),".config",source==="google-chrome"?"google-chrome":"microsoft-edge")}export function historyReadAudience(source,canonicalRoot,profile){if(!sourceValid(source)||!text(canonicalRoot)||!isAbsolute(canonicalRoot)||resolve(canonicalRoot)!==canonicalRoot||!text(profile,64)||!PROFILE.test(profile))throw Error("A canonical browser root and explicit profile are required.");return`indra-local-history:${source}:${createHash("sha256").update(JSON.stringify([pathToFileURL(canonicalRoot).href,profile])).digest("hex")}`}class Refused extends Error{result;constructor(result){super(result.err.message);this.result=result}}function requireOk(result){if(!("ok"in result))throw new Refused("err"in result?result:businessError("data_loss","Local permission custody returned no authority receipt.","storage"));return result.ok}const deny=message=>new Refused(businessError("permission_denied",message,"auth"));export function createHistoryProvider(source,config={},vault){if(!sourceValid(source))throw Error("Name google-chrome or microsoft-edge.");plain(config,["root","profile","authority"]);if(config.authority!==void 0)plain(config.authority,["resourceId","issuer","subject","tenant"]);const selectedRoot=config.root??process.env[source==="google-chrome"?"ZORTEX_CHROME_HISTORY_ROOT":"ZORTEX_EDGE_HISTORY_ROOT"]??defaultHistoryRoot(source);if(!text(selectedRoot)||!isAbsolute(selectedRoot))throw Error("Browser history root must be absolute.");const root=resolve(selectedRoot),profile=config.profile;if(profile!==void 0&&(!text(profile,64)||!PROFILE.test(profile)))throw Error("A browser profile must be Default or Profile N.");const policy=config.authority&&profile?{...config.authority,audience:historyReadAudience(source,root,profile),requiredScopes:SCOPES}:void 0;const info={source,label:source==="google-chrome"?"Chrome \u6D4F\u89C8\u5386\u53F2":"Edge \u6D4F\u89C8\u5386\u53F2",group:"Connector / \u672C\u673A\u6D4F\u89C8\u5668",auth:"none"};const jobs=new Map,stop=new AbortController;let closed=false;const signalFor=signal=>signal?AbortSignal.any([signal,stop.signal]):stop.signal;function active(signal){if(closed)throw new Refused(businessError("unavailable","History source is inactive.","plugin"));if(signal.aborted)throw new Refused(businessError("aborted","History read cancelled.","plugin"))}async function capture(signal){active(signal);if(!vault||!policy)throw new Refused(businessError("failed_precondition","Select a verified native OS-user/profile permission before reading browser history.","auth"));return requireOk(await captureLocalReadAuthority(source,policy,vault,signal))}async function guard(authority,signal){active(signal);requireOk(await checkLocalReadAuthority(authority,vault,signal));active(signal)}async function file(authority,signal){await guard(authority,signal);const actualRoot=await realpath(root);if(actualRoot!==root)throw deny("The selected browser root is not its approved canonical location.");await guard(authority,signal);const directory=join(root,profile),profileStat=await lstat(directory,{bigint:true});if(!profileStat.isDirectory()||profileStat.isSymbolicLink())throw deny("The selected browser profile is not a native directory.");await guard(authority,signal);if(await realpath(directory)!==directory)throw deny("The selected browser profile escaped its approved root.");await guard(authority,signal);const target=join(directory,"History"),stat=await lstat(target,{bigint:true});if(!stat.isFile()||stat.isSymbolicLink())throw deny("The selected History is not a native regular file.");await guard(authority,signal);if(await realpath(target)!==target)throw deny("History escaped the selected native profile.");await guard(authority,signal);return{target,profile,profileIdentity:`${profileStat.dev}:${profileStat.ino}`,fileIdentity:`${stat.dev}:${stat.ino}`}}async function sameFile(expected,authority,signal){const current=await file(authority,signal);if(current.target!==expected.target||current.profileIdentity!==expected.profileIdentity||current.fileIdentity!==expected.fileIdentity)throw deny("The selected native browser profile changed while the read was pending.")}const failed=(error,signal)=>error instanceof Refused?error.result:businessError(signal.aborted?"aborted":"unavailable","Local history cannot be queried consistently; database may be changing or its schema changed. No empty result was assumed.","plugin");const service={info,async status(){const signal=signalFor();if(closed)return businessError("unavailable","History source is inactive.","plugin");try{const authority=await capture(signal);await file(authority,signal);return ok({...info,state:"connected",account:authority.binding.account})}catch{return ok({...info,state:"not-connected",message:"A verified native OS-user/profile permission and readable selected History are required."})}},async connect(options={}){const signal=signalFor(options.signal);try{const authority=await capture(signal),target=options.expectedBinding;if(target&&(target.kind==="binding"?target.bindingId!==authority.binding.id:target.source!==source))throw deny("The requested binding does not match the selected native profile.");const result=await service.read({limit:1},{signal});if(!("ok"in result))return result;await guard(authority,signal);const job={id:randomUUID(),source,state:"connected",startedAt:new Date().toISOString(),account:authority.binding.account};jobs.set(job.id,job);return ok({...job})}catch(error){return failed(error,signal)}},job(id){const job=jobs.get(id);return job?ok({...job}):businessError("not_found","History connection job not found.","plugin")},async read(request,options={}){const invalid=validateRead(request);if(invalid)return invalid;const signal=signalFor(options.signal);try{const authority=await capture(signal),found=await file(authority,signal);let db,snapshot,records=[];try{await guard(authority,signal);try{db=new DatabaseSync(found.target,{readOnly:true});db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=100;");db.prepare("SELECT 1 FROM urls LIMIT 1").get()}catch(error){db?.close();db=void 0;if(!/locked|busy/i.test(error.message))throw error;snapshot=await historySnapshot(found.target,signal,()=>guard(authority,signal));await sameFile(found,authority,signal);await guard(authority,signal);db=new DatabaseSync(snapshot.path);db.exec("PRAGMA query_only=ON;");if(db.prepare("PRAGMA quick_check").get()?.quick_check!=="ok")throw Error("History snapshot failed SQLite integrity validation.")}const terms=["last_visit_time > 0"],parameters=[];if(request.query){terms.push("(instr(lower(url),lower(?)) > 0 OR instr(lower(title),lower(?)) > 0)");parameters.push(request.query,request.query)}for(const[key,operator]of[["since",">="],["until","<="]])if(request[key]){terms.push("last_visit_time "+operator+" ?");parameters.push(Date.parse(request[key])*1e3+116444736e8)}await guard(authority,signal);const rows=db.prepare("SELECT CAST(id AS TEXT) AS id,url,title,CAST(last_visit_time AS TEXT) AS visit_timestamp FROM urls WHERE "+terms.join(" AND ")+" ORDER BY last_visit_time DESC,urls.id DESC LIMIT ?").all(...parameters,request.limit??1);records=rows.map(row=>{const id=String(row.id),timestamp=String(row.visit_timestamp);if(!/^[1-9][0-9]{0,18}$/u.test(id)||BigInt(id)>9223372036854775807n||!/^\d{1,19}$/u.test(timestamp)||typeof row.url!=="string"||!row.url||row.title!==null&&typeof row.title!=="string")throw new Refused(businessError("data_loss","Browser History returned an invalid native record.","plugin"));const date=new Date(Number((BigInt(timestamp)-11644473600000000n)/1000n));if(!Number.isFinite(date.getTime()))throw new Refused(businessError("data_loss","Browser History returned an invalid native timestamp.","plugin"));return{source,sourceId:found.profile+":"+id+":"+timestamp,kind:"browser-history",ts:date.toISOString(),body:(row.title??"")+"\n"+row.url,fields:{url:row.url,title:row.title??"",profile:found.profile}}});await sameFile(found,authority,signal);await guard(authority,signal);const saved=await cache(vault,source,records,{source,account:authority.binding.account,accountId:authority.binding.identity.subject,requiredScopes:[...SCOPES],signal});if(!("ok"in saved))return saved;await guard(authority,signal)}finally{try{db?.close()}finally{await snapshot?.dispose()}}await sameFile(found,authority,signal);await guard(authority,signal);return readResult(source,records)}catch(error){return failed(error,signal)}},close(){closed=true;stop.abort()}};return service}
|
|
1
|
+
import{DatabaseSync}from"node:sqlite";import{lstat,realpath}from"node:fs/promises";import{homedir}from"node:os";import{join,isAbsolute,resolve}from"node:path";import{pathToFileURL}from"node:url";import{randomUUID,createHash}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{captureLocalReadAuthority,checkLocalReadAuthority,validateRead,readResult,cache}from"@zortexhq/plugin-connector-core/api";import{historySnapshot}from"./snapshot.js";const SCOPES=["history.read"],PROFILE=/^(Default|Profile \d{1,8})$/u;const sourceValid=source=>source==="google-chrome"||source==="microsoft-edge";const text=(value,max=4096)=>typeof value==="string"&&!!value&&value===value.trim()&&value.length<=max&&!/[\u0000-\u001f\u007f-\u009f]/u.test(value);function plain(value,keys){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error("Invalid native browser selection.");for(const key of Reflect.ownKeys(value)){const descriptor=Object.getOwnPropertyDescriptor(value,key);if(typeof key!=="string"||!keys.includes(key)||!descriptor.enumerable||!("value"in descriptor))throw Error("Invalid native browser selection.")}}export function defaultHistoryRoot(source){const vendor=source==="google-chrome"?"Google/Chrome":"Microsoft/Edge";return process.platform==="win32"?join(process.env.LOCALAPPDATA??homedir(),vendor,"User Data"):process.platform==="darwin"?join(homedir(),"Library/Application Support",vendor):join(homedir(),".config",source==="google-chrome"?"google-chrome":"microsoft-edge")}export function historyReadAudience(source,canonicalRoot,profile){if(!sourceValid(source)||!text(canonicalRoot)||!isAbsolute(canonicalRoot)||resolve(canonicalRoot)!==canonicalRoot||!text(profile,64)||!PROFILE.test(profile))throw Error("A canonical browser root and explicit profile are required.");return`indra-local-history:${source}:${createHash("sha256").update(JSON.stringify([pathToFileURL(canonicalRoot).href,profile])).digest("hex")}`}class Refused extends Error{result;constructor(result){super(result.err.message);this.result=result}}function requireOk(result){if(!("ok"in result))throw new Refused("err"in result?result:businessError("data_loss","Local permission custody returned no authority receipt.","storage"));return result.ok}const deny=message=>new Refused(businessError("permission_denied",message,"auth"));export function createHistoryProvider(source,config={},vault){if(!sourceValid(source))throw Error("Name google-chrome or microsoft-edge.");plain(config,["root","profile","authority"]);if(config.authority!==void 0)plain(config.authority,["resourceId","issuer","subject","tenant"]);const selectedRoot=config.root??process.env[source==="google-chrome"?"ZORTEX_CHROME_HISTORY_ROOT":"ZORTEX_EDGE_HISTORY_ROOT"]??defaultHistoryRoot(source);if(!text(selectedRoot)||!isAbsolute(selectedRoot))throw Error("Browser history root must be absolute.");const root=resolve(selectedRoot),profile=config.profile;if(profile!==void 0&&(!text(profile,64)||!PROFILE.test(profile)))throw Error("A browser profile must be Default or Profile N.");const policy=config.authority&&profile?{...config.authority,audience:historyReadAudience(source,root,profile),requiredScopes:SCOPES}:void 0;const info={source,label:source==="google-chrome"?"Chrome \u6D4F\u89C8\u5386\u53F2":"Edge \u6D4F\u89C8\u5386\u53F2",group:"Connector / \u672C\u673A\u6D4F\u89C8\u5668",auth:"none",data:{history:"sync",updates:"rescan",retention:"durable",resources:["selected_profile_history"],limitations:["local_history_retention"]}};const jobs=new Map,stop=new AbortController;let closed=false;const signalFor=signal=>signal?AbortSignal.any([signal,stop.signal]):stop.signal;function active(signal){if(closed)throw new Refused(businessError("unavailable","History source is inactive.","plugin"));if(signal.aborted)throw new Refused(businessError("aborted","History read cancelled.","plugin"))}async function capture(signal){active(signal);if(!vault||!policy)throw new Refused(businessError("failed_precondition","Select a verified native OS-user/profile permission before reading browser history.","auth"));return requireOk(await captureLocalReadAuthority(source,policy,vault,signal))}async function guard(authority,signal){active(signal);requireOk(await checkLocalReadAuthority(authority,vault,signal));active(signal)}async function file(authority,signal){await guard(authority,signal);const actualRoot=await realpath(root);if(actualRoot!==root)throw deny("The selected browser root is not its approved canonical location.");await guard(authority,signal);const directory=join(root,profile),profileStat=await lstat(directory,{bigint:true});if(!profileStat.isDirectory()||profileStat.isSymbolicLink())throw deny("The selected browser profile is not a native directory.");await guard(authority,signal);if(await realpath(directory)!==directory)throw deny("The selected browser profile escaped its approved root.");await guard(authority,signal);const target=join(directory,"History"),stat=await lstat(target,{bigint:true});if(!stat.isFile()||stat.isSymbolicLink())throw deny("The selected History is not a native regular file.");await guard(authority,signal);if(await realpath(target)!==target)throw deny("History escaped the selected native profile.");await guard(authority,signal);return{target,profile,profileIdentity:`${profileStat.dev}:${profileStat.ino}`,fileIdentity:`${stat.dev}:${stat.ino}`}}async function sameFile(expected,authority,signal){const current=await file(authority,signal);if(current.target!==expected.target||current.profileIdentity!==expected.profileIdentity||current.fileIdentity!==expected.fileIdentity)throw deny("The selected native browser profile changed while the read was pending.")}const failed=(error,signal)=>error instanceof Refused?error.result:businessError(signal.aborted?"aborted":"unavailable","Local history cannot be queried consistently; database may be changing or its schema changed. No empty result was assumed.","plugin");const service={info,async status(){const signal=signalFor();if(closed)return businessError("unavailable","History source is inactive.","plugin");try{const authority=await capture(signal);await file(authority,signal);return ok({...info,state:"connected",account:authority.binding.account})}catch{return ok({...info,state:"not-connected",message:"A verified native OS-user/profile permission and readable selected History are required."})}},async connect(options={}){const signal=signalFor(options.signal);try{const authority=await capture(signal),target=options.expectedBinding;if(target&&(target.kind==="binding"?target.bindingId!==authority.binding.id:target.source!==source))throw deny("The requested binding does not match the selected native profile.");const result=await service.read({limit:1},{signal});if(!("ok"in result))return result;await guard(authority,signal);const job={id:randomUUID(),source,state:"connected",startedAt:new Date().toISOString(),account:authority.binding.account};jobs.set(job.id,job);return ok({...job})}catch(error){return failed(error,signal)}},job(id){const job=jobs.get(id);return job?ok({...job}):businessError("not_found","History connection job not found.","plugin")},async read(request,options={}){const invalid=validateRead(request);if(invalid)return invalid;const signal=signalFor(options.signal);try{const authority=await capture(signal),found=await file(authority,signal);let db,snapshot,records=[];try{await guard(authority,signal);try{db=new DatabaseSync(found.target,{readOnly:true});db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=100;");db.prepare("SELECT 1 FROM urls LIMIT 1").get()}catch(error){db?.close();db=void 0;if(!/locked|busy/i.test(error.message))throw error;snapshot=await historySnapshot(found.target,signal,()=>guard(authority,signal));await sameFile(found,authority,signal);await guard(authority,signal);db=new DatabaseSync(snapshot.path);db.exec("PRAGMA query_only=ON;");if(db.prepare("PRAGMA quick_check").get()?.quick_check!=="ok")throw Error("History snapshot failed SQLite integrity validation.")}const terms=["last_visit_time > 0"],parameters=[];if(request.query){terms.push("(instr(lower(url),lower(?)) > 0 OR instr(lower(title),lower(?)) > 0)");parameters.push(request.query,request.query)}for(const[key,operator]of[["since",">="],["until","<="]])if(request[key]){terms.push("last_visit_time "+operator+" ?");parameters.push(Date.parse(request[key])*1e3+116444736e8)}await guard(authority,signal);const rows=db.prepare("SELECT CAST(id AS TEXT) AS id,url,title,CAST(last_visit_time AS TEXT) AS visit_timestamp FROM urls WHERE "+terms.join(" AND ")+" ORDER BY last_visit_time DESC,urls.id DESC LIMIT ?").all(...parameters,request.limit??1);records=rows.map(row=>{const id=String(row.id),timestamp=String(row.visit_timestamp);if(!/^[1-9][0-9]{0,18}$/u.test(id)||BigInt(id)>9223372036854775807n||!/^\d{1,19}$/u.test(timestamp)||typeof row.url!=="string"||!row.url||row.title!==null&&typeof row.title!=="string")throw new Refused(businessError("data_loss","Browser History returned an invalid native record.","plugin"));const date=new Date(Number((BigInt(timestamp)-11644473600000000n)/1000n));if(!Number.isFinite(date.getTime()))throw new Refused(businessError("data_loss","Browser History returned an invalid native timestamp.","plugin"));return{source,sourceId:found.profile+":"+id+":"+timestamp,kind:"browser-history",ts:date.toISOString(),body:(row.title??"")+"\n"+row.url,fields:{url:row.url,title:row.title??"",profile:found.profile}}});await sameFile(found,authority,signal);await guard(authority,signal);const saved=await cache(vault,source,records,{source,account:authority.binding.account,accountId:authority.binding.identity.subject,requiredScopes:[...SCOPES],signal});if(!("ok"in saved))return saved;await guard(authority,signal)}finally{try{db?.close()}finally{await snapshot?.dispose()}}await sameFile(found,authority,signal);await guard(authority,signal);return readResult(source,records)}catch(error){return failed(error,signal)}},close(){closed=true;stop.abort()}};return service}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{captureSelectedAccount,isTransientConnectorAction,validateRead,connectionState,readResult,cache}from"@zortexhq/plugin-connector-core/api";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{readJson}from"./http.js";import{MICROSOFT_AUTHORITY as AUTH,OUTLOOK_SCOPE,outlookClientId,credentialExpiring,requestMicrosoftToken}from"./token.js";import{stripMarkup}from"./text.js";import{createOutlookActions}from"./actions.js";const hasMailRead=scopes=>scopes.includes("Mail.Read")||scopes.includes("https://graph.microsoft.com/Mail.Read");const validScopes=scopes=>Array.isArray(scopes)&&scopes.length>0&&scopes.length<=64&&scopes.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());const validToken=value=>typeof value==="string"&&value.length>0&&value.length<=16384&&!/[\s\u0000-\u001f\u007f-\u009f]/u.test(value);function wait(task,signal){return new Promise((resolve,reject)=>{const cancelled=()=>{signal.removeEventListener("abort",cancelled);reject(signal.reason??Error("Outlook read 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 createOutlookProvider({vault,transport=fetch,enrollment}){const info={source:"outlook",label:"Outlook",group:"Connector / Microsoft",auth:"oauth-browser"};const stop=new AbortController;let closed=false;const clientId=outlookClientId();const pending=new Set,connectedJobs=new Map;let closing;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){const{binding,grant:grant2,resource,material}=snapshot;if(binding.identity.source!=="outlook"||binding.identity.issuer!=="microsoft"||binding.provider!=="microsoft"||binding.state!=="connected"||!binding.identity.subject||binding.identity.subject!==binding.identity.subject.trim()||binding.identity.subject.length>512||/[\u0000-\u001f\u007f-\u009f]/u.test(binding.identity.subject)||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","Outlook needs an explicit verified resident OAuth binding for its L1 Microsoft grant.");const credential=material.credential;if(!validScopes(grant2.scopes)||!validScopes(credential.scopes)||!sameScopes(grant2.scopes,credential.scopes))return fail("permission_denied","Outlook credential scopes do not match its 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","Outlook credential material is invalid; reconnect this source.");return ok(credential)}async function selected(snapshot,signal,guard){if(signal.aborted)return fail("aborted","Outlook selected read was stopped.");if(guard){const checked=await guard.check(signal);if(!("ok"in checked))return checked}else if(vault.bindingCustody.sourceSelection){const choice=await vault.bindingCustody.sourceSelection("outlook");if(!("ok"in choice))return choice;if(choice.ok)return fail("failed_precondition","Recovered account selections require a bounded transient read.")}const resolution=await vault.bindingCustody.resolve({kind:guard?"selected-source":"legacy-source",source:"outlook"});if(signal.aborted)return fail("aborted","Outlook selected read was stopped.");if(!("ok"in resolution))return resolution;return resolution.ok.kind==="resolved"&&resolution.ok.binding.id===snapshot.binding.id&&resolution.ok.binding.revision===snapshot.binding.revision?ok(void 0):fail("failed_precondition","Outlook account selection changed while the read was pending.")}async function fence(snapshot,signal,guard){const selection=await selected(snapshot,signal,guard);if(!("ok"in selection))return selection;const latest=await vault.bindingCustody.credentialSnapshot(snapshot.resource.id,{purpose:"L1",audience:"microsoft"});if(signal.aborted)return fail("aborted","Outlook selected read was stopped.");if(!("ok"in latest))return latest;const allowed=authorized(latest.ok);if(!("ok"in allowed))return allowed;if(allowed.ok.expiresAt<=Date.now())return fail("failed_precondition","Outlook access expired while the read was pending.");if(latest.ok.binding.revision!==snapshot.binding.revision||latest.ok.grant.id!==snapshot.grant.id||latest.ok.grant.revision!==snapshot.grant.revision||latest.ok.grant.scopeEpoch!==snapshot.grant.scopeEpoch||latest.ok.resource.revision!==snapshot.resource.revision)return fail("failed_precondition","Outlook credential authority changed while the read was pending.");return selected(snapshot,signal,guard)}function refresh(snapshot,guard){const signal=AbortSignal.any([stop.signal,AbortSignal.timeout(45e3)]);return track(vault.bindingCustody.refreshResource(snapshot,{kind:"resident"},async current=>{const allowed=authorized(current);if(!("ok"in allowed))return allowed;const selection=await selected(current,signal,guard);if(!("ok"in selection))return selection;if(!allowed.ok.refreshToken)return fail("failed_precondition","Outlook authorization expired; reconnect this source.");try{signal.throwIfAborted();const requestedAt=Date.now();const response=await wait(track(requestMicrosoftToken(transport,allowed.ok.clientId,{grant_type:"refresh_token",refresh_token:allowed.ok.refreshToken,scope:allowed.ok.scopes.join(" ")},signal)),signal);const reply=response.body;const scopes=reply.scope===void 0?[...allowed.ok.scopes]:typeof reply.scope==="string"&&reply.scope.length<=8192?reply.scope.trim().split(/\s+/u):[];const 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","Microsoft refresh did not preserve a valid access type, scope and expiry; reconnect this source.");signal.throwIfAborted();return ok({kind:"oauth",credential:{...allowed.ok,accessToken:reply.access_token,...reply.refresh_token!==void 0?{refreshToken:reply.refresh_token}:{},expiresAt,scopes:[...allowed.ok.scopes]}})}catch{return fail("failed_precondition","Microsoft refresh did not complete; its rotating outcome must not be replayed.")}}))}async function resolveSnapshot(signal,mailRead=false,guard){try{if(signal.aborted)return fail("aborted","Outlook selected read was stopped.");if(!vault.bindingCustody)return fail("failed_precondition","Outlook operations require verified account custody.");if(guard){const checked=await guard.check(signal);if(!("ok"in checked))return checked}else if(vault.bindingCustody.sourceSelection){const choice=await vault.bindingCustody.sourceSelection("outlook");if(!("ok"in choice))return choice;if(choice.ok)return fail("failed_precondition","Recovered account selections require a bounded transient read.")}const resolution=await vault.bindingCustody.resolve({kind:guard?"selected-source":"legacy-source",source:"outlook"});if(signal.aborted)return fail("aborted","Outlook selected read was stopped.");if(!("ok"in resolution))return resolution;if(resolution.ok.kind!=="resolved")return fail("failed_precondition","Outlook needs one explicit verified account binding.");const stored=await vault.bindingCustody.credentialSnapshot(oauthCredentialResourceId(resolution.ok.binding.id),{purpose:"L1",audience:"microsoft"});if(signal.aborted)return fail("aborted","Outlook selected read was stopped.");if(!("ok"in stored))return stored;let snapshot=stored.ok;let allowed=authorized(snapshot);if(!("ok"in allowed))return allowed;if(mailRead&&!hasMailRead(allowed.ok.scopes))return fail("permission_denied","The selected Outlook grant does not include Mail.Read.");if(credentialExpiring(allowed.ok)){const selection=await selected(snapshot,signal,guard);if(!("ok"in selection))return selection;if(!allowed.ok.refreshToken)return fail("failed_precondition","Outlook authorization expired; reconnect this source.");const renewed=await refresh(snapshot,guard);if(signal.aborted)return fail("aborted","Outlook selected read was stopped.");if(!("ok"in renewed))return renewed;snapshot=renewed.ok;allowed=authorized(snapshot);if(!("ok"in allowed))return allowed}const before=await fence(snapshot,signal,guard);if(!("ok"in before))return before;const identity=await readJson("https://graph.microsoft.com/v1.0/me?$select=id",{headers:{Authorization:"Bearer "+allowed.ok.accessToken},signal},transport);if(identity.id!==snapshot.binding.identity.subject)return businessError("permission_denied","Outlook native account does not match the selected connection.","auth");const after=await fence(snapshot,signal,guard);return"ok"in after?ok(snapshot):after}catch{return fail(signal.aborted?"aborted":"unavailable","Outlook authorization could not be verified.")}}async function grant(caller){if(closed)return fail("unavailable","Outlook source is inactive.");const signal=AbortSignal.any([caller,stop.signal,AbortSignal.timeout(45e3)]);try{const resolved=await wait(track(resolveSnapshot(signal)),signal);if(!("ok"in resolved))return resolved;const snapshot=resolved.ok,allowed=authorized(snapshot);if(!("ok"in allowed))return allowed;return ok({accessToken:allowed.ok.accessToken,scopes:allowed.ok.scopes,signal,check:checkSignal=>fence(snapshot,checkSignal??signal)})}catch{return fail("aborted","Outlook Action authorization was stopped.")}}async function readSelected(request,signal){try{if(vault.guardedCache!=="atomic-connection")return fail("failed_precondition","Outlook selected reads require atomic cache guards.");if(!vault.bindingCustody)return fail("failed_precondition","Outlook operations require verified account custody.");let guard;if(vault.bindingCustody.sourceSelection){const choice=await vault.bindingCustody.sourceSelection("outlook");if(!("ok"in choice))return choice;if(choice.ok){if(!isTransientConnectorAction())return fail("failed_precondition","Recovered account selections require a bounded transient read.");const captured=await captureSelectedAccount(vault,"outlook",signal);if(!("ok"in captured))return captured;guard=captured.ok}}const resolved=await resolveSnapshot(signal,true,guard);if(!("ok"in resolved))return resolved;const snapshot=resolved.ok,allowed=authorized(snapshot);if(!("ok"in allowed))return allowed;const accountId=snapshot.binding.identity.subject;if(typeof accountId!=="string"||!accountId)return fail("failed_precondition","Outlook requires a verified native account.");const url=new URL("https://graph.microsoft.com/v1.0/me/messages");url.searchParams.set("$top",String(request.limit??1));url.searchParams.set("$select","id,subject,body,bodyPreview,from,toRecipients,receivedDateTime,webLink");if(request.query)url.searchParams.set("$search",JSON.stringify(request.query));else url.searchParams.set("$orderby","receivedDateTime desc");const filter=[request.since?"receivedDateTime ge "+new Date(request.since).toISOString():"",request.until?"receivedDateTime le "+new Date(request.until).toISOString():""].filter(Boolean).join(" and ");if(filter)url.searchParams.set("$filter",filter);const response=await readJson(url.toString(),{headers:{Authorization:"Bearer "+allowed.ok.accessToken,Prefer:'outlook.body-content-type="text"'},signal},transport);const after=await fence(snapshot,signal,guard);if(!("ok"in after))return after;if(!Array.isArray(response.value)||response.value.length>(request.limit??1)||response.value.some(row=>!row||typeof row.id!=="string"||!row.id||row.id!==row.id.trim()||row.id.length>500||/[\u0000-\u001f\u007f-\u009f]/u.test(row.id)||typeof row.receivedDateTime!=="string"||!Number.isFinite(Date.parse(row.receivedDateTime))))return fail("data_loss","Outlook returned malformed messages.");const records=response.value.map(row=>({source:"outlook",sourceId:row.id,kind:"email",ts:row.receivedDateTime,body:stripMarkup(String(row.body?.content??row.bodyPreview??"")),fields:row}));const saved=await cache(vault,"outlook",records,{source:"outlook",account:snapshot.binding.account,accountId,requiredScopes:[...snapshot.grant.scopes],signal});if(!("ok"in saved))return saved;const completed=await fence(snapshot,signal,guard);if(!("ok"in completed))return completed;const result=readResult("outlook",records);return"ok"in result?ok({...result.ok,evidence:{origin:"live",observedAt:new Date().toISOString(),stage:"read-page"}}):result}catch{return fail(signal.aborted?"aborted":"unavailable","Microsoft Graph readonly query failed; no empty result was assumed.")}}const actions=createOutlookActions(grant,transport);const service={info,actions:{...actions,invoke:(...args)=>track(actions.invoke(...args))},status:()=>connectionState(vault,info),job:id=>connectedJobs.has(id)?ok({...connectedJobs.get(id)}):enrollment?enrollment.job(id):businessError("not_found","Microsoft authorization job not found.","plugin"),cancelJob:id=>connectedJobs.has(id)?ok({id,cleanup:"confirmed"}):enrollment?.cancelJob(id)??businessError("not_found","Microsoft authorization job not found.","plugin"),async connect(options={}){if(closed)return fail("unavailable","Outlook source is inactive.");const expected=options.expectedBinding?{...options.expectedBinding}:void 0;const signal=AbortSignal.any([stop.signal,AbortSignal.timeout(45e3),...options.signal?[options.signal]:[]]);if(expected?.kind==="legacy-source"&&expected.source!=="outlook")return fail("invalid_argument","Outlook account selection names another source.");if(options.automatic!==false&&vault.bindingCustody){try{const existing=await vault.connection("outlook");if(!("ok"in existing))return existing;if(expected?.kind==="binding"){const selected2=await vault.bindingCustody.resolve({kind:"legacy-source",source:"outlook"});if(!("ok"in selected2))return selected2;if(selected2.ok.kind!=="resolved"||selected2.ok.binding.id!==expected.bindingId)return fail("failed_precondition","Outlook account selection does not match the existing grant.")}if(existing.ok){const resolved=await wait(track(resolveSnapshot(signal,true)),signal);if(!("ok"in resolved))return resolved;if(signal.aborted)return fail("aborted","Outlook connection was stopped.");if(expected?.kind==="binding"&&resolved.ok.binding.id!==expected.bindingId)return fail("failed_precondition","Outlook account selection changed during authorization reuse.");const job={id:randomUUID(),source:"outlook",state:"connected",startedAt:new Date().toISOString(),account:resolved.ok.binding.account};if(connectedJobs.size>=32)connectedJobs.delete(connectedJobs.keys().next().value);connectedJobs.set(job.id,job);return ok({...job})}}catch{return fail(signal.aborted?"aborted":"unavailable","Outlook existing authorization could not be verified.")}}if(signal.aborted)return fail("aborted","Outlook connection was stopped.");if(!enrollment)return fail("unavailable","Connector enrollment is not installed.");return enrollment.pkce(info,{clientId,authorizeUrl:AUTH+"authorize?prompt=select_account",tokenUrl:AUTH+"token",scope:OUTLOOK_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 OUTLOOK_SCOPE.split(" ").filter(scope=>scope!=="offline_access"))if(!scopes.some(scope=>scope===required||scope.endsWith("/"+required)))throw Error("Required Outlook Action scope missing: "+required);const identity=await readJson("https://graph.microsoft.com/v1.0/me?$select=id,mail,userPrincipalName",{headers:{Authorization:"Bearer "+result.access_token},signal:signal2},transport);const account=identity.mail||identity.userPrincipalName;if(typeof identity.id!=="string"||!identity.id||identity.id!==identity.id.trim()||identity.id.length>512||typeof account!=="string"||!account.trim())throw Error("Microsoft account unconfirmed.");return{account,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)},async read(request,options={}){if(closed)return businessError("unavailable","Outlook source is inactive.","plugin");const invalid=validateRead(request);if(invalid)return invalid;if(request.query&&(request.since||request.until))return businessError("invalid_argument","Outlook text search and time filtering must be separate requests.","plugin");const signal=AbortSignal.any([stop.signal,AbortSignal.timeout(45e3),...options.signal?[options.signal]:[]]);try{return await wait(track(readSelected({...request},signal)),signal)}catch{return fail("aborted","Outlook selected read was stopped.")}},close(){if(closing)return closing;closed=true;stop.abort();enrollment?.cancelSource?.("outlook");closing=(async()=>{while(pending.size)await Promise.allSettled([...pending])})();return closing}};return service}
|
|
1
|
+
import{randomUUID}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{captureSelectedAccount,isTransientConnectorAction,validateRead,connectionState,readResult,cache}from"@zortexhq/plugin-connector-core/api";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{readJson}from"./http.js";import{MICROSOFT_AUTHORITY as AUTH,OUTLOOK_SCOPE,outlookClientId,credentialExpiring,requestMicrosoftToken}from"./token.js";import{stripMarkup}from"./text.js";import{createOutlookActions}from"./actions.js";const hasMailRead=scopes=>scopes.includes("Mail.Read")||scopes.includes("https://graph.microsoft.com/Mail.Read");const validScopes=scopes=>Array.isArray(scopes)&&scopes.length>0&&scopes.length<=64&&scopes.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());const validToken=value=>typeof value==="string"&&value.length>0&&value.length<=16384&&!/[\s\u0000-\u001f\u007f-\u009f]/u.test(value);function wait(task,signal){return new Promise((resolve,reject)=>{const cancelled=()=>{signal.removeEventListener("abort",cancelled);reject(signal.reason??Error("Outlook read 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 createOutlookProvider({vault,transport=fetch,enrollment}){const info={source:"outlook",label:"Outlook",group:"Connector / Microsoft",auth:"oauth-browser",data:{history:"sync",updates:"delta",retention:"durable",resources:["mail"],limitations:["attachment_budgets"]}};const stop=new AbortController;let closed=false;const clientId=outlookClientId();const pending=new Set,connectedJobs=new Map;let closing;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){const{binding,grant:grant2,resource,material}=snapshot;if(binding.identity.source!=="outlook"||binding.identity.issuer!=="microsoft"||binding.provider!=="microsoft"||binding.state!=="connected"||!binding.identity.subject||binding.identity.subject!==binding.identity.subject.trim()||binding.identity.subject.length>512||/[\u0000-\u001f\u007f-\u009f]/u.test(binding.identity.subject)||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","Outlook needs an explicit verified resident OAuth binding for its L1 Microsoft grant.");const credential=material.credential;if(!validScopes(grant2.scopes)||!validScopes(credential.scopes)||!sameScopes(grant2.scopes,credential.scopes))return fail("permission_denied","Outlook credential scopes do not match its 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","Outlook credential material is invalid; reconnect this source.");return ok(credential)}async function selected(snapshot,signal,guard){if(signal.aborted)return fail("aborted","Outlook selected read was stopped.");if(guard){const checked=await guard.check(signal);if(!("ok"in checked))return checked}else if(vault.bindingCustody.sourceSelection){const choice=await vault.bindingCustody.sourceSelection("outlook");if(!("ok"in choice))return choice;if(choice.ok)return fail("failed_precondition","Recovered account selections require a bounded transient read.")}const resolution=await vault.bindingCustody.resolve({kind:guard?"selected-source":"legacy-source",source:"outlook"});if(signal.aborted)return fail("aborted","Outlook selected read was stopped.");if(!("ok"in resolution))return resolution;return resolution.ok.kind==="resolved"&&resolution.ok.binding.id===snapshot.binding.id&&resolution.ok.binding.revision===snapshot.binding.revision?ok(void 0):fail("failed_precondition","Outlook account selection changed while the read was pending.")}async function fence(snapshot,signal,guard){const selection=await selected(snapshot,signal,guard);if(!("ok"in selection))return selection;const latest=await vault.bindingCustody.credentialSnapshot(snapshot.resource.id,{purpose:"L1",audience:"microsoft"});if(signal.aborted)return fail("aborted","Outlook selected read was stopped.");if(!("ok"in latest))return latest;const allowed=authorized(latest.ok);if(!("ok"in allowed))return allowed;if(allowed.ok.expiresAt<=Date.now())return fail("failed_precondition","Outlook access expired while the read was pending.");if(latest.ok.binding.revision!==snapshot.binding.revision||latest.ok.grant.id!==snapshot.grant.id||latest.ok.grant.revision!==snapshot.grant.revision||latest.ok.grant.scopeEpoch!==snapshot.grant.scopeEpoch||latest.ok.resource.revision!==snapshot.resource.revision)return fail("failed_precondition","Outlook credential authority changed while the read was pending.");return selected(snapshot,signal,guard)}function refresh(snapshot,guard){const signal=AbortSignal.any([stop.signal,AbortSignal.timeout(45e3)]);return track(vault.bindingCustody.refreshResource(snapshot,{kind:"resident"},async current=>{const allowed=authorized(current);if(!("ok"in allowed))return allowed;const selection=await selected(current,signal,guard);if(!("ok"in selection))return selection;if(!allowed.ok.refreshToken)return fail("failed_precondition","Outlook authorization expired; reconnect this source.");try{signal.throwIfAborted();const requestedAt=Date.now();const response=await wait(track(requestMicrosoftToken(transport,allowed.ok.clientId,{grant_type:"refresh_token",refresh_token:allowed.ok.refreshToken,scope:allowed.ok.scopes.join(" ")},signal)),signal);const reply=response.body;const scopes=reply.scope===void 0?[...allowed.ok.scopes]:typeof reply.scope==="string"&&reply.scope.length<=8192?reply.scope.trim().split(/\s+/u):[];const 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","Microsoft refresh did not preserve a valid access type, scope and expiry; reconnect this source.");signal.throwIfAborted();return ok({kind:"oauth",credential:{...allowed.ok,accessToken:reply.access_token,...reply.refresh_token!==void 0?{refreshToken:reply.refresh_token}:{},expiresAt,scopes:[...allowed.ok.scopes]}})}catch{return fail("failed_precondition","Microsoft refresh did not complete; its rotating outcome must not be replayed.")}}))}async function resolveSnapshot(signal,mailRead=false,guard){try{if(signal.aborted)return fail("aborted","Outlook selected read was stopped.");if(!vault.bindingCustody)return fail("failed_precondition","Outlook operations require verified account custody.");if(guard){const checked=await guard.check(signal);if(!("ok"in checked))return checked}else if(vault.bindingCustody.sourceSelection){const choice=await vault.bindingCustody.sourceSelection("outlook");if(!("ok"in choice))return choice;if(choice.ok)return fail("failed_precondition","Recovered account selections require a bounded transient read.")}const resolution=await vault.bindingCustody.resolve({kind:guard?"selected-source":"legacy-source",source:"outlook"});if(signal.aborted)return fail("aborted","Outlook selected read was stopped.");if(!("ok"in resolution))return resolution;if(resolution.ok.kind!=="resolved")return fail("failed_precondition","Outlook needs one explicit verified account binding.");const stored=await vault.bindingCustody.credentialSnapshot(oauthCredentialResourceId(resolution.ok.binding.id),{purpose:"L1",audience:"microsoft"});if(signal.aborted)return fail("aborted","Outlook selected read was stopped.");if(!("ok"in stored))return stored;let snapshot=stored.ok;let allowed=authorized(snapshot);if(!("ok"in allowed))return allowed;if(mailRead&&!hasMailRead(allowed.ok.scopes))return fail("permission_denied","The selected Outlook grant does not include Mail.Read.");if(credentialExpiring(allowed.ok)){const selection=await selected(snapshot,signal,guard);if(!("ok"in selection))return selection;if(!allowed.ok.refreshToken)return fail("failed_precondition","Outlook authorization expired; reconnect this source.");const renewed=await refresh(snapshot,guard);if(signal.aborted)return fail("aborted","Outlook selected read was stopped.");if(!("ok"in renewed))return renewed;snapshot=renewed.ok;allowed=authorized(snapshot);if(!("ok"in allowed))return allowed}const before=await fence(snapshot,signal,guard);if(!("ok"in before))return before;const identity=await readJson("https://graph.microsoft.com/v1.0/me?$select=id",{headers:{Authorization:"Bearer "+allowed.ok.accessToken},signal},transport);if(identity.id!==snapshot.binding.identity.subject)return businessError("permission_denied","Outlook native account does not match the selected connection.","auth");const after=await fence(snapshot,signal,guard);return"ok"in after?ok(snapshot):after}catch{return fail(signal.aborted?"aborted":"unavailable","Outlook authorization could not be verified.")}}async function grant(caller){if(closed)return fail("unavailable","Outlook source is inactive.");const signal=AbortSignal.any([caller,stop.signal,AbortSignal.timeout(45e3)]);try{const resolved=await wait(track(resolveSnapshot(signal)),signal);if(!("ok"in resolved))return resolved;const snapshot=resolved.ok,allowed=authorized(snapshot);if(!("ok"in allowed))return allowed;return ok({accessToken:allowed.ok.accessToken,scopes:allowed.ok.scopes,signal,check:checkSignal=>fence(snapshot,checkSignal??signal)})}catch{return fail("aborted","Outlook Action authorization was stopped.")}}async function readSelected(request,signal){try{if(vault.guardedCache!=="atomic-connection")return fail("failed_precondition","Outlook selected reads require atomic cache guards.");if(!vault.bindingCustody)return fail("failed_precondition","Outlook operations require verified account custody.");let guard;if(vault.bindingCustody.sourceSelection){const choice=await vault.bindingCustody.sourceSelection("outlook");if(!("ok"in choice))return choice;if(choice.ok){if(!isTransientConnectorAction())return fail("failed_precondition","Recovered account selections require a bounded transient read.");const captured=await captureSelectedAccount(vault,"outlook",signal);if(!("ok"in captured))return captured;guard=captured.ok}}const resolved=await resolveSnapshot(signal,true,guard);if(!("ok"in resolved))return resolved;const snapshot=resolved.ok,allowed=authorized(snapshot);if(!("ok"in allowed))return allowed;const accountId=snapshot.binding.identity.subject;if(typeof accountId!=="string"||!accountId)return fail("failed_precondition","Outlook requires a verified native account.");const url=new URL("https://graph.microsoft.com/v1.0/me/messages");url.searchParams.set("$top",String(request.limit??1));url.searchParams.set("$select","id,subject,body,bodyPreview,from,toRecipients,receivedDateTime,webLink");if(request.query)url.searchParams.set("$search",JSON.stringify(request.query));else url.searchParams.set("$orderby","receivedDateTime desc");const filter=[request.since?"receivedDateTime ge "+new Date(request.since).toISOString():"",request.until?"receivedDateTime le "+new Date(request.until).toISOString():""].filter(Boolean).join(" and ");if(filter)url.searchParams.set("$filter",filter);const response=await readJson(url.toString(),{headers:{Authorization:"Bearer "+allowed.ok.accessToken,Prefer:'outlook.body-content-type="text"'},signal},transport);const after=await fence(snapshot,signal,guard);if(!("ok"in after))return after;if(!Array.isArray(response.value)||response.value.length>(request.limit??1)||response.value.some(row=>!row||typeof row.id!=="string"||!row.id||row.id!==row.id.trim()||row.id.length>500||/[\u0000-\u001f\u007f-\u009f]/u.test(row.id)||typeof row.receivedDateTime!=="string"||!Number.isFinite(Date.parse(row.receivedDateTime))))return fail("data_loss","Outlook returned malformed messages.");const records=response.value.map(row=>({source:"outlook",sourceId:row.id,kind:"email",ts:row.receivedDateTime,body:stripMarkup(String(row.body?.content??row.bodyPreview??"")),fields:row}));const saved=await cache(vault,"outlook",records,{source:"outlook",account:snapshot.binding.account,accountId,requiredScopes:[...snapshot.grant.scopes],signal});if(!("ok"in saved))return saved;const completed=await fence(snapshot,signal,guard);if(!("ok"in completed))return completed;const result=readResult("outlook",records);return"ok"in result?ok({...result.ok,evidence:{origin:"live",observedAt:new Date().toISOString(),stage:"read-page"}}):result}catch{return fail(signal.aborted?"aborted":"unavailable","Microsoft Graph readonly query failed; no empty result was assumed.")}}const actions=createOutlookActions(grant,transport);const service={info,actions:{...actions,invoke:(...args)=>track(actions.invoke(...args))},status:()=>connectionState(vault,info),job:id=>connectedJobs.has(id)?ok({...connectedJobs.get(id)}):enrollment?enrollment.job(id):businessError("not_found","Microsoft authorization job not found.","plugin"),cancelJob:id=>connectedJobs.has(id)?ok({id,cleanup:"confirmed"}):enrollment?.cancelJob(id)??businessError("not_found","Microsoft authorization job not found.","plugin"),async connect(options={}){if(closed)return fail("unavailable","Outlook source is inactive.");const expected=options.expectedBinding?{...options.expectedBinding}:void 0;const signal=AbortSignal.any([stop.signal,AbortSignal.timeout(45e3),...options.signal?[options.signal]:[]]);if(expected?.kind==="legacy-source"&&expected.source!=="outlook")return fail("invalid_argument","Outlook account selection names another source.");if(options.automatic!==false&&vault.bindingCustody){try{const existing=await vault.connection("outlook");if(!("ok"in existing))return existing;if(expected?.kind==="binding"){const selected2=await vault.bindingCustody.resolve({kind:"legacy-source",source:"outlook"});if(!("ok"in selected2))return selected2;if(selected2.ok.kind!=="resolved"||selected2.ok.binding.id!==expected.bindingId)return fail("failed_precondition","Outlook account selection does not match the existing grant.")}if(existing.ok){const resolved=await wait(track(resolveSnapshot(signal,true)),signal);if(!("ok"in resolved))return resolved;if(signal.aborted)return fail("aborted","Outlook connection was stopped.");if(expected?.kind==="binding"&&resolved.ok.binding.id!==expected.bindingId)return fail("failed_precondition","Outlook account selection changed during authorization reuse.");const job={id:randomUUID(),source:"outlook",state:"connected",startedAt:new Date().toISOString(),account:resolved.ok.binding.account};if(connectedJobs.size>=32)connectedJobs.delete(connectedJobs.keys().next().value);connectedJobs.set(job.id,job);return ok({...job})}}catch{return fail(signal.aborted?"aborted":"unavailable","Outlook existing authorization could not be verified.")}}if(signal.aborted)return fail("aborted","Outlook connection was stopped.");if(!enrollment)return fail("unavailable","Connector enrollment is not installed.");return enrollment.pkce(info,{clientId,authorizeUrl:AUTH+"authorize?prompt=select_account",tokenUrl:AUTH+"token",scope:OUTLOOK_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 OUTLOOK_SCOPE.split(" ").filter(scope=>scope!=="offline_access"))if(!scopes.some(scope=>scope===required||scope.endsWith("/"+required)))throw Error("Required Outlook Action scope missing: "+required);const identity=await readJson("https://graph.microsoft.com/v1.0/me?$select=id,mail,userPrincipalName",{headers:{Authorization:"Bearer "+result.access_token},signal:signal2},transport);const account=identity.mail||identity.userPrincipalName;if(typeof identity.id!=="string"||!identity.id||identity.id!==identity.id.trim()||identity.id.length>512||typeof account!=="string"||!account.trim())throw Error("Microsoft account unconfirmed.");return{account,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)},async read(request,options={}){if(closed)return businessError("unavailable","Outlook source is inactive.","plugin");const invalid=validateRead(request);if(invalid)return invalid;if(request.query&&(request.since||request.until))return businessError("invalid_argument","Outlook text search and time filtering must be separate requests.","plugin");const signal=AbortSignal.any([stop.signal,AbortSignal.timeout(45e3),...options.signal?[options.signal]:[]]);try{return await wait(track(readSelected({...request},signal)),signal)}catch{return fail("aborted","Outlook selected read was stopped.")}},close(){if(closing)return closing;closed=true;stop.abort();enrollment?.cancelSource?.("outlook");closing=(async()=>{while(pending.size)await Promise.allSettled([...pending])})();return closing}};return service}
|
|
@@ -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"};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]:[]]);try{return await wait(track(actions.invoke(name,input,{...options,signal})),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Slack Action did not complete.")}}},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
|
+
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]:[]]);try{return await wait(track(actions.invoke(name,input,{...options,signal})),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Slack Action did not complete.")}}},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{createHash}from"node:crypto";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{pinnedMethods,discoveryPin}from"./discovery-data.js";import{creatorMethods}from"./creator-data.js";import{object,invalidSchema}from"./schema.js";import{createYouTubeConnector}from"./connector.js";import{readTakeout}from"./takeout.js";const methodMap=new Map([...pinnedMethods,...creatorMethods].flatMap(method=>[[method.id,method],[method.contractName,method]]));const info={source:"youtube",label:"YouTube",group:"Connector / Google",auth:"oauth-browser",readById:true};export function createYouTubeSource({parts,auth,vault,transport,takeoutRoot}){const stop=new AbortController,pending=new Set;let closed=false;const track=work=>{pending.add(work);return work.finally(()=>pending.delete(work))};const unavailable=()=>businessError("unavailable","YouTube source is inactive.","connector");const aborted=()=>businessError("aborted","YouTube read was cancelled.","connector");function catalog(options={}){const{query="",resource,limit=20,cursor=0,profile="data"}=options;if(typeof query!=="string"||query.length>500||resource!==void 0&&typeof resource!=="string"||!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return businessError("invalid_argument","Catalog query/limit/cursor is invalid.","connector");if(!["data","analytics","reporting","all"].includes(profile))return businessError("invalid_argument","Unknown YouTube capability profile.","connector");const selected=[...pinnedMethods,...creatorMethods].filter(m=>(profile==="all"||(m.profile??"data")===profile)&&(!resource||m.resource===resource)&&(!query||[m.id,m.description??""].join(" ").toLowerCase().includes(query.toLowerCase())));return Original.ok({total:selected.length,methods:selected.slice(cursor,cursor+limit).map(m=>({id:m.id,contract:m.contractName,resource:m.resource,method:m.httpMethod,scopes:m.scopes??[],body:!!m.request?.$ref,media:!!m.supportsMediaUpload})),...cursor+limit<selected.length?{next:cursor+limit}:{},pin:discoveryPin,gaps:["watchHistory/watchLater require explicit read-only Takeout","creator Analytics/Reporting need separate admitted profile and scopes","audio/video bytes require provider permission","write effects require original action rail verification; HTTP success is not EFFECTED"]})}function method(id){const found=methodMap.get(id);return found?Original.ok(structuredClone(found)):businessError("not_found","Unknown pinned YouTube method.","connector")}async function invokeInner(id,input,options={},level1=false){if(closed)return unavailable();const m=methodMap.get(id);if(!m)return businessError("not_found","Unknown pinned YouTube method.","connector");const invalid=invalidSchema(m.params,input);if(invalid)return businessError("invalid_argument",invalid,"connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const conn=await vault.connection("youtube");if(!("ok"in conn))return conn;if(!conn.ok||conn.ok.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(closed||signal.aborted)return aborted();if(!m.scopes?.length)return businessError("failed_precondition","The pinned provider method "+m.id+" publishes no OAuth scope requirement. Scope/admission reconnaissance is required before a dispatch; no permission was guessed.","auth");if(!(m.scopes??[]).some(scope=>conn.ok.scopes.includes(scope)))return businessError("permission_denied","Method "+id+" requires one of the declared scopes: "+(m.scopes??[]).join(", ")+". Reauthorize this source; no API-key fallback.","auth");if(input.params.onBehalfOfContentOwner!==void 0&&!conn.ok.scopes.includes("https://www.googleapis.com/auth/youtubepartner"))return businessError("permission_denied","Content-owner operations require the partner scope and linked CMS admission.","auth");let pathname=m.path;const query=new URLSearchParams;for(const[key,value]of Object.entries(input.params)){if(m.parameters?.[key]?.location==="path"){const text=String(value);if(text.split("/").some(segment=>segment==="."||segment==="..")||/[?#%\\]/.test(text))return businessError("invalid_argument","Path parameters cannot contain traversal or encoded routing material.","connector");const reserved=pathname.includes("{+"+key+"}");if(reserved&&!/^[A-Za-z0-9_./-]+$/.test(text))return businessError("invalid_argument","Reserved resource paths must be canonical provider resource names.","connector");pathname=pathname.replace(reserved?"{+"+key+"}":"{"+key+"}",reserved?text.split("/").map(encodeURIComponent).join("/"):encodeURIComponent(text))}else query.set(key,Array.isArray(value)?value.join(","):String(value))}if(pathname.includes("{"))return businessError("invalid_argument","Provider path parameter is missing.","connector");if(input.media)return businessError("failed_precondition","Media upload needs the separately admitted bounded streaming transport; no effect was dispatched.","connector");if(m.id==="youtube.youtube.v3.liveChat.messages.stream")return businessError("failed_precondition","The pinned server-streaming RPC requires an admitted cancelable stream transport; use liveChatMessages.list with pageToken until that profile is enabled.","connector");if(m.httpMethod!=="GET"&&!transport&&!level1)return businessError("failed_precondition","Write transport and original action admission are required for "+id+"; no effect was dispatched.","connector");const url=new URL(pathname,m.baseUrl??"https://www.googleapis.com/");url.search=query.toString();const raw=transport?await transport("youtube",url.href,{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"},signal}):await auth.requestRaw("youtube",url.href,{signal,...level1?{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"}}:{}});if(closed||signal.aborted)return aborted();if(!("ok"in raw))return raw;if(Buffer.byteLength(raw.ok.body,"utf8")>2*1024*1024)return businessError("resource_exhausted","YouTube response exceeds the bounded broker body budget. Use an admitted streaming path; no body was truncated.","connector");const reason=parts.googleErrorReasonV1(raw.ok.body),baseOverride=parts.googleStatusOverrideV1(raw.ok.body),status=parts.webStatusErrorV1(raw.ok.status,{provider:"YouTube",what:id,headers:raw.ok.headers,bodyOverride:status2=>status2===403&&reason==="quotaExceeded"?{code:"resource_exhausted",retryability:"throttling",meaning:"the YouTube project quota bucket is exhausted (quotaExceeded)"}:baseOverride(status2),...reason?{detail:reason}:{}});if(status)return{err:status};if(m.supportsMediaDownload){return Original.ok({method:id,resource:m.resource,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain",items:[{id:input.params.id??input.params.resourceName,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain"}],warnings:[],effect:"read",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}if(raw.ok.status===204||!raw.ok.body)return Original.ok({method:id,resource:m.resource,items:[],warnings:["Provider response carries no body; upstream effect remains unverified."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}});let data;try{data=JSON.parse(raw.ok.body)}catch{return businessError("data_loss","YouTube returned invalid JSON for "+id+".","connector")}if(!object(data))return businessError("data_loss","YouTube response must be an object.","connector");if(data.items!==void 0&&(!Array.isArray(data.items)||data.items.some(item=>!object(item))))return businessError("data_loss","YouTube response items are malformed.","connector");if(data.nextPageToken!==void 0&&(typeof data.nextPageToken!=="string"||!data.nextPageToken||data.nextPageToken.length>6e3))return businessError("data_loss","YouTube nextPageToken is malformed.","connector");const items=Array.isArray(data.items)?data.items:typeof data.id==="string"?[data]:[];return Original.ok({method:id,resource:m.resource,data,items,...typeof data.nextPageToken==="string"?{nextPageToken:data.nextPageToken}:{},warnings:m.httpMethod==="GET"?[]:["HTTP response accepted. Only original action read-after-write/event-confirm can mark EFFECTED."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}function invoke(id,input,options={},level1=false){return track(invokeInner(id,input,options,level1).catch(error=>{if(closed||options.signal?.aborted)return aborted();const cause=object(error)?Original.validateStructuredError(error.structuredError):void 0;return parts.connectorError("unavailable","Trusted YouTube transport failed before a confirmed provider response. Raw custody exception text is not a tool result.","transient",cause&&"ok"in cause?cause.ok:void 0)}))}async function*pages(id,params,options={}){const m=methodMap.get(id);if(!m||m.httpMethod!=="GET"){yield businessError("invalid_argument","Only pinned GET methods can be paginated.","connector");return}if(options.maxPages!==void 0&&(!Number.isInteger(options.maxPages)||options.maxPages<1)){yield businessError("invalid_argument","maxPages must be a positive integer.","connector");return}const seen=new Set;let token=typeof params.pageToken==="string"?params.pageToken:void 0,count=0;for(;;){if(token&&seen.has(token)){yield businessError("failed_precondition","YouTube repeated a page token; coverage is incomplete.","connector");return}if(token)seen.add(token);const result=await invoke(id,{params:{...params,...token?{pageToken:token}:{}}},options);yield result;if(!("ok"in result))return;count++;token=result.ok.nextPageToken;if(!token)return;if(options.maxPages!==void 0&&count>=options.maxPages){yield businessError("resource_exhausted","Selected page budget ended with a nonterminal token; coverage is incomplete.","connector");return}}}async function readInner(request,options={}){if(closed)return unavailable();const bad=validateRead(request,["fileId"]);if(bad)return bad;request=structuredClone(request);if(request.fileId!==void 0&&(!/^[A-Za-z0-9_-]{1,200}$/.test(request.fileId)||request.query!==void 0||request.since!==void 0||request.until!==void 0))return businessError("invalid_argument","An exact YouTube video read takes fileId without query or time bounds.","connector");const selected=request.fileId?"youtube.videos.list":request.query?"youtube.search.list":"youtube.activities.list";const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const connection=await vault.connection("youtube");if(!("ok"in connection))return connection;const captured=structuredClone(connection.ok);if(!captured||captured.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(typeof captured.accountId!=="string"||!captured.accountId.trim())return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");const firstScopes=methodMap.get(selected)?.scopes??[],detailScopes=request.query?methodMap.get("youtube.videos.list")?.scopes??[]:firstScopes,scopes=firstScopes.filter(scope=>detailScopes.includes(scope)),readonly="https://www.googleapis.com/auth/youtube.readonly";const requiredScope=scopes.includes(readonly)&&captured.scopes.includes(readonly)?readonly:scopes.find(scope=>captured.scopes.includes(scope));if(!requiredScope)return businessError("permission_denied","The selected YouTube query requires one of its pinned read scopes.","auth");const fence=async()=>{if(closed||signal.aborted)return aborted();const current=await vault.connection("youtube");if(!("ok"in current))return current;if(!current.ok||current.ok.state!=="connected"||current.ok.account!==captured.account||current.ok.accountId!==captured.accountId||!current.ok.scopes.includes(requiredScope))return businessError("permission_denied","YouTube selected read connection or scope changed.","auth");return Original.ok(void 0)};const boundInvoke=async(id,input)=>{const before=await fence();if(!("ok"in before))return before;const answer2=await invoke(id,input,{signal});const after=await fence();return"ok"in after?answer2:after};const wanted=request.limit??1,params=request.fileId?{part:["snippet","contentDetails","status","statistics"],id:[request.fileId]}:request.query?{part:["snippet"],q:request.query,type:["video"],maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}}:{part:["snippet","contentDetails"],mine:true,maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}};let answer=await boundInvoke(selected,{params});if("err"in answer&&selected==="youtube.activities.list"&&answer.err.code==="permission_denied"){const channels=await boundInvoke("youtube.channels.list",{params:{part:["id"],mine:true,maxResults:1}});if("ok"in channels&&!channels.ok.items.length)return readResult("youtube",[],["This Google account has no YouTube channel, so it has no own activity to read; full sync records it as no-youtube-channel."])}if(!("ok"in answer))return answer;const items=[...answer.ok.items],seen=new Set;let steps=1;while(items.length<wanted&&answer.ok.nextPageToken){const token=answer.ok.nextPageToken;if(seen.has(token))return businessError("failed_precondition","Selected YouTube read repeated a token; no complete result was asserted.","connector");seen.add(token);if(++steps>100)return businessError("resource_exhausted","Selected YouTube read exceeded the page budget before satisfying its limit; no complete result was asserted.","connector");answer=await boundInvoke(selected,{params:{...params,pageToken:token}});if(!("ok"in answer))return answer;items.push(...answer.ok.items)}let retained=items.slice(0,wanted),resource=answer.ok.resource;if(request.query&&retained.length){const selectedItems=retained,details=[];for(let index=0;index<selectedItems.length;index+=50){const block=selectedItems.slice(index,index+50),ids=block.map(item=>object(item.id)?item.id.videoId:void 0).filter(id=>typeof id==="string");if(ids.length!==block.length)return businessError("data_loss","A selected YouTube video search result lacks its native video id.","connector");const hydrated=await boundInvoke("youtube.videos.list",{params:{part:["snippet","contentDetails","status","statistics","topicDetails","recordingDetails","localizations"],id:ids}});if(!("ok"in hydrated))return hydrated;for(const item of hydrated.ok.items)details.push({...item,_selection:block.find(selected2=>object(selected2.id)&&selected2.id.videoId===item.id)??null})}retained=details;resource="videos"}const records=retained.map(item=>({source:"youtube",sourceId:captured.accountId+":"+resource+":"+itemId(item),stream:resource,kind:"youtube."+resource.toLowerCase()+".changed",ts:itemTime(item),body:JSON.stringify(item),fields:{...item}}));const beforeReturn=await fence();if(!("ok"in beforeReturn))return beforeReturn;if(closed||signal.aborted)return aborted();return readResult("youtube",records,[...answer.ok.warnings,...answer.ok.nextPageToken||items.length>wanted?["More provider results exist beyond this selected batch."]:[],...retained.length<Math.min(items.length,wanted)?["Some selected videos are currently inaccessible/deleted; search metadata is retained only as an attributed missing detail, never a fabricated video body."]:[],"This selected API query does not establish complete YouTube account or archive coverage."])}function read(request,options={}){return track(readInner(request,options))}async function importTakeout(root=takeoutRoot??"",options={}){if(closed)return unavailable();if(!root)return businessError("failed_precondition","Supply an explicit extracted read-only Takeout copy; API success cannot substitute for history.","connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;const result=await readTakeout(root,signal);if(!("ok"in result))return result;if(closed||signal.aborted)return aborted();const saved=await cache(vault,"youtube",result.ok.records);if(!("ok"in saved))return saved;return result}const account=async()=>{const row=await vault.connection("youtube");if(!("ok"in row))return row;if(!row.ok||row.ok.state!=="connected")return businessError("unauthenticated","YouTube identity needs a connected account.","auth");if(!row.ok.accountId)return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");return Original.ok(row.ok.accountId)};function actionSchema(schema){const{id:_discoveryType,...result}=schema;if(result.properties)result.properties=Object.fromEntries(Object.entries(result.properties).map(([key,value])=>[key,actionSchema(value)]));if(result.items)result.items=actionSchema(result.items);if(object(result.additionalProperties))result.additionalProperties=actionSchema(result.additionalProperties);return result}const actions={catalog,method:id=>{const result=method(id);if(!("ok"in result))return result;const m=result.ok;return Original.ok({...m,params:actionSchema(m.params),...!m.supportsMediaUpload&&m.id!=="youtube.youtube.v3.liveChat.messages.stream"&&(!m.profile||m.httpMethod==="GET")?{level:1,effect:m.httpMethod==="GET"?"read":"write"}:{}})},invoke:(id,input,options={})=>invoke(id,input,options,true)};const source={info,actions,catalog,method,invoke,pages,read,status:()=>closed?Promise.resolve(Original.ok({...info,state:"unavailable",message:"YouTube source is inactive."})):connectionState(vault,info),connect:options=>closed?Promise.resolve(unavailable()):track(auth.connect("youtube",options)),job:id=>closed?unavailable():auth.job(id),cancelJob:id=>auth.cancelJob(id),importTakeout:(root,options)=>track(importTakeout(root,options)),createConnector:(plan,options={})=>createYouTubeConnector({parts,invoke,method,account,isClosed:()=>closed},plan,options),async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}};return source}export function itemId(item){if(typeof item.id==="string")return item.id;if(typeof item.videoId==="string")return item.videoId;if(object(item.id)){for(const key of["videoId","channelId","playlistId"])if(typeof item.id[key]==="string")return key+":"+item.id[key]}const value=JSON.parse(JSON.stringify(item.id??item));return createHash("sha256").update(Original.jcsCanonicalize(value)).digest("hex")}export function itemTime(item){const snippet=object(item.snippet)?item.snippet:{};for(const value of[item.time,item.updated,item.updatedAt,snippet.updatedAt,snippet.publishedAt])if(typeof value==="string"&&Number.isFinite(Date.parse(value)))return new Date(value).toISOString();return"1970-01-01T00:00:00.000Z"}
|
|
1
|
+
import{createHash}from"node:crypto";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{pinnedMethods,discoveryPin}from"./discovery-data.js";import{creatorMethods}from"./creator-data.js";import{object,invalidSchema}from"./schema.js";import{createYouTubeConnector}from"./connector.js";import{readTakeout}from"./takeout.js";const methodMap=new Map([...pinnedMethods,...creatorMethods].flatMap(method=>[[method.id,method],[method.contractName,method]]));const info={source:"youtube",label:"YouTube",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["authorized_collections"],limitations:["provider_history_limits"]},readById:true};export function createYouTubeSource({parts,auth,vault,transport,takeoutRoot}){const stop=new AbortController,pending=new Set;let closed=false;const track=work=>{pending.add(work);return work.finally(()=>pending.delete(work))};const unavailable=()=>businessError("unavailable","YouTube source is inactive.","connector");const aborted=()=>businessError("aborted","YouTube read was cancelled.","connector");function catalog(options={}){const{query="",resource,limit=20,cursor=0,profile="data"}=options;if(typeof query!=="string"||query.length>500||resource!==void 0&&typeof resource!=="string"||!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return businessError("invalid_argument","Catalog query/limit/cursor is invalid.","connector");if(!["data","analytics","reporting","all"].includes(profile))return businessError("invalid_argument","Unknown YouTube capability profile.","connector");const selected=[...pinnedMethods,...creatorMethods].filter(m=>(profile==="all"||(m.profile??"data")===profile)&&(!resource||m.resource===resource)&&(!query||[m.id,m.description??""].join(" ").toLowerCase().includes(query.toLowerCase())));return Original.ok({total:selected.length,methods:selected.slice(cursor,cursor+limit).map(m=>({id:m.id,contract:m.contractName,resource:m.resource,method:m.httpMethod,scopes:m.scopes??[],body:!!m.request?.$ref,media:!!m.supportsMediaUpload})),...cursor+limit<selected.length?{next:cursor+limit}:{},pin:discoveryPin,gaps:["watchHistory/watchLater require explicit read-only Takeout","creator Analytics/Reporting need separate admitted profile and scopes","audio/video bytes require provider permission","write effects require original action rail verification; HTTP success is not EFFECTED"]})}function method(id){const found=methodMap.get(id);return found?Original.ok(structuredClone(found)):businessError("not_found","Unknown pinned YouTube method.","connector")}async function invokeInner(id,input,options={},level1=false){if(closed)return unavailable();const m=methodMap.get(id);if(!m)return businessError("not_found","Unknown pinned YouTube method.","connector");const invalid=invalidSchema(m.params,input);if(invalid)return businessError("invalid_argument",invalid,"connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const conn=await vault.connection("youtube");if(!("ok"in conn))return conn;if(!conn.ok||conn.ok.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(closed||signal.aborted)return aborted();if(!m.scopes?.length)return businessError("failed_precondition","The pinned provider method "+m.id+" publishes no OAuth scope requirement. Scope/admission reconnaissance is required before a dispatch; no permission was guessed.","auth");if(!(m.scopes??[]).some(scope=>conn.ok.scopes.includes(scope)))return businessError("permission_denied","Method "+id+" requires one of the declared scopes: "+(m.scopes??[]).join(", ")+". Reauthorize this source; no API-key fallback.","auth");if(input.params.onBehalfOfContentOwner!==void 0&&!conn.ok.scopes.includes("https://www.googleapis.com/auth/youtubepartner"))return businessError("permission_denied","Content-owner operations require the partner scope and linked CMS admission.","auth");let pathname=m.path;const query=new URLSearchParams;for(const[key,value]of Object.entries(input.params)){if(m.parameters?.[key]?.location==="path"){const text=String(value);if(text.split("/").some(segment=>segment==="."||segment==="..")||/[?#%\\]/.test(text))return businessError("invalid_argument","Path parameters cannot contain traversal or encoded routing material.","connector");const reserved=pathname.includes("{+"+key+"}");if(reserved&&!/^[A-Za-z0-9_./-]+$/.test(text))return businessError("invalid_argument","Reserved resource paths must be canonical provider resource names.","connector");pathname=pathname.replace(reserved?"{+"+key+"}":"{"+key+"}",reserved?text.split("/").map(encodeURIComponent).join("/"):encodeURIComponent(text))}else query.set(key,Array.isArray(value)?value.join(","):String(value))}if(pathname.includes("{"))return businessError("invalid_argument","Provider path parameter is missing.","connector");if(input.media)return businessError("failed_precondition","Media upload needs the separately admitted bounded streaming transport; no effect was dispatched.","connector");if(m.id==="youtube.youtube.v3.liveChat.messages.stream")return businessError("failed_precondition","The pinned server-streaming RPC requires an admitted cancelable stream transport; use liveChatMessages.list with pageToken until that profile is enabled.","connector");if(m.httpMethod!=="GET"&&!transport&&!level1)return businessError("failed_precondition","Write transport and original action admission are required for "+id+"; no effect was dispatched.","connector");const url=new URL(pathname,m.baseUrl??"https://www.googleapis.com/");url.search=query.toString();const raw=transport?await transport("youtube",url.href,{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"},signal}):await auth.requestRaw("youtube",url.href,{signal,...level1?{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"}}:{}});if(closed||signal.aborted)return aborted();if(!("ok"in raw))return raw;if(Buffer.byteLength(raw.ok.body,"utf8")>2*1024*1024)return businessError("resource_exhausted","YouTube response exceeds the bounded broker body budget. Use an admitted streaming path; no body was truncated.","connector");const reason=parts.googleErrorReasonV1(raw.ok.body),baseOverride=parts.googleStatusOverrideV1(raw.ok.body),status=parts.webStatusErrorV1(raw.ok.status,{provider:"YouTube",what:id,headers:raw.ok.headers,bodyOverride:status2=>status2===403&&reason==="quotaExceeded"?{code:"resource_exhausted",retryability:"throttling",meaning:"the YouTube project quota bucket is exhausted (quotaExceeded)"}:baseOverride(status2),...reason?{detail:reason}:{}});if(status)return{err:status};if(m.supportsMediaDownload){return Original.ok({method:id,resource:m.resource,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain",items:[{id:input.params.id??input.params.resourceName,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain"}],warnings:[],effect:"read",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}if(raw.ok.status===204||!raw.ok.body)return Original.ok({method:id,resource:m.resource,items:[],warnings:["Provider response carries no body; upstream effect remains unverified."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}});let data;try{data=JSON.parse(raw.ok.body)}catch{return businessError("data_loss","YouTube returned invalid JSON for "+id+".","connector")}if(!object(data))return businessError("data_loss","YouTube response must be an object.","connector");if(data.items!==void 0&&(!Array.isArray(data.items)||data.items.some(item=>!object(item))))return businessError("data_loss","YouTube response items are malformed.","connector");if(data.nextPageToken!==void 0&&(typeof data.nextPageToken!=="string"||!data.nextPageToken||data.nextPageToken.length>6e3))return businessError("data_loss","YouTube nextPageToken is malformed.","connector");const items=Array.isArray(data.items)?data.items:typeof data.id==="string"?[data]:[];return Original.ok({method:id,resource:m.resource,data,items,...typeof data.nextPageToken==="string"?{nextPageToken:data.nextPageToken}:{},warnings:m.httpMethod==="GET"?[]:["HTTP response accepted. Only original action read-after-write/event-confirm can mark EFFECTED."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}function invoke(id,input,options={},level1=false){return track(invokeInner(id,input,options,level1).catch(error=>{if(closed||options.signal?.aborted)return aborted();const cause=object(error)?Original.validateStructuredError(error.structuredError):void 0;return parts.connectorError("unavailable","Trusted YouTube transport failed before a confirmed provider response. Raw custody exception text is not a tool result.","transient",cause&&"ok"in cause?cause.ok:void 0)}))}async function*pages(id,params,options={}){const m=methodMap.get(id);if(!m||m.httpMethod!=="GET"){yield businessError("invalid_argument","Only pinned GET methods can be paginated.","connector");return}if(options.maxPages!==void 0&&(!Number.isInteger(options.maxPages)||options.maxPages<1)){yield businessError("invalid_argument","maxPages must be a positive integer.","connector");return}const seen=new Set;let token=typeof params.pageToken==="string"?params.pageToken:void 0,count=0;for(;;){if(token&&seen.has(token)){yield businessError("failed_precondition","YouTube repeated a page token; coverage is incomplete.","connector");return}if(token)seen.add(token);const result=await invoke(id,{params:{...params,...token?{pageToken:token}:{}}},options);yield result;if(!("ok"in result))return;count++;token=result.ok.nextPageToken;if(!token)return;if(options.maxPages!==void 0&&count>=options.maxPages){yield businessError("resource_exhausted","Selected page budget ended with a nonterminal token; coverage is incomplete.","connector");return}}}async function readInner(request,options={}){if(closed)return unavailable();const bad=validateRead(request,["fileId"]);if(bad)return bad;request=structuredClone(request);if(request.fileId!==void 0&&(!/^[A-Za-z0-9_-]{1,200}$/.test(request.fileId)||request.query!==void 0||request.since!==void 0||request.until!==void 0))return businessError("invalid_argument","An exact YouTube video read takes fileId without query or time bounds.","connector");const selected=request.fileId?"youtube.videos.list":request.query?"youtube.search.list":"youtube.activities.list";const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const connection=await vault.connection("youtube");if(!("ok"in connection))return connection;const captured=structuredClone(connection.ok);if(!captured||captured.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(typeof captured.accountId!=="string"||!captured.accountId.trim())return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");const firstScopes=methodMap.get(selected)?.scopes??[],detailScopes=request.query?methodMap.get("youtube.videos.list")?.scopes??[]:firstScopes,scopes=firstScopes.filter(scope=>detailScopes.includes(scope)),readonly="https://www.googleapis.com/auth/youtube.readonly";const requiredScope=scopes.includes(readonly)&&captured.scopes.includes(readonly)?readonly:scopes.find(scope=>captured.scopes.includes(scope));if(!requiredScope)return businessError("permission_denied","The selected YouTube query requires one of its pinned read scopes.","auth");const fence=async()=>{if(closed||signal.aborted)return aborted();const current=await vault.connection("youtube");if(!("ok"in current))return current;if(!current.ok||current.ok.state!=="connected"||current.ok.account!==captured.account||current.ok.accountId!==captured.accountId||!current.ok.scopes.includes(requiredScope))return businessError("permission_denied","YouTube selected read connection or scope changed.","auth");return Original.ok(void 0)};const boundInvoke=async(id,input)=>{const before=await fence();if(!("ok"in before))return before;const answer2=await invoke(id,input,{signal});const after=await fence();return"ok"in after?answer2:after};const wanted=request.limit??1,params=request.fileId?{part:["snippet","contentDetails","status","statistics"],id:[request.fileId]}:request.query?{part:["snippet"],q:request.query,type:["video"],maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}}:{part:["snippet","contentDetails"],mine:true,maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}};let answer=await boundInvoke(selected,{params});if("err"in answer&&selected==="youtube.activities.list"&&answer.err.code==="permission_denied"){const channels=await boundInvoke("youtube.channels.list",{params:{part:["id"],mine:true,maxResults:1}});if("ok"in channels&&!channels.ok.items.length)return readResult("youtube",[],["This Google account has no YouTube channel, so it has no own activity to read; full sync records it as no-youtube-channel."])}if(!("ok"in answer))return answer;const items=[...answer.ok.items],seen=new Set;let steps=1;while(items.length<wanted&&answer.ok.nextPageToken){const token=answer.ok.nextPageToken;if(seen.has(token))return businessError("failed_precondition","Selected YouTube read repeated a token; no complete result was asserted.","connector");seen.add(token);if(++steps>100)return businessError("resource_exhausted","Selected YouTube read exceeded the page budget before satisfying its limit; no complete result was asserted.","connector");answer=await boundInvoke(selected,{params:{...params,pageToken:token}});if(!("ok"in answer))return answer;items.push(...answer.ok.items)}let retained=items.slice(0,wanted),resource=answer.ok.resource;if(request.query&&retained.length){const selectedItems=retained,details=[];for(let index=0;index<selectedItems.length;index+=50){const block=selectedItems.slice(index,index+50),ids=block.map(item=>object(item.id)?item.id.videoId:void 0).filter(id=>typeof id==="string");if(ids.length!==block.length)return businessError("data_loss","A selected YouTube video search result lacks its native video id.","connector");const hydrated=await boundInvoke("youtube.videos.list",{params:{part:["snippet","contentDetails","status","statistics","topicDetails","recordingDetails","localizations"],id:ids}});if(!("ok"in hydrated))return hydrated;for(const item of hydrated.ok.items)details.push({...item,_selection:block.find(selected2=>object(selected2.id)&&selected2.id.videoId===item.id)??null})}retained=details;resource="videos"}const records=retained.map(item=>({source:"youtube",sourceId:captured.accountId+":"+resource+":"+itemId(item),stream:resource,kind:"youtube."+resource.toLowerCase()+".changed",ts:itemTime(item),body:JSON.stringify(item),fields:{...item}}));const beforeReturn=await fence();if(!("ok"in beforeReturn))return beforeReturn;if(closed||signal.aborted)return aborted();return readResult("youtube",records,[...answer.ok.warnings,...answer.ok.nextPageToken||items.length>wanted?["More provider results exist beyond this selected batch."]:[],...retained.length<Math.min(items.length,wanted)?["Some selected videos are currently inaccessible/deleted; search metadata is retained only as an attributed missing detail, never a fabricated video body."]:[],"This selected API query does not establish complete YouTube account or archive coverage."])}function read(request,options={}){return track(readInner(request,options))}async function importTakeout(root=takeoutRoot??"",options={}){if(closed)return unavailable();if(!root)return businessError("failed_precondition","Supply an explicit extracted read-only Takeout copy; API success cannot substitute for history.","connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;const result=await readTakeout(root,signal);if(!("ok"in result))return result;if(closed||signal.aborted)return aborted();const saved=await cache(vault,"youtube",result.ok.records);if(!("ok"in saved))return saved;return result}const account=async()=>{const row=await vault.connection("youtube");if(!("ok"in row))return row;if(!row.ok||row.ok.state!=="connected")return businessError("unauthenticated","YouTube identity needs a connected account.","auth");if(!row.ok.accountId)return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");return Original.ok(row.ok.accountId)};function actionSchema(schema){const{id:_discoveryType,...result}=schema;if(result.properties)result.properties=Object.fromEntries(Object.entries(result.properties).map(([key,value])=>[key,actionSchema(value)]));if(result.items)result.items=actionSchema(result.items);if(object(result.additionalProperties))result.additionalProperties=actionSchema(result.additionalProperties);return result}const actions={catalog,method:id=>{const result=method(id);if(!("ok"in result))return result;const m=result.ok;return Original.ok({...m,params:actionSchema(m.params),...!m.supportsMediaUpload&&m.id!=="youtube.youtube.v3.liveChat.messages.stream"&&(!m.profile||m.httpMethod==="GET")?{level:1,effect:m.httpMethod==="GET"?"read":"write"}:{}})},invoke:(id,input,options={})=>invoke(id,input,options,true)};const source={info,actions,catalog,method,invoke,pages,read,status:()=>closed?Promise.resolve(Original.ok({...info,state:"unavailable",message:"YouTube source is inactive."})):connectionState(vault,info),connect:options=>closed?Promise.resolve(unavailable()):track(auth.connect("youtube",options)),job:id=>closed?unavailable():auth.job(id),cancelJob:id=>auth.cancelJob(id),importTakeout:(root,options)=>track(importTakeout(root,options)),createConnector:(plan,options={})=>createYouTubeConnector({parts,invoke,method,account,isClosed:()=>closed},plan,options),async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}};return source}export function itemId(item){if(typeof item.id==="string")return item.id;if(typeof item.videoId==="string")return item.videoId;if(object(item.id)){for(const key of["videoId","channelId","playlistId"])if(typeof item.id[key]==="string")return key+":"+item.id[key]}const value=JSON.parse(JSON.stringify(item.id??item));return createHash("sha256").update(Original.jcsCanonicalize(value)).digest("hex")}export function itemTime(item){const snippet=object(item.snippet)?item.snippet:{};for(const value of[item.time,item.updated,item.updatedAt,snippet.updatedAt,snippet.publishedAt])if(typeof value==="string"&&Number.isFinite(Date.parse(value)))return new Date(value).toISOString();return"1970-01-01T00:00:00.000Z"}
|