@redocly/framework-plugin-apigee 0.0.1 → 0.1.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +103 -0
  3. package/lib/.tsbuildinfo +1 -0
  4. package/lib/client/ApigeeTemplate.d.ts +24 -0
  5. package/lib/client/ApigeeTemplate.js +1 -0
  6. package/lib/client/Primitives.d.ts +84 -0
  7. package/lib/client/Primitives.js +372 -0
  8. package/lib/client/api.d.ts +28 -0
  9. package/lib/client/api.js +1 -0
  10. package/lib/client/context.d.ts +12 -0
  11. package/lib/client/context.js +1 -0
  12. package/lib/client/hooks.d.ts +21 -0
  13. package/lib/client/hooks.js +1 -0
  14. package/lib/client/views/AdminView.d.ts +2 -0
  15. package/lib/client/views/AdminView.js +21 -0
  16. package/lib/client/views/AppsView.d.ts +11 -0
  17. package/lib/client/views/AppsView.js +1 -0
  18. package/lib/client/views/Dialogs.d.ts +49 -0
  19. package/lib/client/views/Dialogs.js +1 -0
  20. package/lib/client/views/TeamsView.d.ts +10 -0
  21. package/lib/client/views/TeamsView.js +1 -0
  22. package/lib/config.d.ts +31 -0
  23. package/lib/config.js +1 -0
  24. package/lib/constants.d.ts +37 -0
  25. package/lib/constants.js +1 -0
  26. package/lib/contract.d.ts +182 -0
  27. package/lib/contract.js +1 -0
  28. package/lib/plugin.d.ts +10 -0
  29. package/lib/plugin.js +1 -0
  30. package/lib/server/apigee-types.d.ts +72 -0
  31. package/lib/server/apigee-types.js +0 -0
  32. package/lib/server/client.d.ts +60 -0
  33. package/lib/server/client.js +1 -0
  34. package/lib/server/mappers.d.ts +10 -0
  35. package/lib/server/mappers.js +1 -0
  36. package/lib/server/routes.d.ts +25 -0
  37. package/lib/server/routes.js +1 -0
  38. package/lib/server/service.d.ts +93 -0
  39. package/lib/server/service.js +1 -0
  40. package/lib/server/store.d.ts +38 -0
  41. package/lib/server/store.js +1 -0
  42. package/lib/server/token.d.ts +13 -0
  43. package/lib/server/token.js +2 -0
  44. package/package.json +57 -3
@@ -0,0 +1 @@
1
+ var i=function(e,t,o,d){function v(a){return a instanceof o?a:new o(function(l){l(a)})}return new(o||(o=Promise))(function(a,l){function y(c){try{b(d.next(c))}catch(h){l(h)}}function g(c){try{b(d.throw(c))}catch(h){l(h)}}function b(c){c.done?a(c.value):v(c.value).then(y,g)}b((d=d.apply(e,t||[])).next())})};import{resolveApigeeSettings as A}from"../config.js";import{ApigeeApiError as q,ApigeeClient as x}from"./client.js";import{ApigeeService as T,ForbiddenError as I,NotFoundError as S,ValidationError as w}from"./service.js";import{ApigeeTokenError as E,createTokenProvider as R}from"./token.js";const f={"Cache-Control":"no-store"};function u(e,t,o){return e.json({error:o,status:t},t,f)}function r(e,t,o=200){return e.json(t,o,f)}function j(e){const t=e.req.header("sec-fetch-site");return t!==void 0&&t!=="same-origin"&&t!=="none"}function K(e,t,o){var d,v,a;if(t instanceof w)return u(e,400,t.message);if(t instanceof I)return u(e,403,t.message);if(t instanceof S)return u(e,404,t.message);if(t instanceof q){(d=o.logger)===null||d===void 0||d.warn(`apigee: management API answered ${t.status}: ${t.message}`);const l=t.status>=500||t.status===401||t.status===403?502:t.status;return u(e,l,t.message)}return t instanceof E?((v=o.logger)===null||v===void 0||v.error(`apigee: ${t.message}`),u(e,502,"Apigee is not reachable with the configured credentials")):((a=o.logger)===null||a===void 0||a.error(`apigee: unexpected error: ${String(t)}`),u(e,500,"Something went wrong"))}function s(e,t){const o=e.req.param(t);if(o===void 0)throw new w(`Missing ${t}`);return o}function p(e){return i(this,void 0,void 0,function*(){const t=yield e.req.json().catch(()=>null);if(!t||typeof t!="object"||Array.isArray(t))throw new w("The request body must be a JSON object");return t})}function n(e,t={}){return(o,d)=>i(this,void 0,void 0,function*(){const v=A(d.config);if(!v)return u(o,404,"Apigee is not configured");if(t.review&&!v.approvalsEnabled)return u(o,404,"Approvals are not enabled");const a=d.request.viewer;if(!a?.isAuthenticated||!a.email)return u(o,401,"Sign in to manage your apps");if(!d.isSlugVisible(v.basePath))return u(o,403,"You do not have access to this page");if(o.req.method!=="GET"&&j(o))return u(o,403,"Cross-site requests are refused");const l=new x(v,R(v.auth)),y=new T(v,l,a,d,d.logger);try{return t.review&&!(yield y.canReview())?u(o,403,"You cannot review access requests"):yield e(o,y)}catch(g){return K(o,g,d)}})}const m=e=>e.req.query("team")||void 0,C=n((e,t)=>i(void 0,void 0,void 0,function*(){const o=yield t.listApiProducts();return r(e,{organizationName:t.settings.organizationName,stage:t.settings.stage,basePath:t.settings.basePath,teamsEnabled:t.settings.teamsEnabled,approvals:yield t.approvalSummary(),viewer:Object.assign({email:t.email},t.viewer.name?{name:t.viewer.name}:{}),apiProducts:o})})),N=n((e,t)=>i(void 0,void 0,void 0,function*(){const o=e.req.query("apiId");return o?r(e,yield t.getAccess(o)):u(e,400,"apiId is required")})),$=n((e,t)=>i(void 0,void 0,void 0,function*(){return r(e,yield t.listApps())})),O=n((e,t)=>i(void 0,void 0,void 0,function*(){const o=yield p(e);return r(e,yield t.createApp(o),201)})),z=n((e,t)=>i(void 0,void 0,void 0,function*(){const o=yield p(e);return r(e,yield t.updateApp(m(e),s(e,"appId"),o))})),F=n((e,t)=>i(void 0,void 0,void 0,function*(){return yield t.deleteApp(m(e),s(e,"appId")),e.body(null,204,f)})),J=n((e,t)=>i(void 0,void 0,void 0,function*(){const o=yield p(e);return r(e,yield t.createKey(m(e),s(e,"appId"),o),201)})),V=n((e,t)=>i(void 0,void 0,void 0,function*(){const o=yield p(e);return r(e,yield t.updateKeyProducts(m(e),s(e,"appId"),s(e,"consumerKey"),o))})),Y=n((e,t)=>i(void 0,void 0,void 0,function*(){return yield t.deleteKey(m(e),s(e,"appId"),s(e,"consumerKey")),e.body(null,204,f)})),G=n((e,t)=>i(void 0,void 0,void 0,function*(){return r(e,yield t.listMyTeams())})),Q=n((e,t)=>i(void 0,void 0,void 0,function*(){const o=yield p(e);return r(e,yield t.createTeam(o),201)})),B=n((e,t)=>i(void 0,void 0,void 0,function*(){return r(e,yield t.getTeam(s(e,"teamId")))})),D=n((e,t)=>i(void 0,void 0,void 0,function*(){const o=yield p(e);return r(e,yield t.updateTeam(s(e,"teamId"),o))})),H=n((e,t)=>i(void 0,void 0,void 0,function*(){return yield t.deleteTeam(s(e,"teamId")),e.body(null,204,f)})),L=n((e,t)=>i(void 0,void 0,void 0,function*(){const o=yield p(e);return r(e,yield t.addMember(s(e,"teamId"),o),201)})),U=n((e,t)=>i(void 0,void 0,void 0,function*(){const o=yield p(e);return r(e,yield t.setMemberRole(s(e,"teamId"),s(e,"email"),o.role))})),W=n((e,t)=>i(void 0,void 0,void 0,function*(){return r(e,yield t.removeMember(s(e,"teamId"),s(e,"email")))})),X=n((e,t)=>i(void 0,void 0,void 0,function*(){return r(e,yield t.listRequests())}),{review:!0}),Z=n((e,t)=>i(void 0,void 0,void 0,function*(){const o=yield e.req.json().catch(()=>({})),d=typeof o?.note=="string"?o.note:void 0;return r(e,yield t.decideRequest(s(e,"requestId"),"approve",d))}),{review:!0}),ee=n((e,t)=>i(void 0,void 0,void 0,function*(){const o=yield e.req.json().catch(()=>({})),d=typeof o?.note=="string"?o.note:void 0;return r(e,yield t.decideRequest(s(e,"requestId"),"revoke",d))}),{review:!0}),te=n((e,t)=>i(void 0,void 0,void 0,function*(){return r(e,yield t.listAllApps())}),{review:!0}),oe=n((e,t)=>i(void 0,void 0,void 0,function*(){return r(e,yield t.listAudit())}),{review:!0});export{N as access,L as addTeamMember,Z as adminApprove,te as adminApps,oe as adminAudit,X as adminRequests,ee as adminRevoke,O as createApp,J as createKey,Q as createTeam,F as deleteApp,Y as deleteKey,H as deleteTeam,B as getTeam,$ as listApps,G as listTeams,C as meta,W as removeTeamMember,z as updateApp,V as updateKey,D as updateTeam,U as updateTeamMember};
@@ -0,0 +1,93 @@
1
+ import type { ServerRouteContext } from '@redocly/framework/plugin';
2
+ import type { ApigeeSettings } from '../config.js';
3
+ import type { AccessRequest, AdminApp, ApiAccess, ApiProduct, ApprovalsSummary, App, AppInput, AppOwner, AppUpdateInput, AuditEntry, Credential, KeyInput, Team, TeamInput, TeamMemberInput, TeamRole } from '../contract.js';
4
+ import { type AppOwnerPath, type ApigeeClient, type KeyAction } from './client.js';
5
+ import { ApigeeStore } from './store.js';
6
+ export declare class ValidationError extends Error {
7
+ name: string;
8
+ }
9
+ export declare class ForbiddenError extends Error {
10
+ name: string;
11
+ }
12
+ export declare class NotFoundError extends Error {
13
+ name: string;
14
+ }
15
+ export type ProductPage = {
16
+ slug: string;
17
+ title: string;
18
+ };
19
+ /** The API pages that document Apigee products: by product name (`apiId` metadata) and by lower-cased title. */
20
+ export type ProductPages = {
21
+ byApiId: Record<string, ProductPage>;
22
+ byTitle: Record<string, ProductPage>;
23
+ };
24
+ export type RouteRole = ReturnType<ServerRouteContext['roleForSlug']>;
25
+ type Viewer = NonNullable<ServerRouteContext['request']['viewer']>;
26
+ type Logger = NonNullable<ServerRouteContext['logger']>;
27
+ export type AuthenticatedViewer = Viewer & {
28
+ email: string;
29
+ };
30
+ export declare class ApigeeService {
31
+ #private;
32
+ readonly settings: ApigeeSettings;
33
+ readonly client: ApigeeClient;
34
+ readonly viewer: AuthenticatedViewer;
35
+ private readonly ctx;
36
+ private readonly logger?;
37
+ readonly store: ApigeeStore;
38
+ constructor(settings: ApigeeSettings, client: ApigeeClient, viewer: AuthenticatedViewer, ctx: Pick<ServerRouteContext, 'entities' | 'isSlugVisible' | 'roleForSlug' | 'kv' | 'request'>, logger?: Logger | undefined);
39
+ get email(): string;
40
+ private apigeeProducts;
41
+ private productPages;
42
+ /** The page documenting `product`: by `apiId`, else by title when the config allows it. */
43
+ private pageFor;
44
+ /** The viewer's role for `productName`: the higher of its page's role and the apps page's role. */
45
+ private roleFor;
46
+ approvalSummary(): Promise<ApprovalsSummary>;
47
+ canReview(): Promise<boolean>;
48
+ /** The products this viewer may request: offered by config and documented by a page they can open. */
49
+ listApiProducts(): Promise<ApiProduct[]>;
50
+ private assertProductsAllowed;
51
+ resolveOwner(teamId: string | undefined): Promise<{
52
+ owner: AppOwner;
53
+ path: AppOwnerPath;
54
+ }>;
55
+ private ownerPath;
56
+ /** Adds the reviewers' decisions to the product statuses of every key. */
57
+ private withDecisions;
58
+ listApps(): Promise<App[]>;
59
+ private appsOf;
60
+ createApp(input: AppInput): Promise<App>;
61
+ updateApp(teamId: string | undefined, appId: string, input: AppUpdateInput): Promise<App>;
62
+ deleteApp(teamId: string | undefined, appId: string): Promise<void>;
63
+ createKey(teamId: string | undefined, appId: string, input: KeyInput): Promise<Credential>;
64
+ updateKeyProducts(teamId: string | undefined, appId: string, consumerKey: string, input: KeyInput): Promise<Credential>;
65
+ deleteKey(teamId: string | undefined, appId: string, consumerKey: string): Promise<void>;
66
+ private recordRequestNotes;
67
+ getAccess(apiProduct: string): Promise<ApiAccess>;
68
+ /** Enabled by config and backed by AppGroups, which Apigee Edge does not have. */
69
+ private assertTeams;
70
+ private withRole;
71
+ /** The teams whose AppGroup lists the viewer, read from every AppGroup of the organization. */
72
+ listMyTeams(): Promise<Team[]>;
73
+ /** The teams in the viewer's KV index whose AppGroup still lists them, without reading every AppGroup. */
74
+ private indexedTeams;
75
+ private requireTeam;
76
+ getTeam(teamId: string): Promise<Team>;
77
+ createTeam(input: TeamInput): Promise<Team>;
78
+ updateTeam(teamId: string, input: TeamInput): Promise<Team>;
79
+ deleteTeam(teamId: string): Promise<void>;
80
+ addMember(teamId: string, input: TeamMemberInput): Promise<Team>;
81
+ setMemberRole(teamId: string, email: string, role: TeamRole): Promise<Team>;
82
+ /** An owner removes anyone; a member may leave. */
83
+ removeMember(teamId: string, email: string): Promise<Team>;
84
+ private syncAppGroup;
85
+ private ownerOf;
86
+ /** Requests for the products the viewer may review, newest first. */
87
+ listRequests(): Promise<AccessRequest[]>;
88
+ decideRequest(requestId: string, action: KeyAction, note?: string): Promise<AuditEntry>;
89
+ /** Every app a reviewer of all products sees; a product reviewer sees the apps holding that product. */
90
+ listAllApps(): Promise<AdminApp[]>;
91
+ listAudit(): Promise<AuditEntry[]>;
92
+ }
93
+ export {};
@@ -0,0 +1 @@
1
+ var u=function(s,e,i,t){function r(n){return n instanceof i?n:new i(function(o){o(n)})}return new(i||(i=Promise))(function(n,o){function a(l){try{c(t.next(l))}catch(p){o(p)}}function d(l){try{c(t.throw(l))}catch(p){o(p)}}function c(l){l.done?n(l.value):r(l.value).then(a,d)}c((t=t.apply(s,e||[])).next())})},x=function(s,e,i,t){if(i==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!t:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return i==="m"?t:i==="a"?t.call(s):t?t.value:e.get(s)},B=function(s,e,i,t,r){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?r.call(s,i):r?r.value=i:e.set(s,i),i},D=function(s,e){var i={};for(var t in s)Object.prototype.hasOwnProperty.call(s,t)&&e.indexOf(t)<0&&(i[t]=s[t]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(s);r<t.length;r++)e.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(s,t[r])&&(i[t[r]]=s[t[r]]);return i},R,j;import{createHash as ie,randomBytes as re}from"node:crypto";import{isApiProductOffered as C}from"../config.js";import{APIGEE_DEFAULT_KEY_LIFETIME_SECONDS as $,APIGEE_DISPLAY_NAME_ATTRIBUTE as I,APIGEE_NOTES_ATTRIBUTE as k,APIGEE_PRODUCTS_ENTITY_KEY as ne,APIGEE_PRODUCTS_VALUE_KEY as oe,APIGEE_TEAM_MEMBERS_ATTRIBUTE as F}from"../constants.js";import{maskKey as L}from"../contract.js";import{ApigeeApiError as se}from"./client.js";import{attributesToRecord as O,recordToAttributes as K,toApiProduct as V,toApp as N,toCredential as z}from"./mappers.js";import{ApigeeStore as ae,normalizeEmail as _}from"./store.js";class v extends Error{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ValidationError"})}}class S extends Error{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ForbiddenError"})}}class b extends Error{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"NotFoundError"})}}const de={byApiId:{},byTitle:{}},E={none:0,read:1,triage:2,write:3,maintain:4,admin:5};function T(s){return E[s]>=E.triage}function G(s){return E[s]>=E.maintain}function le(s,e){return E[s]>=E[e]?s:e}const ce=/^[A-Za-z0-9._$ -]{1,100}$/,ue=new Set(["teams","admin"]),pe=/^[a-z0-9][a-z0-9-]{1,62}$/,P=2e3,me=2048;function he(s){return Buffer.from(JSON.stringify(s)).toString("base64url")}function Y(s){return ie("sha256").update(s).digest("base64url")}function fe(s){try{const e=JSON.parse(Buffer.from(s,"base64url").toString());if(!e||typeof e.appId!="string"||typeof e.keyDigest!="string"||typeof e.apiProduct!="string"||!e.owner)throw new Error("shape");return e}catch{throw new v("Unknown request")}}function ve(s){return s.trim().toLowerCase().split(/[^a-z0-9]/).filter(Boolean).join("-").slice(0,63)}function we(s){var e,i,t,r;const n=((i=s.name)!==null&&i!==void 0?i:"").trim().split(/\s+/).filter(Boolean),o=(r=(e=((t=s.email)!==null&&t!==void 0?t:"").split("@")[0])===null||e===void 0?void 0:e.split(/[.-]/))!==null&&r!==void 0?r:[];return{firstName:n[0]||o[0]||"Unknown",lastName:n.slice(1).join(" ")||o[1]||"Unknown"}}function H(s){return re(s).toString("base64url")}function J(s,e){const i=O(s.attributes)[F];if(!i)return[];try{const t=JSON.parse(i);return Array.isArray(t)?t.flatMap(r=>{var n,o;if(typeof r?.developer!="string")return[];const a=_(r.developer),d=e?.members.find(c=>c.email===a);return[{email:a,role:!((n=r.roles)===null||n===void 0)&&n.includes("owner")?"owner":"member",addedAt:(o=d?.addedAt)!==null&&o!==void 0?o:Number(s.createdAt)||0}]}):[]}catch{return[]}}function U(s,e){var i,t,r,n;const o=J(s,e);return{id:s.name,name:s.displayName||s.name,description:(t=O(s.attributes)[k])!==null&&t!==void 0?t:"",createdAt:Number(s.createdAt)||e?.createdAt||Date.now(),createdBy:(n=(r=e?.createdBy)!==null&&r!==void 0?r:(i=o.find(a=>a.role==="owner"))===null||i===void 0?void 0:i.email)!==null&&n!==void 0?n:"",members:o}}function W(s){return JSON.stringify(s.map(e=>({developer:e.email,roles:[e.role]})))}class Te{constructor(e,i,t,r,n){Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"viewer",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"ctx",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"store",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),R.set(this,void 0),j.set(this,void 0),this.store=new ae(r.kv)}get email(){return _(this.viewer.email)}apigeeProducts(){var e;return B(this,R,(e=x(this,R,"f"))!==null&&e!==void 0?e:this.client.listApiProducts(),"f"),x(this,R,"f")}productPages(){var e;return B(this,j,(e=x(this,j,"f"))!==null&&e!==void 0?e:this.ctx.entities.load(ne).then(i=>{var t;return(t=i?.[oe])!==null&&t!==void 0?t:de}),"f"),x(this,j,"f")}pageFor(e,i){const t=i.byApiId[e.name];if(t||!this.settings.apiProducts.matchByTitle)return t;const r=(e.displayName||e.name).trim().toLowerCase();return i.byTitle[r]}roleFor(e,i,t){const r=t.find(a=>a.name===e),n=r?this.pageFor(r,i):i.byApiId[e],o=n?this.ctx.roleForSlug(n.slug):"none";return le(o,this.ctx.roleForSlug(this.settings.basePath))}approvalSummary(){return u(this,void 0,void 0,function*(){if(!this.settings.approvalsEnabled)return{enabled:!1,canView:!1,canDecide:!1};const e=this.ctx.roleForSlug(this.settings.basePath);if(G(e))return{enabled:!0,canView:!0,canDecide:!0};const[i,t]=yield Promise.all([this.apigeeProducts(),this.productPages()]);let r=T(e),n=!1;for(const o of i){if(!C(this.settings,o.name))continue;const a=this.roleFor(o.name,t,i);r||(r=T(a)),n||(n=G(a))}return{enabled:!0,canView:r,canDecide:n}})}canReview(){return u(this,void 0,void 0,function*(){return(yield this.approvalSummary()).canView})}listApiProducts(){return u(this,void 0,void 0,function*(){const[e,i]=yield Promise.all([this.apigeeProducts(),this.productPages()]),t=[];for(const r of e){if(!C(this.settings,r.name))continue;const n=this.pageFor(r,i);if(n){if(!this.ctx.isSlugVisible(n.slug))continue;t.push(V(r,n))}else this.settings.apiProducts.allowOutsideCatalog&&t.push(V(r))}return t.sort((r,n)=>r.name.localeCompare(n.name))})}assertProductsAllowed(e){return u(this,void 0,void 0,function*(){const i=Z(e),t=yield this.listApiProducts(),r=i.filter(o=>!t.some(a=>a.id===o));if(r.length>0)throw new v(`Unknown API product: ${r.join(", ")}`);const n=new Map(t.map(o=>[o.id,o]));return[...new Set(i)].flatMap(o=>{const a=n.get(o);return a?[a]:[]})})}resolveOwner(e){return u(this,void 0,void 0,function*(){if(!e)return{owner:{kind:"developer",email:this.email},path:{kind:"developer",email:this.email}};const i=yield this.requireTeam(e);return{owner:{kind:"team",teamId:i.id},path:{kind:"appgroup",name:i.id}}})}ownerPath(e){return e.kind==="developer"?{kind:"developer",email:e.email}:{kind:"appgroup",name:e.teamId}}withDecisions(e){return u(this,void 0,void 0,function*(){const i=[];for(const n of e)for(const o of n.credentials)for(const a of o.apiProducts)i.push({owner:n.owner,appId:n.id,consumerKey:o.consumerKey,apiProduct:a.id});const t=yield this.store.getDecisions(i);let r=0;for(const n of e)for(const o of n.credentials)for(const a of o.apiProducts){const d=t[r++];d&&(a.decision=d)}return e})}listApps(){return u(this,void 0,void 0,function*(){return this.appsOf(yield this.listMyTeams())})}appsOf(e){return u(this,void 0,void 0,function*(){const[i,...t]=yield Promise.all([this.client.listApps({kind:"developer",email:this.email}),...e.map(n=>this.client.listApps({kind:"appgroup",name:n.id}))]),r=i.map(n=>N(n,{kind:"developer",email:this.email}));return e.forEach((n,o)=>{r.push(...t[o].map(a=>N(a,{kind:"team",teamId:n.id})))}),this.withDecisions(r.sort((n,o)=>{var a,d;return((a=o.createdAt)!==null&&a!==void 0?a:0)-((d=n.createdAt)!==null&&d!==void 0?d:0)}))})}createApp(e){return u(this,void 0,void 0,function*(){var i;const t=Q(e.name),r=g(e.description,P,"description"),n=ee(e.callbackUrl),o=g(e.note,P,"note"),a=yield this.assertProductsAllowed((i=e.apiProducts)!==null&&i!==void 0?i:[]),{owner:d,path:c}=yield this.resolveOwner(e.teamId);if(d.kind==="developer"&&(yield this.client.ensureDeveloper(Object.assign({email:this.email,userName:this.email},we(this.viewer)))),yield this.client.getApp(c,t))throw new v(`An app named "${t}" already exists`);const l=yield this.client.createApp(c,Object.assign(Object.assign({name:t,apiProducts:a.map(h=>h.id)},n?{callbackUrl:n}:{}),{keyExpiresIn:String($*(d.kind==="developer"?1e3:1)),attributes:K({[I]:t,[k]:r??""})})),p=N(l,d);return yield this.recordRequestNotes(d,p.id,p.credentials,a,o),p})}updateApp(e,i,t){return u(this,void 0,void 0,function*(){var r;const{owner:n,path:o}=yield this.resolveOwner(e),a=yield this.client.getApp(o,i);if(!a)throw new b("App not found");const d=O(a.attributes);t.name!==void 0&&(d[I]=Q(t.name)),t.description!==void 0&&(d[k]=(r=g(t.description,P,"description"))!==null&&r!==void 0?r:"");const c=t.callbackUrl===void 0?a.callbackUrl:ee(t.callbackUrl),l=yield this.client.updateApp(o,i,Object.assign({attributes:K(d)},c!==void 0?{callbackUrl:c}:{}));return N(l,n)})}deleteApp(e,i){return u(this,void 0,void 0,function*(){const{path:t}=yield this.resolveOwner(e);if(!(yield this.client.getApp(t,i)))throw new b("App not found");yield this.client.deleteApp(t,i)})}createKey(e,i,t){return u(this,void 0,void 0,function*(){var r;const{owner:n,path:o}=yield this.resolveOwner(e);if(!(yield this.client.getApp(o,i)))throw new b("App not found");const a=yield this.assertProductsAllowed((r=t.apiProducts)!==null&&r!==void 0?r:[]),d=g(t.note,P,"note"),c=yield this.client.createKey(o,i,{consumerKey:H(24),consumerSecret:H(24),expiresInSeconds:$}),l=a.length>0?yield this.client.addKeyProducts(o,i,c.consumerKey,a.map(h=>h.id),c.attributes):c,p=z(l);return yield this.recordRequestNotes(n,i,[p],a,d),p})}updateKeyProducts(e,i,t,r){return u(this,void 0,void 0,function*(){var n,o;const{owner:a,path:d}=yield this.resolveOwner(e),c=yield this.client.getKey(d,i,t);if(!c)throw new b("Key not found");const l=new Set(((n=c.apiProducts)!==null&&n!==void 0?n:[]).map(y=>y.apiproduct)),p=Z((o=r.apiProducts)!==null&&o!==void 0?o:[]),h=yield this.assertProductsAllowed(p.filter(y=>!l.has(y))),w=g(r.note,P,"note"),m=[...l].filter(y=>!p.includes(y));let f=c;h.length>0&&(f=yield this.client.addKeyProducts(d,i,t,h.map(y=>y.id),c.attributes));for(const y of m)yield this.client.removeKeyProduct(d,i,t,y),yield this.store.deleteRequestNote({owner:a,appId:i,consumerKey:t,apiProduct:y}),yield this.store.deleteDecision({owner:a,appId:i,consumerKey:t,apiProduct:y});const A=m.length>0?yield this.client.getKey(d,i,t):null,q=z(A??f);return yield this.recordRequestNotes(a,i,[q],h,w),q})}deleteKey(e,i,t){return u(this,void 0,void 0,function*(){const{path:r}=yield this.resolveOwner(e);if(!(yield this.client.getKey(r,i,t)))throw new b("Key not found");yield this.client.deleteKey(r,i,t)})}recordRequestNotes(e,i,t,r,n){return u(this,void 0,void 0,function*(){const o=r.filter(d=>d.approvalType==="manual");if(o.length===0)return;const a=Date.now();for(const d of t)for(const c of o)yield this.store.putRequestNote({owner:e,appId:i,consumerKey:d.consumerKey,apiProduct:c.id},Object.assign({requestedBy:this.email,requestedAt:a},n?{note:n}:{}))})}getAccess(e){return u(this,void 0,void 0,function*(){const i=yield this.appsOf(yield this.indexedTeams()),t=Date.now(),r=o=>i.flatMap(a=>a.credentials.filter(d=>a.status!=="revoked"&&d.status==="approved"&&(d.expiresAt===null||d.expiresAt>t)&&d.apiProducts.some(c=>c.id===e&&c.status===o)).map(d=>({app:a,credential:d}))),n=r("approved").sort((o,a)=>o.app.owner.kind===a.app.owner.kind?0:o.app.owner.kind==="developer"?-1:1);if(n.length>0){const{credential:o}=n[0];return{status:"APPROVED",link:this.settings.basePath,requestValues:{security:{default:Object.assign({client_id:o.consumerKey},o.consumerSecret?{client_secret:o.consumerSecret}:{})}}}}return{status:r("pending").length>0?"PENDING":"NONE",link:`${this.settings.basePath}?createApp&apiProduct=${encodeURIComponent(e)}`}})}assertTeams(){if(!this.settings.teamsEnabled)throw new S("Teams are disabled")}withRole(e){const i=e.members.find(t=>t.email===this.email);return i?Object.assign(Object.assign({},e),{myRole:i.role}):e}listMyTeams(){return u(this,void 0,void 0,function*(){var e,i;if(!this.settings.teamsEnabled)return[];let t;try{t=yield this.client.listAppGroups()}catch(o){return(e=this.logger)===null||e===void 0||e.debug(`apigee: AppGroups unavailable: ${String(o)}`),[]}const r=new Map((yield this.store.listTeamsOf(this.email)).map(o=>[o.id,o])),n=[];for(const o of t){if(!J(o).some(d=>d.email===this.email))continue;const a=U(o,(i=r.get(o.name))!==null&&i!==void 0?i:yield this.store.getTeam(o.name));r.has(a.id)||(yield this.store.putTeam(a)),n.push(this.withRole(a))}return n.sort((o,a)=>o.name.localeCompare(a.name))})}indexedTeams(){return u(this,void 0,void 0,function*(){if(!this.settings.teamsEnabled)return[];const e=yield this.store.listTeamsOf(this.email);return(yield Promise.all(e.map(t=>this.client.getAppGroup(t.id)))).flatMap((t,r)=>{const n=t?this.withRole(U(t,e[r])):null;return n?.myRole?[n]:[]})})}requireTeam(e,i){return u(this,void 0,void 0,function*(){this.assertTeams();const[t,r]=yield Promise.all([this.client.getAppGroup(e),this.store.getTeam(e)]);if(!t)throw new b("Team not found");const n=this.withRole(U(t,r));if(!n.myRole)throw new S("You are not a member of this team");if(i==="owner"&&n.myRole!=="owner")throw new S("Only a team owner can do this");return n})}getTeam(e){return u(this,void 0,void 0,function*(){return this.requireTeam(e)})}createTeam(e){return u(this,void 0,void 0,function*(){var i;this.assertTeams();const t=g(e.name,100,"name");if(!t)throw new v("A team needs a name");const r=ve(t);if(!pe.test(r))throw new v("The team name needs at least two letters or digits");const n=(i=g(e.description,P,"description"))!==null&&i!==void 0?i:"";if((yield this.store.getTeam(r))||(yield this.client.getAppGroup(r)))throw new v(`A team named "${t}" already exists`);const o=[{email:this.email,role:"owner",addedAt:Date.now()}];yield this.client.createAppGroup({name:r,displayName:t,attributes:K({[k]:n,[F]:W(o)})});const a={id:r,name:t,description:n,createdAt:Date.now(),createdBy:this.email,members:o};return yield this.store.putTeam(a),this.withRole(a)})}updateTeam(e,i){return u(this,void 0,void 0,function*(){var t;const r=yield this.requireTeam(e,"owner"),n=g(i.name,100,"name")||r.name,o=(t=g(i.description,P,"description"))!==null&&t!==void 0?t:r.description,a=Object.assign(Object.assign({},M(r)),{name:n,description:o});return yield this.syncAppGroup(a),yield this.store.putTeam(a),this.withRole(a)})}deleteTeam(e){return u(this,void 0,void 0,function*(){const i=yield this.requireTeam(e,"owner"),t={kind:"appgroup",name:i.id};for(const r of yield this.client.listApps(t))yield this.client.deleteApp(t,r.name);try{yield this.client.deleteAppGroup(i.id)}catch(r){if(!(r instanceof se&&r.status===404))throw r}yield this.store.deleteTeam(i.id)})}addMember(e,i){return u(this,void 0,void 0,function*(){const t=yield this.requireTeam(e,"owner"),r=ye(i.email),n=te(i.role);if(t.members.some(a=>a.email===r))throw new v(`${r} is already a member`);const o=Object.assign(Object.assign({},M(t)),{members:[...t.members,{email:r,role:n,addedAt:Date.now()}]});return yield this.syncAppGroup(o),yield this.store.putTeam(o),this.withRole(o)})}setMemberRole(e,i,t){return u(this,void 0,void 0,function*(){const r=yield this.requireTeam(e,"owner"),n=_(i);if(!r.members.some(d=>d.email===n))throw new b("Member not found");const o=r.members.map(d=>d.email===n?Object.assign(Object.assign({},d),{role:te(t)}):d);X(o);const a=Object.assign(Object.assign({},M(r)),{members:o});return yield this.syncAppGroup(a),yield this.store.putTeam(a),this.withRole(a)})}removeMember(e,i){return u(this,void 0,void 0,function*(){const t=yield this.requireTeam(e),r=_(i);if(t.myRole!=="owner"&&r!==this.email)throw new S("Only a team owner can remove other members");if(!t.members.some(a=>a.email===r))throw new b("Member not found");const n=t.members.filter(a=>a.email!==r);X(n);const o=Object.assign(Object.assign({},M(t)),{members:n});return yield this.syncAppGroup(o),yield this.store.putTeam(o),this.withRole(o)})}syncAppGroup(e){return u(this,void 0,void 0,function*(){const i=yield this.client.getAppGroup(e.id);if(!i)throw new b("Team not found");const t=Object.assign(Object.assign({},O(i.attributes)),{[k]:e.description,[F]:W(e.members)});yield this.client.updateAppGroup(e.id,Object.assign(Object.assign({},i),{name:e.id,displayName:e.name,attributes:K(t)}))})}ownerOf(e,i){return u(this,void 0,void 0,function*(){var t;if(e.appGroup)return{kind:"team",teamId:e.appGroup};if(e.developerEmail)return{kind:"developer",email:_(e.developerEmail)};if(e.developerId){let r=i.get(e.developerId);if(r||(r=(t=yield this.client.getDeveloper(e.developerId))===null||t===void 0?void 0:t.email,r&&i.set(e.developerId,r)),r)return{kind:"developer",email:_(r)}}return null})}listRequests(){return u(this,void 0,void 0,function*(){var e,i;const[t,r,n]=yield Promise.all([this.client.listOrganizationApps(),this.apigeeProducts(),this.productPages()]),o=new Map,a=[];for(const d of t){const c=((e=d.credentials)!==null&&e!==void 0?e:[]).flatMap(h=>{var w;return((w=h.apiProducts)!==null&&w!==void 0?w:[]).filter(m=>m.status==="pending").filter(m=>T(this.roleFor(m.apiproduct,n,r))).map(m=>({credential:h,apiProduct:m.apiproduct}))});if(c.length===0)continue;const l=yield this.ownerOf(d,o);if(!l)continue;const p=O(d.attributes)[I];for(const{credential:h,apiProduct:w}of c){const{consumerKey:m}=h,f=yield this.store.getRequestNote({owner:l,appId:d.name,consumerKey:m,apiProduct:w});a.push(Object.assign(Object.assign(Object.assign(Object.assign({id:he({owner:l,appId:d.name,keyDigest:Y(m),apiProduct:w}),owner:l},f?{requestedBy:f.requestedBy}:{}),{appId:d.name,appName:p||d.name,consumerKey:L(m),apiProduct:w}),f?.note?{note:f.note}:{}),{requestedAt:(i=f?.requestedAt)!==null&&i!==void 0?i:Number(h.issuedAt)||null,canDecide:G(this.roleFor(w,n,r))}))}}return a.sort((d,c)=>{var l,p;return((l=c.requestedAt)!==null&&l!==void 0?l:0)-((p=d.requestedAt)!==null&&p!==void 0?p:0)})})}decideRequest(e,i,t){return u(this,void 0,void 0,function*(){var r;const n=fe(e),{keyDigest:o}=n,a=D(n,["keyDigest"]),[d,c]=yield Promise.all([this.apigeeProducts(),this.productPages()]);if(!G(this.roleFor(a.apiProduct,c,d)))throw new S("You cannot decide requests for this API product");const l=g(t,P,"note"),p=this.ownerPath(a.owner),h=yield this.client.getApp(p,a.appId);if(!h)throw new b("App not found");const w=(r=h.credentials)===null||r===void 0?void 0:r.find(A=>Y(A.consumerKey)===o);if(!w)throw new b("Key not found");const m=Object.assign(Object.assign({},a),{consumerKey:w.consumerKey});yield this.client.setKeyProductStatus(p,m.appId,m.consumerKey,m.apiProduct,i),yield this.store.deleteRequestNote(m);const f=Object.assign({action:i,actor:this.email,at:Date.now()},l?{note:l}:{});return yield this.store.putDecision(m,f),this.store.appendAudit(Object.assign({at:f.at,actor:this.email,action:i,owner:m.owner,appId:m.appId,appName:O(h.attributes)[I]||h.name,consumerKey:L(m.consumerKey),apiProduct:m.apiProduct},l?{note:l}:{}))})}listAllApps(){return u(this,void 0,void 0,function*(){var e;const[i,t,r]=yield Promise.all([this.client.listOrganizationApps(),this.apigeeProducts(),this.productPages()]),n=T(this.ctx.roleForSlug(this.settings.basePath)),o=new Map,a=[];for(const d of i){if(!(n||((e=d.credentials)!==null&&e!==void 0?e:[]).some(m=>{var f;return((f=m.apiProducts)!==null&&f!==void 0?f:[]).some(A=>T(this.roleFor(A.apiproduct,r,t)))})))continue;const l=yield this.ownerOf(d,o);if(!l)continue;const p=N(d,l),{credentials:h}=p,w=D(p,["credentials"]);a.push(Object.assign(Object.assign({},w),{credentials:h.map(m=>{var{consumerKey:f,consumerSecret:A}=m,q=D(m,["consumerKey","consumerSecret"]);return q})}))}return a.sort((d,c)=>{var l,p;return((l=c.createdAt)!==null&&l!==void 0?l:0)-((p=d.createdAt)!==null&&p!==void 0?p:0)})})}listAudit(){return u(this,void 0,void 0,function*(){const[e,i,t]=yield Promise.all([this.store.listAudit(),this.apigeeProducts(),this.productPages()]);return e.filter(r=>T(this.roleFor(r.apiProduct,t,i)))})}}R=new WeakMap,j=new WeakMap;function M(s){const{myRole:e}=s;return D(s,["myRole"])}function X(s){if(!s.some(e=>e.role==="owner"))throw new v("A team needs at least one owner")}function Z(s){if(!Array.isArray(s)||s.some(e=>typeof e!="string"))throw new v("apiProducts must be a list of product names");return s}function Q(s){if(typeof s!="string"||!ce.test(s.trim()))throw new v("An app name has 1 to 100 letters, digits, spaces, dots, dashes or underscores");const e=s.trim();if(ue.has(e))throw new v(`An app cannot be named "${e}"`);return e}function g(s,e,i){if(s==null)return;if(typeof s!="string")throw new v(`${i} must be text`);const t=s.trim();if(t.length>e)throw new v(`${i} is longer than ${e} characters`);return t}function ee(s){const e=g(s,me,"callbackUrl");if(!e)return e===""?"":void 0;for(const i of e.split(","))try{new URL(i.trim())}catch{throw new v(`"${i.trim()}" is not a valid callback URL`)}return e}function ye(s){const e=typeof s=="string"?s.trim():"",i=e.indexOf("@"),t=e.slice(i+1);if(i<1||/\s/.test(e)||!t.includes(".")||t.startsWith(".")||t.endsWith("."))throw new v("Enter a valid email address");return _(e)}function te(s){if(s===void 0)return"member";if(s!=="owner"&&s!=="member")throw new v("Unknown role");return s}export{Te as ApigeeService,S as ForbiddenError,b as NotFoundError,v as ValidationError};
@@ -0,0 +1,38 @@
1
+ import type { KvService } from '@redocly/config';
2
+ import type { AppOwner, AuditEntry, Decision, Team } from '../contract.js';
3
+ /** What a developer wrote when asking for a manually approved product; Apigee has no field for it. */
4
+ export type RequestNote = {
5
+ requestedBy: string;
6
+ requestedAt: number;
7
+ note?: string;
8
+ };
9
+ export type StoredTeam = Omit<Team, 'myRole'>;
10
+ /** One product on one key of one app: what a request and a decision are about. */
11
+ export type RequestTarget = {
12
+ owner: AppOwner;
13
+ appId: string;
14
+ consumerKey: string;
15
+ apiProduct: string;
16
+ };
17
+ export declare function normalizeEmail(email: string): string;
18
+ /** The plugin's records in the site's KV store: team membership, request notes and the audit log. */
19
+ export declare class ApigeeStore {
20
+ private readonly kv;
21
+ constructor(kv: KvService);
22
+ getTeam(id: string): Promise<StoredTeam | null>;
23
+ putTeam(team: StoredTeam): Promise<void>;
24
+ deleteTeam(id: string): Promise<void>;
25
+ /** The teams `email` belongs to, from the membership index. */
26
+ listTeamsOf(email: string): Promise<StoredTeam[]>;
27
+ private requestKey;
28
+ putRequestNote(target: RequestTarget, note: RequestNote): Promise<void>;
29
+ getRequestNote(target: RequestTarget): Promise<RequestNote | null>;
30
+ deleteRequestNote(target: RequestTarget): Promise<void>;
31
+ private decisionKey;
32
+ putDecision(target: RequestTarget, decision: Decision): Promise<void>;
33
+ getDecisions(targets: RequestTarget[]): Promise<(Decision | null)[]>;
34
+ deleteDecision(target: RequestTarget): Promise<void>;
35
+ /** Keys sort by time, then by append order, so `list` in reverse yields the newest entries first. */
36
+ appendAudit(entry: Omit<AuditEntry, 'id'>): Promise<AuditEntry>;
37
+ listAudit(limit?: number): Promise<AuditEntry[]>;
38
+ }
@@ -0,0 +1 @@
1
+ var s=function(d,e,t,i){function o(n){return n instanceof t?n:new t(function(c){c(n)})}return new(t||(t=Promise))(function(n,c){function k(u){try{h(i.next(u))}catch(f){c(f)}}function S(u){try{h(i.throw(u))}catch(f){c(f)}}function h(u){u.done?n(u.value):o(u.value).then(k,S)}h((i=i.apply(d,e||[])).next())})};const r="apigee",v="teams",a="memberships",g="requests",b="decisions",m="audit",q=200;let p=0;function l(d){return d.trim().toLowerCase()}function y(d){return d.kind==="developer"?`developer:${l(d.email)}`:`team:${d.teamId}`}class K{constructor(e){Object.defineProperty(this,"kv",{enumerable:!0,configurable:!0,writable:!0,value:e})}getTeam(e){return s(this,void 0,void 0,function*(){return this.kv.get([r,v,e])})}putTeam(e){return s(this,void 0,void 0,function*(){yield this.kv.transaction(t=>s(this,void 0,void 0,function*(){var i;const o=yield t.get([r,v,e.id]);for(const n of(i=o?.members)!==null&&i!==void 0?i:[])e.members.some(c=>l(c.email)===l(n.email))||(yield t.delete([r,a,l(n.email),e.id]));yield t.set([r,v,e.id],e);for(const n of e.members)yield t.set([r,a,l(n.email),e.id],{role:n.role})}))})}deleteTeam(e){return s(this,void 0,void 0,function*(){yield this.kv.transaction(t=>s(this,void 0,void 0,function*(){var i;const o=yield t.get([r,v,e]);for(const n of(i=o?.members)!==null&&i!==void 0?i:[])yield t.delete([r,a,l(n.email),e]);yield t.delete([r,v,e])}))})}listTeamsOf(e){return s(this,void 0,void 0,function*(){const{items:t}=yield this.kv.list({prefix:[r,a,l(e)]},{limit:1e3}),i=t.map(n=>String(n.key[n.key.length-1]));return i.length===0?[]:(yield this.kv.getMany(i.map(n=>[r,v,n]))).flatMap(n=>n?.value?[n.value]:[])})}requestKey({owner:e,appId:t,consumerKey:i,apiProduct:o}){return[r,g,y(e),t,i,o]}putRequestNote(e,t){return s(this,void 0,void 0,function*(){yield this.kv.set(this.requestKey(e),t)})}getRequestNote(e){return s(this,void 0,void 0,function*(){return this.kv.get(this.requestKey(e))})}deleteRequestNote(e){return s(this,void 0,void 0,function*(){yield this.kv.delete(this.requestKey(e))})}decisionKey(e){return[r,b,y(e.owner),e.appId,e.consumerKey,e.apiProduct]}putDecision(e,t){return s(this,void 0,void 0,function*(){yield this.kv.set(this.decisionKey(e),t)})}getDecisions(e){return s(this,void 0,void 0,function*(){return e.length===0?[]:(yield this.kv.getMany(e.map(i=>this.decisionKey(i)))).map(i=>{var o;return(o=i?.value)!==null&&o!==void 0?o:null})})}deleteDecision(e){return s(this,void 0,void 0,function*(){yield this.kv.delete(this.decisionKey(e))})}appendAudit(e){return s(this,void 0,void 0,function*(){p+=1;const t=String(p).padStart(12,"0"),i=`${String(e.at).padStart(15,"0")}-${t}-${Math.random().toString(36).slice(2,8)}`,o=Object.assign(Object.assign({},e),{id:i});return yield this.kv.set([r,m,i],o),o})}listAudit(){return s(this,arguments,void 0,function*(e=200){const{items:t}=yield this.kv.list({prefix:[r,m]},{limit:e,reverse:!0});return t.flatMap(i=>i.value?[i.value]:[])})}}export{K as ApigeeStore,l as normalizeEmail};
@@ -0,0 +1,13 @@
1
+ import type { ApigeeAdapterConfig } from '@redocly/config';
2
+ type ApigeeAuth = ApigeeAdapterConfig['auth'];
3
+ export type TokenProvider = () => Promise<string>;
4
+ export declare class ApigeeTokenError extends Error {
5
+ name: string;
6
+ }
7
+ export declare function signServiceAccountJwt(auth: Extract<ApigeeAuth, {
8
+ type: 'SERVICE_ACCOUNT';
9
+ }>, now?: number): string;
10
+ /** A bearer token for `auth`, refreshed before it expires; a failed exchange is not cached. */
11
+ export declare function createTokenProvider(auth: ApigeeAuth, fetchImpl?: typeof fetch): TokenProvider;
12
+ export declare function clearTokenCache(): void;
13
+ export {};
@@ -0,0 +1,2 @@
1
+ var d=function(e,c,n,t){function r(o){return o instanceof n?o:new n(function(i){i(o)})}return new(n||(n=Promise))(function(o,i){function f(s){try{u(t.next(s))}catch(p){i(p)}}function E(s){try{u(t.throw(s))}catch(p){i(p)}}function u(s){s.done?o(s.value):r(s.value).then(f,E)}u((t=t.apply(e,c||[])).next())})};import{createSign as _}from"node:crypto";const h="https://oauth2.googleapis.com/token",y="https://www.googleapis.com/oauth2/v4/token",S="https://www.googleapis.com/auth/cloud-platform",A=6e4,m=3600,a=new Map;class l extends Error{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ApigeeTokenError"})}}function g(e){return Buffer.from(e).toString("base64url")}function O(e){return e.includes("\\n")?e.replace(/\\n/g,`
2
+ `):e}function k(e,c=Date.now()){const n=Math.floor(c/1e3),t=g(JSON.stringify({alg:"RS256",typ:"JWT"})),r=g(JSON.stringify({iss:e.serviceAccountEmail,sub:e.serviceAccountEmail,aud:y,scope:S,iat:n,exp:n+m})),o=`${t}.${r}`,i=_("RSA-SHA256").update(o).sign(O(e.serviceAccountPrivateKey),"base64url");return`${o}.${i}`}function w(e,c,n){return d(this,void 0,void 0,function*(){const t=yield n(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(c).toString()}),r=yield t.text();if(!t.ok)throw new l(`Apigee access token request failed with ${t.status}: ${r.slice(0,500)}`);let o;try{o=JSON.parse(r)}catch{throw new l("Apigee access token response is not JSON")}if(typeof o.access_token!="string")throw new l("Apigee access token response has no access_token");const i=Number(o.expires_in)||3600;return{token:o.access_token,expiresAt:Date.now()+i*1e3}})}function x(e,c){return e.type==="SERVICE_ACCOUNT"?w(h,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:k(e)},c):w(e.tokenEndpoint,{grant_type:"client_credentials",client_id:e.clientId,client_secret:e.clientSecret},c)}function v(e){return e.type==="SERVICE_ACCOUNT"?`sa:${e.serviceAccountEmail}`:`oauth2:${e.tokenEndpoint}:${e.clientId}`}function C(e,c=fetch){const n=v(e);return()=>d(this,void 0,void 0,function*(){let t=a.get(n);if(t){const r=yield t.catch(()=>null);if(r&&r.expiresAt-A>Date.now())return r.token}t=x(e,c),a.set(n,t);try{return(yield t).token}catch(r){throw a.get(n)===t&&a.delete(n),r}})}function N(){a.clear()}export{l as ApigeeTokenError,N as clearTokenCache,C as createTokenProvider,k as signServiceAccountJwt};
package/package.json CHANGED
@@ -1,5 +1,59 @@
1
1
  {
2
2
  "name": "@redocly/framework-plugin-apigee",
3
- "version": "0.0.1",
4
- "description": "Placeholder for the Redocly Apigee plugin; install the next tag."
5
- }
3
+ "version": "0.1.0-next.0",
4
+ "description": "Experimental Apigee developer onboarding plugin for Redocly",
5
+ "author": "team@redocly.com",
6
+ "license": "SEE LICENSE IN LICENSE",
7
+ "files": [
8
+ "lib",
9
+ "CHANGELOG.md"
10
+ ],
11
+ "type": "module",
12
+ "main": "lib/plugin.js",
13
+ "exports": {
14
+ ".": "./lib/plugin.js",
15
+ "./plugin.js": "./lib/plugin.js",
16
+ "./package.json": "./package.json"
17
+ },
18
+ "keywords": [
19
+ "redocly",
20
+ "realm",
21
+ "apigee"
22
+ ],
23
+ "dependencies": {
24
+ "@redocly/config": "0.74.0",
25
+ "styled-components": "^6.4.2"
26
+ },
27
+ "devDependencies": {
28
+ "@redocly/framework": "1.0.0-next.7",
29
+ "@types/node": "24.1.0",
30
+ "@types/react": "^19.2.7",
31
+ "@types/react-dom": "^19.2.3",
32
+ "@vitest/coverage-v8": "4.1.11",
33
+ "esbuild-minify-dir": "0.0.1",
34
+ "hono": "4.13.13",
35
+ "rimraf": "5.0.7",
36
+ "typescript": "6.0.3",
37
+ "vitest": "4.1.11"
38
+ },
39
+ "peerDependencies": {
40
+ "@redocly/framework": "^1.0.0-next.7",
41
+ "@redocly/theme": "0.73.0-next.2",
42
+ "react": "^19.2.7",
43
+ "react-dom": "^19.2.7",
44
+ "react-router": "^8.3.0"
45
+ },
46
+ "nx": {
47
+ "implicitDependencies": [
48
+ "@redocly/framework"
49
+ ]
50
+ },
51
+ "scripts": {
52
+ "clean": "rimraf lib",
53
+ "compile": "tsgo -p tsconfig.build.json",
54
+ "build": "pnpm run clean && pnpm run compile && pnpm run minify",
55
+ "minify": "esbuild-minify-dir ./lib",
56
+ "watch": "tsgo -w -p tsconfig.build.json",
57
+ "test": "nx run vitest:test"
58
+ }
59
+ }