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

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 +64 -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 +81 -0
  7. package/lib/client/Primitives.js +420 -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 +20 -0
  16. package/lib/client/views/AppsView.d.ts +15 -0
  17. package/lib/client/views/AppsView.js +5 -0
  18. package/lib/client/views/Dialogs.d.ts +58 -0
  19. package/lib/client/views/Dialogs.js +9 -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 +195 -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 +98 -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,60 @@
1
+ import type { ApigeeSettings } from '../config.js';
2
+ import type { ApigeeApiProduct, ApigeeApp, ApigeeAppGroup, ApigeeAppInput, ApigeeAttribute, ApigeeCredential, ApigeeDeveloper } from './apigee-types.js';
3
+ import type { TokenProvider } from './token.js';
4
+ /** Who an app belongs to in Apigee: a developer (by email) or an AppGroup (by name). */
5
+ export type AppOwnerPath = {
6
+ kind: 'developer';
7
+ email: string;
8
+ } | {
9
+ kind: 'appgroup';
10
+ name: string;
11
+ };
12
+ export type KeyAction = 'approve' | 'revoke';
13
+ export declare class ApigeeApiError extends Error {
14
+ readonly status: number;
15
+ readonly code?: string | undefined;
16
+ name: string;
17
+ constructor(status: number, message: string, code?: string | undefined);
18
+ }
19
+ export declare class ApigeeClient {
20
+ private readonly settings;
21
+ private readonly getToken;
22
+ private readonly fetchImpl;
23
+ readonly organizationUrl: string;
24
+ constructor(settings: ApigeeSettings, getToken: TokenProvider, fetchImpl?: typeof fetch);
25
+ ownerUrl(owner: AppOwnerPath): string;
26
+ request<T>(path: string, init?: RequestInit & {
27
+ json?: unknown;
28
+ }): Promise<T>;
29
+ listApiProducts(): Promise<ApigeeApiProduct[]>;
30
+ getDeveloper(idOrEmail: string): Promise<ApigeeDeveloper | null>;
31
+ createDeveloper(developer: ApigeeDeveloper): Promise<ApigeeDeveloper>;
32
+ /** Apigee only knows a developer once a record exists; the first app creates it from the session. */
33
+ ensureDeveloper(developer: ApigeeDeveloper): Promise<void>;
34
+ listApps(owner: AppOwnerPath): Promise<ApigeeApp[]>;
35
+ getApp(owner: AppOwnerPath, name: string): Promise<ApigeeApp | null>;
36
+ createApp(owner: AppOwnerPath, input: ApigeeAppInput): Promise<ApigeeApp>;
37
+ updateApp(owner: AppOwnerPath, name: string, input: Partial<ApigeeAppInput> & {
38
+ attributes: ApigeeAttribute[];
39
+ }): Promise<ApigeeApp>;
40
+ deleteApp(owner: AppOwnerPath, name: string): Promise<void>;
41
+ private keyUrl;
42
+ createKey(owner: AppOwnerPath, app: string, key: {
43
+ consumerKey: string;
44
+ consumerSecret: string;
45
+ expiresInSeconds: number;
46
+ }): Promise<ApigeeCredential>;
47
+ getKey(owner: AppOwnerPath, app: string, key: string): Promise<ApigeeCredential | null>;
48
+ /** Associates `apiProducts` with the key; products already on the key stay. */
49
+ addKeyProducts(owner: AppOwnerPath, app: string, key: string, apiProducts: string[], attributes: ApigeeAttribute[] | undefined): Promise<ApigeeCredential>;
50
+ removeKeyProduct(owner: AppOwnerPath, app: string, key: string, apiProduct: string): Promise<void>;
51
+ deleteKey(owner: AppOwnerPath, app: string, key: string): Promise<void>;
52
+ setKeyProductStatus(owner: AppOwnerPath, app: string, key: string, apiProduct: string, action: KeyAction): Promise<void>;
53
+ listAppGroups(): Promise<ApigeeAppGroup[]>;
54
+ getAppGroup(name: string): Promise<ApigeeAppGroup | null>;
55
+ createAppGroup(group: ApigeeAppGroup): Promise<ApigeeAppGroup>;
56
+ updateAppGroup(name: string, group: ApigeeAppGroup): Promise<ApigeeAppGroup>;
57
+ deleteAppGroup(name: string): Promise<void>;
58
+ /** Every app in the organization with its credentials, developer and AppGroup apps alike. */
59
+ listOrganizationApps(): Promise<ApigeeApp[]>;
60
+ }
@@ -0,0 +1 @@
1
+ var i=function(s,e,t,r){function n(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function d(u){try{c(r.next(u))}catch(l){a(l)}}function p(u){try{c(r.throw(u))}catch(l){a(l)}}function c(u){u.done?o(u.value):n(u.value).then(d,p)}c((r=r.apply(s,e||[])).next())})};class h extends Error{constructor(e,t,r){super(t),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ApigeeApiError"})}}const U="developer.service.DeveloperDoesNotExist",f=1e3;function b(s){var e,t,r,n,o,a,d,p,c,u,l;try{const v=JSON.parse(s),m=(o=(n=(r=(t=(e=v.error)===null||e===void 0?void 0:e.details)===null||t===void 0?void 0:t[0])===null||r===void 0?void 0:r.violations)===null||n===void 0?void 0:n[0])===null||o===void 0?void 0:o.type;return{message:(c=(p=(a=v.error)===null||a===void 0?void 0:a.message)!==null&&p!==void 0?p:v.message)!==null&&c!==void 0?c:s,code:(l=(u=v.code)!==null&&u!==void 0?u:m)!==null&&l!==void 0?l:(d=v.error)===null||d===void 0?void 0:d.status}}catch{return{message:s||"Apigee request failed"}}}function y(s){return encodeURIComponent(s)}class ${constructor(e,t,r=fetch){Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"getToken",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"fetchImpl",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"organizationUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.organizationUrl=`${e.apiUrl}/organizations/${encodeURIComponent(e.organizationName)}`}ownerUrl(e){return e.kind==="developer"?`/developers/${y(e.email)}`:`/appgroups/${encodeURIComponent(e.name)}`}request(e){return i(this,arguments,void 0,function*(t,r={}){const n=`${this.organizationUrl}${t}`,o=Object.assign(Object.assign({Accept:"application/json",Authorization:`Bearer ${yield this.getToken()}`},this.settings.auth.type==="OAUTH2"?{"X-Api-Key":this.settings.auth.clientId}:{}),r.headers);let a=r.body;r.json!==void 0&&(o["Content-Type"]="application/json",a=JSON.stringify(r.json));const d=yield this.fetchImpl(n,Object.assign(Object.assign({},r),{headers:o,body:a})),p=yield d.text();if(!d.ok){const{message:c,code:u}=b(p);throw new h(d.status,c,u)}return p?JSON.parse(p):void 0})}listApiProducts(){return i(this,void 0,void 0,function*(){var e;return(e=(yield this.request("/apiproducts?expand=true")).apiProduct)!==null&&e!==void 0?e:[]})}getDeveloper(e){return i(this,void 0,void 0,function*(){try{return yield this.request(`/developers/${y(e)}`)}catch(t){if(t instanceof h&&t.status===404)return null;throw t}})}createDeveloper(e){return i(this,void 0,void 0,function*(){return this.request("/developers",{method:"POST",json:e})})}ensureDeveloper(e){return i(this,void 0,void 0,function*(){if(!(yield this.getDeveloper(e.email)))try{yield this.createDeveloper(e)}catch(t){if(t instanceof h&&t.status===409)return;throw t}})}listApps(e){return i(this,void 0,void 0,function*(){var t,r;try{return e.kind==="appgroup"?(t=(yield this.request(`${this.ownerUrl(e)}/apps`)).appGroupApps)!==null&&t!==void 0?t:[]:(r=(yield this.request(`${this.ownerUrl(e)}/apps?expand=true`)).app)!==null&&r!==void 0?r:[]}catch(n){if(g(n))return[];throw n}})}getApp(e,t){return i(this,void 0,void 0,function*(){try{return yield this.request(`${this.ownerUrl(e)}/apps/${encodeURIComponent(t)}`)}catch(r){if(r instanceof h&&r.status===404||g(r))return null;throw r}})}createApp(e,t){return i(this,void 0,void 0,function*(){return this.request(`${this.ownerUrl(e)}/apps`,{method:"POST",json:t})})}updateApp(e,t,r){return i(this,void 0,void 0,function*(){return this.request(`${this.ownerUrl(e)}/apps/${encodeURIComponent(t)}`,{method:"PUT",json:Object.assign({name:t},r)})})}deleteApp(e,t){return i(this,void 0,void 0,function*(){yield this.request(`${this.ownerUrl(e)}/apps/${encodeURIComponent(t)}`,{method:"DELETE"})})}keyUrl(e,t,r){return`${this.ownerUrl(e)}/apps/${encodeURIComponent(t)}/keys/${encodeURIComponent(r)}`}createKey(e,t,r){return i(this,void 0,void 0,function*(){const n=e.kind==="appgroup"?"keys":"keys/create";return this.request(`${this.ownerUrl(e)}/apps/${encodeURIComponent(t)}/${n}`,{method:"POST",json:{consumerKey:r.consumerKey,consumerSecret:r.consumerSecret,expiresInSeconds:String(r.expiresInSeconds)}})})}getKey(e,t,r){return i(this,void 0,void 0,function*(){try{return yield this.request(this.keyUrl(e,t,r))}catch(n){if(n instanceof h&&n.status===404)return null;throw n}})}addKeyProducts(e,t,r,n,o){return i(this,void 0,void 0,function*(){return this.request(this.keyUrl(e,t,r),{method:"POST",json:{apiProducts:n,attributes:o}})})}removeKeyProduct(e,t,r,n){return i(this,void 0,void 0,function*(){yield this.request(`${this.keyUrl(e,t,r)}/apiproducts/${encodeURIComponent(n)}`,{method:"DELETE"})})}deleteKey(e,t,r){return i(this,void 0,void 0,function*(){yield this.request(this.keyUrl(e,t,r),{method:"DELETE"})})}setKeyProductStatus(e,t,r,n,o){return i(this,void 0,void 0,function*(){yield this.request(`${this.keyUrl(e,t,r)}/apiproducts/${encodeURIComponent(n)}?action=${o}`,{method:"POST",headers:{"Content-Type":"application/octet-stream"}})})}listAppGroups(){return i(this,void 0,void 0,function*(){var e;const t=[];let r;do{const n=new URLSearchParams({pageSize:String(f)});r&&n.set("pageToken",r);const o=yield this.request(`/appgroups?${n}`);t.push(...(e=o.appGroups)!==null&&e!==void 0?e:[]),r=o.nextPageToken}while(r);return t})}getAppGroup(e){return i(this,void 0,void 0,function*(){try{return yield this.request(`/appgroups/${encodeURIComponent(e)}`)}catch(t){if(t instanceof h&&t.status===404)return null;throw t}})}createAppGroup(e){return i(this,void 0,void 0,function*(){return this.request("/appgroups",{method:"POST",json:e})})}updateAppGroup(e,t){return i(this,void 0,void 0,function*(){return this.request(`/appgroups/${encodeURIComponent(e)}`,{method:"PUT",json:t})})}deleteAppGroup(e){return i(this,void 0,void 0,function*(){yield this.request(`/appgroups/${encodeURIComponent(e)}`,{method:"DELETE"})})}listOrganizationApps(){return i(this,void 0,void 0,function*(){var e;const t=[];let r;do{const n=new URLSearchParams({expand:"true",includeCred:"true",pageSize:String(f)});r&&n.set("pageToken",r);const o=yield this.request(`/apps?${n}`);t.push(...(e=o.app)!==null&&e!==void 0?e:[]),r=o.nextPageToken}while(r);return t})}}function g(s){return s instanceof h&&(s.code===U||s.status===404)}export{h as ApigeeApiError,$ as ApigeeClient};
@@ -0,0 +1,10 @@
1
+ import type { ApiProduct, App, AppOwner, Credential } from '../contract.js';
2
+ import type { ApigeeApiProduct, ApigeeApp, ApigeeAttribute, ApigeeCredential } from './apigee-types.js';
3
+ export declare function attributesToRecord(attributes: ApigeeAttribute[] | undefined): Record<string, string>;
4
+ export declare function recordToAttributes(record: Record<string, string | undefined>): ApigeeAttribute[];
5
+ export declare function toCredential(credential: ApigeeCredential): Credential;
6
+ export declare function toApp(app: ApigeeApp, owner: AppOwner): App;
7
+ export declare function toApiProduct(product: ApigeeApiProduct, api?: {
8
+ slug: string;
9
+ title: string;
10
+ }): ApiProduct;
@@ -0,0 +1 @@
1
+ import{APIGEE_DISPLAY_NAME_ATTRIBUTE as a,APIGEE_NOTES_ATTRIBUTE as l}from"../constants.js";function u(t){return Object.fromEntries((t??[]).map(e=>[e.name,e.value]))}function p(t){return Object.entries(t).flatMap(([e,n])=>n===void 0?[]:[{name:e,value:n}])}function r(t){const e=Number(t);return Number.isFinite(e)&&e>0?e:null}function c(t){return t==="approved"||t==="revoked"||t==="pending"?t:"pending"}function d(t){var e,n;return{consumerKey:t.consumerKey,consumerSecret:t.consumerSecret,status:c(t.status),issuedAt:r(t.issuedAt),expiresAt:r(t.expiresAt),apiProducts:((e=t.apiProducts)!==null&&e!==void 0?e:[]).map(s=>({id:s.apiproduct,status:c(s.status)})),scopes:(n=t.scopes)!==null&&n!==void 0?n:[]}}function A(t,e){var n,s,o;const i=u(t.attributes);return Object.assign(Object.assign({id:t.name,name:i[a]||t.name,description:(n=i[l])!==null&&n!==void 0?n:""},t.callbackUrl?{callbackUrl:t.callbackUrl}:{}),{owner:e,status:(s=t.status)!==null&&s!==void 0?s:"approved",createdAt:r(t.createdAt),lastModifiedAt:r(t.lastModifiedAt),credentials:((o=t.credentials)!==null&&o!==void 0?o:[]).map(d)})}function b(t,e){var n;const s=u(t.attributes);return Object.assign({id:t.name,name:t.displayName||s[a]||t.name,description:(n=t.description)!==null&&n!==void 0?n:"",approvalType:t.approvalType==="manual"?"manual":"auto"},e?{api:e}:{})}export{u as attributesToRecord,p as recordToAttributes,b as toApiProduct,A as toApp,d as toCredential};
@@ -0,0 +1,25 @@
1
+ import type { ServerRouteContext, ServerRouteHandler } from '@redocly/framework/plugin';
2
+ type Context = Parameters<ServerRouteHandler>[0];
3
+ export declare const meta: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
4
+ export declare const access: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
5
+ export declare const listApps: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
6
+ export declare const createApp: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
7
+ export declare const updateApp: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
8
+ export declare const deleteApp: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
9
+ export declare const createKey: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
10
+ export declare const updateKey: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
11
+ export declare const deleteKey: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
12
+ export declare const listTeams: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
13
+ export declare const createTeam: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
14
+ export declare const getTeam: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
15
+ export declare const updateTeam: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
16
+ export declare const deleteTeam: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
17
+ export declare const addTeamMember: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
18
+ export declare const updateTeamMember: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
19
+ export declare const removeTeamMember: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
20
+ export declare const adminRequests: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
21
+ export declare const adminApprove: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
22
+ export declare const adminRevoke: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
23
+ export declare const adminApps: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
24
+ export declare const adminAudit: (c: Context, ctx: ServerRouteContext) => Promise<Response>;
25
+ export {};
@@ -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,98 @@
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
+ /**
87
+ * AppGroup display names by AppGroup name; groups without one are left out. Empty when teams
88
+ * are off or the AppGroups cannot be read.
89
+ */
90
+ private teamNames;
91
+ /** Requests for the products the viewer may review, newest first. */
92
+ listRequests(): Promise<AccessRequest[]>;
93
+ decideRequest(requestId: string, action: KeyAction, note?: string): Promise<AuditEntry>;
94
+ /** Every app a reviewer of all products sees; a product reviewer sees the apps holding that product. */
95
+ listAllApps(): Promise<AdminApp[]>;
96
+ listAudit(): Promise<AuditEntry[]>;
97
+ }
98
+ export {};
@@ -0,0 +1 @@
1
+ var u=function(s,e,i,t){function r(o){return o instanceof i?o:new i(function(n){n(o)})}return new(i||(i=Promise))(function(o,n){function a(p){try{l(t.next(p))}catch(c){n(c)}}function d(p){try{l(t.throw(p))}catch(c){n(c)}}function l(p){p.done?o(p.value):r(p.value).then(a,d)}l((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)},C=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},I=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 ne,randomBytes as oe}from"node:crypto";import{isApiProductOffered as L}from"../config.js";import{APIGEE_DEFAULT_KEY_LIFETIME_SECONDS as V,APIGEE_DISPLAY_NAME_ATTRIBUTE as D,APIGEE_NOTES_ATTRIBUTE as k,APIGEE_PRODUCTS_ENTITY_KEY as se,APIGEE_PRODUCTS_VALUE_KEY as ae,APIGEE_TEAM_MEMBERS_ATTRIBUTE as F}from"../constants.js";import{maskKey as z}from"../contract.js";import{ApigeeApiError as de}from"./client.js";import{attributesToRecord as O,recordToAttributes as K,toApiProduct as Y,toApp as S,toCredential as H}from"./mappers.js";import{ApigeeStore as le,normalizeEmail as _}from"./store.js";class y extends Error{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ValidationError"})}}class q 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 ce={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 ue(s,e){return E[s]>=E[e]?s:e}const pe=/^[A-Za-z0-9._$ -]{1,100}$/,me=new Set(["teams","admin"]),he=/^[a-z0-9][a-z0-9-]{1,62}$/,P=2e3,fe=2048;function ve(s){return Buffer.from(JSON.stringify(s)).toString("base64url")}function J(s){return ne("sha256").update(s).digest("base64url")}function ye(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 y("Unknown request")}}function we(s){return s.trim().toLowerCase().split(/[^a-z0-9]/).filter(Boolean).join("-").slice(0,63)}function ge(s){var e,i,t,r;const o=((i=s.name)!==null&&i!==void 0?i:"").trim().split(/\s+/).filter(Boolean),n=(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:o[0]||n[0]||"Unknown",lastName:o.slice(1).join(" ")||n[1]||"Unknown"}}function W(s){return oe(s).toString("base64url")}function X(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 o,n;if(typeof r?.developer!="string")return[];const a=_(r.developer),d=e?.members.find(l=>l.email===a);return[{email:a,role:!((o=r.roles)===null||o===void 0)&&o.includes("owner")?"owner":"member",addedAt:(n=d?.addedAt)!==null&&n!==void 0?n:Number(s.createdAt)||0}]}):[]}catch{return[]}}function U(s,e){var i,t,r,o;const n=X(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:(o=(r=e?.createdBy)!==null&&r!==void 0?r:(i=n.find(a=>a.role==="owner"))===null||i===void 0?void 0:i.email)!==null&&o!==void 0?o:"",members:n}}function Z(s){return JSON.stringify(s.map(e=>({developer:e.email,roles:[e.role]})))}class Re{constructor(e,i,t,r,o){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:o}),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 le(r.kv)}get email(){return _(this.viewer.email)}apigeeProducts(){var e;return C(this,R,(e=x(this,R,"f"))!==null&&e!==void 0?e:this.client.listApiProducts(),"f"),x(this,R,"f")}productPages(){var e;return C(this,j,(e=x(this,j,"f"))!==null&&e!==void 0?e:this.ctx.entities.load(se).then(i=>{var t;return(t=i?.[ae])!==null&&t!==void 0?t:ce}),"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),o=r?this.pageFor(r,i):i.byApiId[e],n=o?this.ctx.roleForSlug(o.slug):"none";return ue(n,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),o=!1;for(const n of i){if(!L(this.settings,n.name))continue;const a=this.roleFor(n.name,t,i);r||(r=T(a)),o||(o=G(a))}return{enabled:!0,canView:r,canDecide:o}})}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(!L(this.settings,r.name))continue;const o=this.pageFor(r,i);if(o){if(!this.ctx.isSlugVisible(o.slug))continue;t.push(Y(r,o))}else this.settings.apiProducts.allowOutsideCatalog&&t.push(Y(r))}return t.sort((r,o)=>r.name.localeCompare(o.name))})}assertProductsAllowed(e){return u(this,void 0,void 0,function*(){const i=ee(e),t=yield this.listApiProducts(),r=i.filter(n=>!t.some(a=>a.id===n));if(r.length>0)throw new y(`Unknown API product: ${r.join(", ")}`);const o=new Map(t.map(n=>[n.id,n]));return[...new Set(i)].flatMap(n=>{const a=o.get(n);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 o of e)for(const n of o.credentials)for(const a of n.apiProducts)i.push({owner:o.owner,appId:o.id,consumerKey:n.consumerKey,apiProduct:a.id});const t=yield this.store.getDecisions(i);let r=0;for(const o of e)for(const n of o.credentials)for(const a of n.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(o=>this.client.listApps({kind:"appgroup",name:o.id}))]),r=i.map(o=>S(o,{kind:"developer",email:this.email}));return e.forEach((o,n)=>{r.push(...t[n].map(a=>S(a,{kind:"team",teamId:o.id})))}),this.withDecisions(r.sort((o,n)=>{var a,d;return((a=n.createdAt)!==null&&a!==void 0?a:0)-((d=o.createdAt)!==null&&d!==void 0?d:0)}))})}createApp(e){return u(this,void 0,void 0,function*(){var i;const t=te(e.name),r=A(e.description,P,"description"),o=ie(e.callbackUrl),n=A(e.note,P,"note"),a=yield this.assertProductsAllowed((i=e.apiProducts)!==null&&i!==void 0?i:[]),{owner:d,path:l}=yield this.resolveOwner(e.teamId);if(d.kind==="developer"&&(yield this.client.ensureDeveloper(Object.assign({email:this.email,userName:this.email},ge(this.viewer)))),yield this.client.getApp(l,t))throw new y(`An app named "${t}" already exists`);const p=yield this.client.createApp(l,Object.assign(Object.assign({name:t,apiProducts:a.map(m=>m.id)},o?{callbackUrl:o}:{}),{keyExpiresIn:String(V*(d.kind==="developer"?1e3:1)),attributes:K({[D]:t,[k]:r??""})})),c=S(p,d);return yield this.recordRequestNotes(d,c.id,c.credentials,a,n),c})}updateApp(e,i,t){return u(this,void 0,void 0,function*(){var r;const{owner:o,path:n}=yield this.resolveOwner(e),a=yield this.client.getApp(n,i);if(!a)throw new b("App not found");const d=O(a.attributes);t.name!==void 0&&(d[D]=te(t.name)),t.description!==void 0&&(d[k]=(r=A(t.description,P,"description"))!==null&&r!==void 0?r:"");const l=t.callbackUrl===void 0?a.callbackUrl:ie(t.callbackUrl),p=yield this.client.updateApp(n,i,Object.assign({attributes:K(d)},l!==void 0?{callbackUrl:l}:{}));return S(p,o)})}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:o,path:n}=yield this.resolveOwner(e);if(!(yield this.client.getApp(n,i)))throw new b("App not found");const a=yield this.assertProductsAllowed((r=t.apiProducts)!==null&&r!==void 0?r:[]),d=A(t.note,P,"note"),l=yield this.client.createKey(n,i,{consumerKey:W(24),consumerSecret:W(24),expiresInSeconds:V}),p=a.length>0?yield this.client.addKeyProducts(n,i,l.consumerKey,a.map(m=>m.id),l.attributes):l,c=H(p);return yield this.recordRequestNotes(o,i,[c],a,d),c})}updateKeyProducts(e,i,t,r){return u(this,void 0,void 0,function*(){var o,n;const{owner:a,path:d}=yield this.resolveOwner(e),l=yield this.client.getKey(d,i,t);if(!l)throw new b("Key not found");const p=new Set(((o=l.apiProducts)!==null&&o!==void 0?o:[]).map(g=>g.apiproduct)),c=ee((n=r.apiProducts)!==null&&n!==void 0?n:[]),m=yield this.assertProductsAllowed(c.filter(g=>!p.has(g))),w=A(r.note,P,"note"),h=[...p].filter(g=>!c.includes(g));let f=l;m.length>0&&(f=yield this.client.addKeyProducts(d,i,t,m.map(g=>g.id),l.attributes));for(const g of h)yield this.client.removeKeyProduct(d,i,t,g),yield this.store.deleteRequestNote({owner:a,appId:i,consumerKey:t,apiProduct:g}),yield this.store.deleteDecision({owner:a,appId:i,consumerKey:t,apiProduct:g});const v=h.length>0?yield this.client.getKey(d,i,t):null,N=H(v??f);return yield this.recordRequestNotes(a,i,[N],m,w),N})}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,o){return u(this,void 0,void 0,function*(){const n=r.filter(d=>d.approvalType==="manual");if(n.length===0)return;const a=Date.now();for(const d of t)for(const l of n)yield this.store.putRequestNote({owner:e,appId:i,consumerKey:d.consumerKey,apiProduct:l.id},Object.assign({requestedBy:this.email,requestedAt:a},o?{note:o}:{}))})}getAccess(e){return u(this,void 0,void 0,function*(){const i=yield this.appsOf(yield this.indexedTeams()),t=Date.now(),r=n=>i.flatMap(a=>a.credentials.filter(d=>a.status!=="revoked"&&d.status==="approved"&&(d.expiresAt===null||d.expiresAt>t)&&d.apiProducts.some(l=>l.id===e&&l.status===n)).map(d=>({app:a,credential:d}))),o=r("approved").sort((n,a)=>n.app.owner.kind===a.app.owner.kind?0:n.app.owner.kind==="developer"?-1:1);if(o.length>0){const{credential:n}=o[0];return{status:"APPROVED",link:this.settings.basePath,requestValues:{security:{default:Object.assign({client_id:n.consumerKey},n.consumerSecret?{client_secret:n.consumerSecret}:{})}}}}return{status:r("pending").length>0?"PENDING":"NONE",link:`${this.settings.basePath}?createApp&apiProduct=${encodeURIComponent(e)}`}})}assertTeams(){if(!this.settings.teamsEnabled)throw new q("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(n){return(e=this.logger)===null||e===void 0||e.debug(`apigee: AppGroups unavailable: ${String(n)}`),[]}const r=new Map((yield this.store.listTeamsOf(this.email)).map(n=>[n.id,n])),o=[];for(const n of t){if(!X(n).some(d=>d.email===this.email))continue;const a=U(n,(i=r.get(n.name))!==null&&i!==void 0?i:yield this.store.getTeam(n.name));r.has(a.id)||(yield this.store.putTeam(a)),o.push(this.withRole(a))}return o.sort((n,a)=>n.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 o=t?this.withRole(U(t,e[r])):null;return o?.myRole?[o]:[]})})}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 o=this.withRole(U(t,r));if(!o.myRole)throw new q("You are not a member of this team");if(i==="owner"&&o.myRole!=="owner")throw new q("Only a team owner can do this");return o})}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=A(e.name,100,"name");if(!t)throw new y("A team needs a name");const r=we(t);if(!he.test(r))throw new y("The team name needs at least two letters or digits");const o=(i=A(e.description,P,"description"))!==null&&i!==void 0?i:"";if((yield this.store.getTeam(r))||(yield this.client.getAppGroup(r)))throw new y(`A team named "${t}" already exists`);const n=[{email:this.email,role:"owner",addedAt:Date.now()}];yield this.client.createAppGroup({name:r,displayName:t,attributes:K({[k]:o,[F]:Z(n)})});const a={id:r,name:t,description:o,createdAt:Date.now(),createdBy:this.email,members:n};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"),o=A(i.name,100,"name")||r.name,n=(t=A(i.description,P,"description"))!==null&&t!==void 0?t:r.description,a=Object.assign(Object.assign({},M(r)),{name:o,description:n});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 de&&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=be(i.email),o=re(i.role);if(t.members.some(a=>a.email===r))throw new y(`${r} is already a member`);const n=Object.assign(Object.assign({},M(t)),{members:[...t.members,{email:r,role:o,addedAt:Date.now()}]});return yield this.syncAppGroup(n),yield this.store.putTeam(n),this.withRole(n)})}setMemberRole(e,i,t){return u(this,void 0,void 0,function*(){const r=yield this.requireTeam(e,"owner"),o=_(i);if(!r.members.some(d=>d.email===o))throw new b("Member not found");const n=r.members.map(d=>d.email===o?Object.assign(Object.assign({},d),{role:re(t)}):d);Q(n);const a=Object.assign(Object.assign({},M(r)),{members:n});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 q("Only a team owner can remove other members");if(!t.members.some(a=>a.email===r))throw new b("Member not found");const o=t.members.filter(a=>a.email!==r);Q(o);const n=Object.assign(Object.assign({},M(t)),{members:o});return yield this.syncAppGroup(n),yield this.store.putTeam(n),this.withRole(n)})}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]:Z(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})}teamNames(){return u(this,void 0,void 0,function*(){var e;const i=new Map;if(!this.settings.teamsEnabled)return i;let t;try{t=yield this.client.listAppGroups()}catch(r){return(e=this.logger)===null||e===void 0||e.debug(`apigee: AppGroups unavailable: ${String(r)}`),i}for(const r of t)r.displayName&&i.set(r.name,r.displayName);return i})}listRequests(){return u(this,void 0,void 0,function*(){var e,i;const[t,r,o,n]=yield Promise.all([this.client.listOrganizationApps(),this.apigeeProducts(),this.productPages(),this.teamNames()]),a=new Map,d=[];for(const l of t){const p=((e=l.credentials)!==null&&e!==void 0?e:[]).flatMap(w=>{var h;return((h=w.apiProducts)!==null&&h!==void 0?h:[]).filter(f=>f.status==="pending").filter(f=>T(this.roleFor(f.apiproduct,o,r))).map(f=>({credential:w,apiProduct:f.apiproduct}))});if(p.length===0)continue;const c=yield this.ownerOf(l,a);if(!c)continue;const m=O(l.attributes)[D];for(const{credential:w,apiProduct:h}of p){const{consumerKey:f}=w,v=yield this.store.getRequestNote({owner:c,appId:l.name,consumerKey:f,apiProduct:h});d.push(Object.assign(Object.assign(Object.assign(Object.assign({id:ve({owner:c,appId:l.name,keyDigest:J(f),apiProduct:h}),owner:c},v?{requestedBy:v.requestedBy}:{}),{teamName:B(c,n),appId:l.name,appName:m||l.name,consumerKey:z(f),apiProduct:h,apiProductName:$(r,h)}),v?.note?{note:v.note}:{}),{requestedAt:(i=v?.requestedAt)!==null&&i!==void 0?i:Number(w.issuedAt)||null,canDecide:G(this.roleFor(h,o,r))}))}}return d.sort((l,p)=>{var c,m;return((c=p.requestedAt)!==null&&c!==void 0?c:0)-((m=l.requestedAt)!==null&&m!==void 0?m:0)})})}decideRequest(e,i,t){return u(this,void 0,void 0,function*(){var r;const o=ye(e),{keyDigest:n}=o,a=I(o,["keyDigest"]),[d,l]=yield Promise.all([this.apigeeProducts(),this.productPages()]);if(!G(this.roleFor(a.apiProduct,l,d)))throw new q("You cannot decide requests for this API product");const p=A(t,P,"note"),c=this.ownerPath(a.owner),m=yield this.client.getApp(c,a.appId);if(!m)throw new b("App not found");const w=(r=m.credentials)===null||r===void 0?void 0:r.find(v=>J(v.consumerKey)===n);if(!w)throw new b("Key not found");const h=Object.assign(Object.assign({},a),{consumerKey:w.consumerKey});yield this.client.setKeyProductStatus(c,h.appId,h.consumerKey,h.apiProduct,i),yield this.store.deleteRequestNote(h);const f=Object.assign({action:i,actor:this.email,at:Date.now()},p?{note:p}:{});return yield this.store.putDecision(h,f),this.store.appendAudit(Object.assign({at:f.at,actor:this.email,action:i,owner:h.owner,appId:h.appId,appName:O(m.attributes)[D]||m.name,consumerKey:z(h.consumerKey),apiProduct:h.apiProduct},p?{note:p}:{}))})}listAllApps(){return u(this,void 0,void 0,function*(){var e;const[i,t,r,o]=yield Promise.all([this.client.listOrganizationApps(),this.apigeeProducts(),this.productPages(),this.teamNames()]),n=T(this.ctx.roleForSlug(this.settings.basePath)),a=new Map,d=[];for(const l of i){if(!(n||((e=l.credentials)!==null&&e!==void 0?e:[]).some(f=>{var v;return((v=f.apiProducts)!==null&&v!==void 0?v:[]).some(N=>T(this.roleFor(N.apiproduct,r,t)))})))continue;const c=yield this.ownerOf(l,a);if(!c)continue;const m=S(l,c),{credentials:w}=m,h=I(m,["credentials"]);for(const f of w.flatMap(v=>v.apiProducts))f.name=$(t,f.id);d.push(Object.assign(Object.assign({},h),{teamName:B(c,o),credentials:w.map(f=>{var{consumerKey:v,consumerSecret:N}=f,g=I(f,["consumerKey","consumerSecret"]);return g})}))}return d.sort((l,p)=>{var c,m;return((c=p.createdAt)!==null&&c!==void 0?c:0)-((m=l.createdAt)!==null&&m!==void 0?m:0)})})}listAudit(){return u(this,void 0,void 0,function*(){const[e,i,t,r]=yield Promise.all([this.store.listAudit(),this.apigeeProducts(),this.productPages(),this.teamNames()]),o=e.filter(n=>T(this.roleFor(n.apiProduct,t,i)));for(const n of o)n.teamName=B(n.owner,r),n.apiProductName=$(i,n.apiProduct);return o})}}R=new WeakMap,j=new WeakMap;function B(s,e){return s.kind==="team"?e.get(s.teamId):void 0}function $(s,e){var i;return(i=s.find(t=>t.name===e))===null||i===void 0?void 0:i.displayName}function M(s){const{myRole:e}=s;return I(s,["myRole"])}function Q(s){if(!s.some(e=>e.role==="owner"))throw new y("A team needs at least one owner")}function ee(s){if(!Array.isArray(s)||s.some(e=>typeof e!="string"))throw new y("apiProducts must be a list of product names");return s}function te(s){if(typeof s!="string"||!pe.test(s.trim()))throw new y("An app name has 1 to 100 letters, digits, spaces, dots, dashes or underscores");const e=s.trim();if(me.has(e))throw new y(`An app cannot be named "${e}"`);return e}function A(s,e,i){if(s==null)return;if(typeof s!="string")throw new y(`${i} must be text`);const t=s.trim();if(t.length>e)throw new y(`${i} is longer than ${e} characters`);return t}function ie(s){const e=A(s,fe,"callbackUrl");if(!e)return e===""?"":void 0;for(const i of e.split(","))try{new URL(i.trim())}catch{throw new y(`"${i.trim()}" is not a valid callback URL`)}return e}function be(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 y("Enter a valid email address");return _(e)}function re(s){if(s===void 0)return"member";if(s!=="owner"&&s!=="member")throw new y("Unknown role");return s}export{Re as ApigeeService,q as ForbiddenError,b as NotFoundError,y 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.1",
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.8",
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.8",
41
+ "@redocly/theme": "0.73.0-next.3",
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
+ }