@flumens/models 0.32.0 → 0.32.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.
@@ -28,7 +28,7 @@ export type BackendConfig = {
28
28
  */
29
29
  clientPass?: string;
30
30
  /**
31
- * User scopes (roles to fetch).
31
+ * OAuth scopes to request. Defaults to ['authenticated']; use [] to omit.
32
32
  */
33
33
  scopes?: string[];
34
34
  };
@@ -1 +1 @@
1
- import{__rest as e,__awaiter as i}from"tslib";import t from"axios";import{jwtDecode as s}from"jwt-decode";import{object as r,z as o}from"zod";import{HandledError as n}from"@flumens/utils";import a from"../Model.mjs";function d(e){const i={};return Object.keys(e).forEach((t=>{if(t.match(/^field_/)){const s=t.replace("field_","").replace(/_([a-z])/g,(e=>e[1].toUpperCase()));if(!e[t])return;if(Array.isArray(e[t])&&e[t].length)return void(i[s]=e[t][0].value);i[s]=e[t]}})),i}var c;!function(e){e.EmailTaken="AUTH_EMAIL_TAKEN",e.InvalidCredentials="AUTH_INVALID_CREDENTIALS",e.UnrecognizedEmail="AUTH_UNRECOGNIZED_EMAIL",e.AccountAlreadyActivated="AUTH_ACCOUNT_ALREADY_ACTIVATED",e.AccountInactive="AUTH_ACCOUNT_INACTIVE",e.Timeout="AUTH_REQUEST_TIMEOUT"}(c||(c={}));class h extends n{constructor(e,i,t){super(i),this.name="DrupalUserError",this.code=e,this.cause=t}}const l=e=>{var i,t,s,r,o;const n=(null===(t=null===(i=e.response)||void 0===i?void 0:i.data)||void 0===t?void 0:t.error_description)||(null===(r=null===(s=e.response)||void 0===s?void 0:s.data)||void 0===r?void 0:r.message);if(n){if(n.includes("is already taken"))throw new h(c.EmailTaken,"This email is already taken.",e);if("The user credentials were incorrect."===n)throw new h(c.InvalidCredentials,"Incorrect password or email",e);if("Unrecognized username or email address."===n)throw new h(c.UnrecognizedEmail,"Unrecognized email address.",e);if("This account is already activated"===n)throw new h(c.AccountAlreadyActivated,"This account is already activated.",e);if(n.includes("not been activated"))throw new h(c.AccountInactive,"The user has not been activated or is blocked.",e);throw new Error(n)}if(null===(o=e.message)||void 0===o?void 0:o.includes("timeout"))throw new h(c.Timeout,"Timeout",e);throw e},u=6e4;const f={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0,profileFetched:!1};class m extends a{constructor(i){var{config:t}=i,s=e(i,["config"]);super(Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},f),s.data)})),this.config=t}logIn(e,t){return i(this,void 0,void 0,(function*(){const i=yield this._exchangePasswordToTokens(e,t);return this.data.tokens=i,yield this.refreshProfile(),this.save()}))}register(e,s,r){return i(this,void 0,void 0,(function*(){const i=JSON.stringify(Object.assign({name:[{value:e}],pass:[{value:s}],mail:[{value:e}]},r)),o={method:"post",url:`${this.config.url}/user/register-with-password?_format=json`,headers:{"content-type":"application/json"},data:i,timeout:u},{data:n}=yield t(o).catch(l);if(!!m.registerSchemaBackend.safeParse(n).error)throw new Error("Invalid backend response.");const a=yield this._exchangePasswordToTokens(e,s);this.id=n.uid[0].value;const c=d(n);return Object.assign(this.data,Object.assign({email:e,tokens:a,profileFetched:!0},c)),this.save()}))}resetPassword(e){return i(this,void 0,void 0,(function*(){const i=JSON.stringify({mail:e}),s={method:"post",url:`${this.config.url}/user/password?_format=json`,headers:{"content-type":"application/json"},data:i};try{yield t(s).catch(l)}catch(i){if("The user has not been activated or is blocked."===i.message)return void(yield this._sendVerificationEmail(e));l(i)}}))}delete(){return i(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0),i={method:"delete",url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`}};yield t(i).catch(l),this.logOut()}))}updateRemote(e){return i(this,void 0,void 0,(function*(){const i=yield this.getAccessToken(),s={method:"patch",url:`${this.config.url}/user/${this.id}?_format=json`,data:e,headers:{Authorization:`Bearer ${i}`},timeout:u};yield t(s),yield this._refreshAccessToken(),this.save()}))}refreshProfile(){return i(this,void 0,void 0,(function*(){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((()=>i(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0);if(this.data.verified){const i={url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`},timeout:u},{data:s}=yield t(i).catch(l),r=d(s);Object.assign(this.data,Object.assign({email:s.mail[0].value,profileFetched:!0},r))}yield this.save(),delete this._refreshingProfilePromise})))).catch((e=>{throw delete this._refreshingProfilePromise,e}))),this._refreshingProfilePromise}))}hasLogIn(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()}isLoggedIn(){return this.data.email,!!this.id}logOut(){return i(this,void 0,void 0,(function*(){return this.reset()}))}reset(e){return super.reset(Object.assign(Object.assign({},f),e))}getAccessToken(e){return i(this,void 0,void 0,(function*(){if(!e&&!this.isLoggedIn())throw new Error("User is not logged in.");const{access_token:i}=this.data.tokens||{},t=function(e){if(!e)return!0;const{exp:i}=s(e),t=1e3*i;return Date.now()+12e4>t}(i);if(!i||t||e)try{yield this._refreshAccessToken()}catch(e){console.error(e);const i="The refresh token is invalid."===e.message,t="Token has no user email."===e.message;if(i||t)throw yield this.logOut(),new Error("User re-login is required.");throw e}return this.data.tokens.access_token}))}_sendVerificationEmail(e){return i(this,void 0,void 0,(function*(){const i=JSON.stringify({mail:[{value:e||this.data.email}]}),s={method:"post",url:`${this.config.url}/user/register-with-password?_format=json&resendVerificationEmail=true`,headers:{"content-type":"application/json"},data:i,timeout:u};return t(s).catch(l)}))}_exchangePasswordToTokens(e,s){return i(this,void 0,void 0,(function*(){var i;const r=new FormData;r.append("grant_type","password"),r.append("username",e),r.append("password",s),r.append("client_id",this.config.clientId),this.config.clientPass&&r.append("client_secret",this.config.clientPass),(null===(i=this.config.scopes)||void 0===i?void 0:i.length)&&r.append("scope",this.config.scopes.join(" "));const o={method:"post",url:`${this.config.url}/oauth/token`,data:r},{data:n}=yield t(o).catch(l);return n}))}_refreshAccessToken(){return i(this,void 0,void 0,(function*(){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((()=>i(this,void 0,void 0,(function*(){const{refresh_token:e}=this.data.tokens||{};if(!e)throw new Error("No user session refresh token was found");const i=new FormData;i.append("grant_type","refresh_token"),i.append("refresh_token",e),i.append("client_id",this.config.clientId),this.config.clientPass&&i.append("client_secret",this.config.clientPass);const r={method:"post",url:`${this.config.url}/oauth/token`,data:i,timeout:u},{data:o}=yield t(r).catch(l),n=Object.assign(Object.assign({},this.data.tokens),o),a=s(n.access_token),{email:c}=a;if(!c)throw new Error("Token has no user email.");const{iss:h,email_verified:f}=a,m=a["http://indicia.org.uk/user:id"],g=a.scopes,v=d(a);this.id=a.sub,Object.assign(this.data,Object.assign({email:c,roles:g,verified:f,iss:h,indiciaUserId:m,tokens:n},v)),yield this.save(),delete this._refreshingTokenPromise})))).catch((e=>{throw delete this._refreshingTokenPromise,e}))),this._refreshingTokenPromise}))}}m.loginSchema=r({email:o.string().email("Please fill in"),password:o.string().min(1,"Please fill in")}),m.loginSchemaBackend=r({id:o.number(),email:o.string().email()}),m.resetSchema=r({email:o.string().email("Please fill in")}),m.registerSchema=r({email:o.string().email("Please fill in"),password:o.string().min(1,"Please fill in")}),m.registerSchemaBackend=r({uid:o.array(r({value:o.number()}))});export{h as DrupalUserError,c as DrupalUserErrorCode,m as default};
1
+ import{__rest as e,__awaiter as i}from"tslib";import t from"axios";import{jwtDecode as s}from"jwt-decode";import{object as r,z as n}from"zod";import{HandledError as o}from"@flumens/utils";import a from"../Model.mjs";function d(e){const i={};return Object.keys(e).forEach((t=>{if(t.match(/^field_/)){const s=t.replace("field_","").replace(/_([a-z])/g,(e=>e[1].toUpperCase()));if(!e[t])return;if(Array.isArray(e[t])&&e[t].length)return void(i[s]=e[t][0].value);i[s]=e[t]}})),i}var c;!function(e){e.EmailTaken="AUTH_EMAIL_TAKEN",e.InvalidCredentials="AUTH_INVALID_CREDENTIALS",e.UnrecognizedEmail="AUTH_UNRECOGNIZED_EMAIL",e.AccountAlreadyActivated="AUTH_ACCOUNT_ALREADY_ACTIVATED",e.AccountInactive="AUTH_ACCOUNT_INACTIVE",e.Timeout="AUTH_REQUEST_TIMEOUT"}(c||(c={}));class h extends o{constructor(e,i,t){super(i),this.name="DrupalUserError",this.code=e,this.cause=t}}const l=e=>{var i,t,s,r,n;const o=(null===(t=null===(i=e.response)||void 0===i?void 0:i.data)||void 0===t?void 0:t.error_description)||(null===(r=null===(s=e.response)||void 0===s?void 0:s.data)||void 0===r?void 0:r.message);if(o){if(o.includes("is already taken"))throw new h(c.EmailTaken,"This email is already taken.",e);if("The user credentials were incorrect."===o)throw new h(c.InvalidCredentials,"Incorrect password or email",e);if("Unrecognized username or email address."===o)throw new h(c.UnrecognizedEmail,"Unrecognized email address.",e);if("This account is already activated"===o)throw new h(c.AccountAlreadyActivated,"This account is already activated.",e);if(o.includes("not been activated"))throw new h(c.AccountInactive,"The user has not been activated or is blocked.",e);throw new Error(o)}if(null===(n=e.message)||void 0===n?void 0:n.includes("timeout"))throw new h(c.Timeout,"Timeout",e);throw e},u=6e4;const f={email:"",tokens:void 0,verified:!1,iss:void 0,indiciaUserId:void 0,profileFetched:!1};class m extends a{constructor(i){var{config:t}=i,s=e(i,["config"]);super(Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},f),s.data)})),this.config=t}logIn(e,t){return i(this,void 0,void 0,(function*(){const i=yield this._exchangePasswordToTokens(e,t);return this.data.tokens=i,yield this.refreshProfile(),this.save()}))}register(e,s,r){return i(this,void 0,void 0,(function*(){const i=JSON.stringify(Object.assign({name:[{value:e}],pass:[{value:s}],mail:[{value:e}]},r)),n={method:"post",url:`${this.config.url}/user/register-with-password?_format=json`,headers:{"content-type":"application/json"},data:i,timeout:u},{data:o}=yield t(n).catch(l);if(!!m.registerSchemaBackend.safeParse(o).error)throw new Error("Invalid backend response.");const a=yield this._exchangePasswordToTokens(e,s);this.id=o.uid[0].value;const c=d(o);return Object.assign(this.data,Object.assign({email:e,tokens:a,profileFetched:!0},c)),this.save()}))}resetPassword(e){return i(this,void 0,void 0,(function*(){const i=JSON.stringify({mail:e}),s={method:"post",url:`${this.config.url}/user/password?_format=json`,headers:{"content-type":"application/json"},data:i};try{yield t(s).catch(l)}catch(i){if("The user has not been activated or is blocked."===i.message)return void(yield this._sendVerificationEmail(e));l(i)}}))}delete(){return i(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0),i={method:"delete",url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`}};yield t(i).catch(l),this.logOut()}))}updateRemote(e){return i(this,void 0,void 0,(function*(){const i=yield this.getAccessToken(),s={method:"patch",url:`${this.config.url}/user/${this.id}?_format=json`,data:e,headers:{Authorization:`Bearer ${i}`},timeout:u};yield t(s),yield this._refreshAccessToken(),this.save()}))}refreshProfile(){return i(this,void 0,void 0,(function*(){return this._refreshingProfilePromise||(this._refreshingProfilePromise=Promise.resolve().then((()=>i(this,void 0,void 0,(function*(){const e=yield this.getAccessToken(!0);if(this.data.verified){const i={url:`${this.config.url}/user/${this.id}?_format=json`,headers:{Authorization:`Bearer ${e}`},timeout:u},{data:s}=yield t(i).catch(l),r=d(s);Object.assign(this.data,Object.assign({email:s.mail[0].value,profileFetched:!0},r))}yield this.save(),delete this._refreshingProfilePromise})))).catch((e=>{throw delete this._refreshingProfilePromise,e}))),this._refreshingProfilePromise}))}hasLogIn(){return console.warn("hasLogIn is deprecated, please use isLoggedIn instead."),this.isLoggedIn()}isLoggedIn(){return this.data.email,!!this.id}logOut(){return i(this,void 0,void 0,(function*(){return this.reset()}))}reset(e){return super.reset(Object.assign(Object.assign({},f),e))}getAccessToken(e){return i(this,void 0,void 0,(function*(){if(!e&&!this.isLoggedIn())throw new Error("User is not logged in.");const{access_token:i}=this.data.tokens||{},t=function(e){if(!e)return!0;const{exp:i}=s(e),t=1e3*i;return Date.now()+12e4>t}(i);if(!i||t||e)try{yield this._refreshAccessToken()}catch(e){console.error(e);const i="The refresh token is invalid."===e.message,t="Token has no user email."===e.message;if(i||t)throw yield this.logOut(),new Error("User re-login is required.");throw e}return this.data.tokens.access_token}))}_sendVerificationEmail(e){return i(this,void 0,void 0,(function*(){const i=JSON.stringify({mail:[{value:e||this.data.email}]}),s={method:"post",url:`${this.config.url}/user/register-with-password?_format=json&resendVerificationEmail=true`,headers:{"content-type":"application/json"},data:i,timeout:u};return t(s).catch(l)}))}_exchangePasswordToTokens(e,s){return i(this,void 0,void 0,(function*(){var i;const r=null!==(i=this.config.scopes)&&void 0!==i?i:["authenticated"],n=new FormData;n.append("grant_type","password"),n.append("username",e),n.append("password",s),n.append("client_id",this.config.clientId),this.config.clientPass&&n.append("client_secret",this.config.clientPass),r.length&&n.append("scope",r.join(" "));const o={method:"post",url:`${this.config.url}/oauth/token`,data:n},{data:a}=yield t(o).catch(l);return a}))}_refreshAccessToken(){return i(this,void 0,void 0,(function*(){return this._refreshingTokenPromise||(this._refreshingTokenPromise=Promise.resolve().then((()=>i(this,void 0,void 0,(function*(){const{refresh_token:e}=this.data.tokens||{};if(!e)throw new Error("No user session refresh token was found");const i=new FormData;i.append("grant_type","refresh_token"),i.append("refresh_token",e),i.append("client_id",this.config.clientId),this.config.clientPass&&i.append("client_secret",this.config.clientPass);const r={method:"post",url:`${this.config.url}/oauth/token`,data:i,timeout:u},{data:n}=yield t(r).catch(l),o=Object.assign(Object.assign({},this.data.tokens),n),a=s(o.access_token),{email:c}=a;if(!c)throw new Error("Token has no user email.");const{iss:h,email_verified:f}=a,m=a["http://indicia.org.uk/user:id"],g=a.scopes,v=d(a);this.id=a.sub,Object.assign(this.data,Object.assign({email:c,roles:g,verified:f,iss:h,indiciaUserId:m,tokens:o},v)),yield this.save(),delete this._refreshingTokenPromise})))).catch((e=>{throw delete this._refreshingTokenPromise,e}))),this._refreshingTokenPromise}))}}m.loginSchema=r({email:n.string().email("Please fill in"),password:n.string().min(1,"Please fill in")}),m.loginSchemaBackend=r({id:n.number(),email:n.string().email()}),m.resetSchema=r({email:n.string().email("Please fill in")}),m.registerSchema=r({email:n.string().email("Please fill in"),password:n.string().min(1,"Please fill in")}),m.registerSchemaBackend=r({uid:n.array(r({value:n.number()}))});export{h as DrupalUserError,c as DrupalUserErrorCode,m as default};
@@ -1 +1 @@
1
- import{__awaiter as e}from"tslib";import t from"node:assert/strict";import{test as o}from"node:test";import{MailSlurp as n}from"mailslurp-client";const i=12e4,a="https://example.com",r="http://indicia.org.uk/user:id";function s(e){console.info(`[user lifecycle] ${e}`)}function d(e){const o=process.env[e];return t.ok(o,`${e} must be set`),o}const l=new URL(d("DRUPAL_SITE_URL")),c=d("APP_BACKEND_CLIENT_ID"),u=process.env.APP_BACKEND_CLIENT_PASS,f=new n({apiKey:d("MAILSLURP_API_KEY")});function m(e){return new URL(e,l)}function h(e){return`'${e.replaceAll("'","'\\''")}'`}function p(e,t={}){const o=["curl",`--request ${t.method||"GET"}`,h(e.toString())];if(new Headers(t.headers).forEach(((e,t)=>{o.push(`--header ${h(`${t}: ${e}`)}`)})),t.body instanceof FormData)for(const[e,n]of t.body.entries())o.push(`--form ${h(`${e}=${String(n)}`)}`);if(t.body instanceof URLSearchParams)for(const[e,n]of t.body.entries())o.push(`--data-urlencode ${h(`${e}=${n}`)}`);return"string"==typeof t.body&&o.push(`--data ${h(t.body)}`),o.map(((e,t)=>t?` ${e}`:e)).join(" \\\n")}function v(e){console.error(`[user lifecycle] Failed request:\n${e}`)}function y(e,o){const n=e.headers.get("access-control-allow-origin"),i="*"===n||n===a;i||v(o),t.ok(i,`${e.url} returned ${e.status} with Access-Control-Allow-Origin: ${n||"missing"}`)}function g(t){return e(this,arguments,void 0,(function*(e,t={}){const o=m(e),n=new Headers(t.headers);n.set("Origin",a);const i=Object.assign(Object.assign({},t),{headers:n}),r=p(o,i);let s;try{s=yield fetch(o,i)}catch(e){throw v(r),e}return y(s,r),{response:s,curl:r}}))}function k(o,n){return e(this,arguments,void 0,(function*(e,o,n=[]){var i,r;const d=new Headers({Origin:a,"Access-Control-Request-Method":o});n.length&&d.set("Access-Control-Request-Headers",n.join(", "));const l=m(e),c={method:"OPTIONS",headers:d},u=p(l,c);let f;try{f=yield fetch(l,c)}catch(e){throw v(u),e}y(f,u);const h=(null===(i=f.headers.get("access-control-allow-methods"))||void 0===i?void 0:i.toUpperCase())||"",g=(null===(r=f.headers.get("access-control-allow-headers"))||void 0===r?void 0:r.toLowerCase())||"";f.ok&&(h.includes("*")||h.includes(o))&&!n.some((e=>!g.includes(e)))||v(u),t.ok(f.ok,`CORS preflight returned ${f.status}`),t.ok(h.includes("*")||h.includes(o),`CORS preflight did not allow ${o}`);for(const e of n)t.ok(g.includes(e),`CORS preflight did not allow ${e}`);s(`Validated CORS preflight for ${o} ${l.pathname}`)}))}function _(t){return e(this,arguments,void 0,(function*(t,o={}){const{response:n,curl:i}=yield g(t,o);return yield function(t,o){return e(this,void 0,void 0,(function*(){if(!t.ok)throw v(o),new Error(`${t.url} returned ${t.status}: ${yield t.text()}`);s(`Received ${t.status} from ${new URL(t.url).pathname}`)}))}(n,i),n}))}function w(e,t){const o=new FormData;return o.append("grant_type","password"),o.append("username",e),o.append("password",t),o.append("client_id",c),u&&o.append("client_secret",u),o}function $(e){const t=new FormData;return t.append("grant_type","refresh_token"),t.append("refresh_token",e),t.append("client_id",c),u&&t.append("client_secret",u),t}function S(e){const o=e.split(".")[1];return t.ok(o,"Access token is not a JWT"),JSON.parse(Buffer.from(o,"base64url").toString())}function j(e,o,n){const i=S(e);t.equal(i.email,o),t.equal(i.email_verified,n),t.ok(i[r],`JWT did not include ${r}`),s(`Validated JWT email, verification, and ${r}`)}function E(o){return e(this,void 0,void 0,(function*(){var e;const n=(o.isHTML?(yield f.emailController.getEmailLinks({emailId:o.id})).links:(null===(e=o.body)||void 0===e?void 0:e.match(/https?:\/\/[^\s"'<>]+/g))||[]).map((e=>e.replaceAll("&amp;","&"))),i=n.find((e=>{const t=new URL(e,l);return/\/user\/(?:registrationpassword|reset)\//.test(t.pathname)}));return i||s(`Email links found: ${n.join(", ")||"none"}`),t.ok(i,"Drupal account link was not found in the email"),i}))}o("supports browser CORS requests",(()=>e(void 0,void 0,void 0,(function*(){yield k("/oauth/token","POST"),yield k("/user/register-with-password?_format=json","POST",["content-type"]),yield k("/user/register-with-password?_format=json&resendVerificationEmail=true","POST",["content-type"]),yield k("/user/password?_format=json","POST",["content-type"]),yield k("/user/1?_format=json","GET",["authorization"]),yield k("/user/1?_format=json","PATCH",["authorization","content-type"]),yield k("/user/1?_format=json","DELETE",["authorization"]),yield k("/user/login_status?_format=json","GET",["authorization"])})))),o("completes the Drupal user account lifecycle",{timeout:3e5},(o=>e(void 0,void 0,void 0,(function*(){var n,a,r,d,c,u,h,y,k,T,C,O,R,b;s(`Starting test against ${l.origin}`),s("Creating temporary MailSlurp inbox");const P=yield f.createInbox(),D=P.emailAddress,A=`E2e-${crypto.randomUUID()}-aA1!`,q="User",L="Updated",U="E2E User";let I,N,F,z=!1;t.ok(D,"MailSlurp did not create an email address"),o.after((()=>e(void 0,void 0,void 0,(function*(){s("Cleaning up test resources");const e=[f.deleteInbox(P.id)];F&&I&&!z&&(s(`Deleting Drupal account ${F} during cleanup`),e.push(fetch(m(`/user/${F}?_format=json`),{method:"DELETE",headers:{Authorization:`Bearer ${I}`}}).then((e=>{e.ok||s(`Drupal account ${F} requires manual cleanup after delete returned ${e.status}`)})))),!F||I||z||s(`Drupal account ${F} requires manual cleanup because no access token was obtained`),yield Promise.allSettled(e),s("Cleanup complete")})))),s("Creating Drupal account");const J=yield _("/user/register-with-password?_format=json",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:[{value:D}],pass:[{value:A}],mail:[{value:D}],field_first_name:[{value:"E2E"}],field_last_name:[{value:q}]})}),V=yield J.json();F=null===(a=null===(n=V.uid)||void 0===n?void 0:n[0])||void 0===a?void 0:a.value,t.ok(F,"Registration response did not include a user ID"),s(`Created Drupal account ${F}`),s("Following the model registration login before verification");const B=yield _("/oauth/token",{method:"POST",body:w(D,A)}),x=yield B.json();I=x.access_token,N=x.refresh_token,t.ok(I,"Registration login did not return an access token"),t.ok(N,"Registration login did not return a refresh token"),j(I,D,!1),s("Confirmed the account can log in but remains unverified"),s("Waiting for account verification email");const H=yield f.waitForLatestEmail(P.id,i,!0);s("Received account verification email"),yield E(H),s("Validated initial account verification email"),s("Requesting a password reset for the unverified account"),yield _("/user/password?_format=json",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mail:D})}),s("Requesting a verification email for the unverified account"),yield _("/user/register-with-password?_format=json&resendVerificationEmail=true",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mail:[{value:D}]})}),s("Waiting for resent account verification email");const W=yield f.waitForLatestEmail(P.id,i,!0);t.notEqual(W.id,H.id,"Verification email was not resent");const M=yield E(W);s("Received resent account verification email"),s("Opening resent account verification link");const K={redirect:"manual"},G=p(new URL(M),K);let Y;try{Y=yield fetch(M,K)}catch(e){throw v(G),e}let Q=Y.ok||Y.status>=300&&Y.status<400;if(Q||v(G),504===Y.status){s("Checking whether the timed-out verification completed");const e=yield _("/oauth/token",{method:"POST",body:w(D,A)});Q=!0===S((yield e.json()).access_token).email_verified}t.ok(Q,`Verification returned ${Y.status}`),s(`Verified account with response ${Y.status}`),s("Requesting access and refresh tokens");const X=yield _("/oauth/token",{method:"POST",body:w(D,A)}),Z=yield X.json();I=Z.access_token,N=Z.refresh_token,t.ok(I,"Password grant did not return an access token"),t.ok(N,"Password grant did not return a refresh token"),j(I,D,!0),s("Received access and refresh tokens"),s("Fetching and validating account data");const ee=yield _(`/user/${F}?_format=json`,{headers:{Authorization:`Bearer ${I}`}}),te=yield ee.json();t.equal(null===(d=null===(r=te.name)||void 0===r?void 0:r[0])||void 0===d?void 0:d.value,D),t.equal(null===(u=null===(c=te.mail)||void 0===c?void 0:c[0])||void 0===u?void 0:u.value,D),t.equal(null===(y=null===(h=te.field_first_name)||void 0===h?void 0:h[0])||void 0===y?void 0:y.value,"E2E"),t.equal(null===(T=null===(k=te.field_last_name)||void 0===k?void 0:k[0])||void 0===T?void 0:T.value,q),s("Validated account name, email, first name, and last name"),s("Updating account first and last names"),yield _(`/user/${F}?_format=json`,{method:"PATCH",headers:{Authorization:`Bearer ${I}`,"Content-Type":"application/json"},body:JSON.stringify({field_first_name:[{value:L}],field_last_name:[{value:U}]})}),s("Refreshing access token after account update");const oe=yield _("/oauth/token",{method:"POST",body:$(N)}),ne=yield oe.json();I=ne.access_token,N=ne.refresh_token||N,t.ok(I,"Refresh grant did not return an access token"),t.ok(N,"Refresh grant did not retain a refresh token"),j(I,D,!0),s("Refreshed access token after account update"),s("Fetching and validating updated account data");const ie=yield _(`/user/${F}?_format=json`,{headers:{Authorization:`Bearer ${I}`}}),ae=yield ie.json();t.equal(null===(O=null===(C=ae.field_first_name)||void 0===C?void 0:C[0])||void 0===O?void 0:O.value,L),t.equal(null===(b=null===(R=ae.field_last_name)||void 0===R?void 0:R[0])||void 0===b?void 0:b.value,U),s("Updated and validated account data"),s("Requesting password reset email"),yield _("/user/password?_format=json",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mail:D})}),s("Waiting for password reset email");const re=yield f.waitForLatestEmail(P.id,i,!0);t.ok(re.to.includes(D),"Password reset email was not sent to the test account"),s("Received password reset email"),s("Deleting Drupal account"),yield _(`/user/${F}?_format=json`,{method:"DELETE",headers:{Authorization:`Bearer ${I}`}}),z=!0,s("Checking the refresh token after account deletion");const se=$(N),{response:de,curl:le}=yield g("/oauth/token",{method:"POST",body:se});if(de.ok){const e=S((yield de.json()).access_token);t.equal(e.email,void 0,"Deleted account unexpectedly received a usable token"),s("Confirmed the deleted account token has no user email")}else{const e=yield de.text();v(le),t.match(e,/invalid|revoked|user|email/i),s(`Confirmed refresh was rejected with ${de.status}`)}s("Deleted Drupal account; lifecycle complete")}))));
1
+ import{__awaiter as e}from"tslib";import{MailSlurp as t}from"mailslurp-client";import o from"node:assert/strict";import{test as n}from"node:test";const i=12e4,a="https://example.com",r="http://indicia.org.uk/user:id",s="authenticated";function d(e){console.info(`[user lifecycle] ${e}`)}function l(e){const t=process.env[e];return o.ok(t,`${e} must be set`),t}const c=new URL(l("DRUPAL_SITE_URL")),u=l("APP_BACKEND_CLIENT_ID"),f=process.env.APP_BACKEND_CLIENT_PASS,p=new t({apiKey:l("MAILSLURP_API_KEY")});function h(e){return new URL(e,c)}function m(e){return`'${e.replaceAll("'","'\\''")}'`}function v(e,t={}){const o=["curl",`--request ${t.method||"GET"}`,m(e.toString())];if(new Headers(t.headers).forEach(((e,t)=>{o.push(`--header ${m(`${t}: ${e}`)}`)})),t.body instanceof FormData)for(const[e,n]of t.body.entries())o.push(`--form ${m(`${e}=${String(n)}`)}`);if(t.body instanceof URLSearchParams)for(const[e,n]of t.body.entries())o.push(`--data-urlencode ${m(`${e}=${n}`)}`);return"string"==typeof t.body&&o.push(`--data ${m(t.body)}`),o.map(((e,t)=>t?` ${e}`:e)).join(" \\\n")}function y(e){console.error(`[user lifecycle] Failed request:\n${e}`)}function g(e,t){const n=e.headers.get("access-control-allow-origin"),i="*"===n||n===a;i||y(t),o.ok(i,`${e.url} returned ${e.status} with Access-Control-Allow-Origin: ${n||"missing"}`)}function k(t){return e(this,arguments,void 0,(function*(e,t={}){const o=h(e),n=new Headers(t.headers);n.set("Origin",a);const i=Object.assign(Object.assign({},t),{headers:n}),r=v(o,i);let s;try{s=yield fetch(o,i)}catch(e){throw y(r),e}return g(s,r),{response:s,curl:r}}))}function _(t,n){return e(this,arguments,void 0,(function*(e,t,n=[]){var i,r;const s=new Headers({Origin:a,"Access-Control-Request-Method":t});n.length&&s.set("Access-Control-Request-Headers",n.join(", "));const l=h(e),c={method:"OPTIONS",headers:s},u=v(l,c);let f;try{f=yield fetch(l,c)}catch(e){throw y(u),e}g(f,u);const p=(null===(i=f.headers.get("access-control-allow-methods"))||void 0===i?void 0:i.toUpperCase())||"",m=(null===(r=f.headers.get("access-control-allow-headers"))||void 0===r?void 0:r.toLowerCase())||"";f.ok&&(p.includes("*")||p.includes(t))&&!n.some((e=>!m.includes(e)))||y(u),o.ok(f.ok,`CORS preflight returned ${f.status}`),o.ok(p.includes("*")||p.includes(t),`CORS preflight did not allow ${t}`);for(const e of n)o.ok(m.includes(e),`CORS preflight did not allow ${e}`);d(`Validated CORS preflight for ${t} ${l.pathname}`)}))}function w(t){return e(this,arguments,void 0,(function*(t,o={}){const{response:n,curl:i}=yield k(t,o);return yield function(t,o){return e(this,void 0,void 0,(function*(){if(!t.ok)throw y(o),new Error(`${t.url} returned ${t.status}: ${yield t.text()}`);d(`Received ${t.status} from ${new URL(t.url).pathname}`)}))}(n,i),n}))}function $(e,t){const o=new FormData;return o.append("grant_type","password"),o.append("scope",s),o.append("username",e),o.append("password",t),o.append("client_id",u),f&&o.append("client_secret",f),o}function S(e){const t=new FormData;return t.append("grant_type","refresh_token"),t.append("refresh_token",e),t.append("client_id",u),f&&t.append("client_secret",f),t}function j(e){const t=e.split(".")[1];o.ok(t,"Access token is not a JWT");const n=JSON.parse(Buffer.from(t,"base64url").toString());return o.ok(Array.isArray(n.scope)&&n.scope.includes(s),`JWT did not include the ${s} scope`),n}function E(e,t,n){const i=j(e);o.equal(i.email,t),o.equal(i.email_verified,n),o.ok(i[r],`JWT did not include ${r}`),d(`Validated JWT email, verification, and ${r}`)}function T(t){return e(this,void 0,void 0,(function*(){var e;const n=(t.isHTML?(yield p.emailController.getEmailLinks({emailId:t.id})).links:(null===(e=t.body)||void 0===e?void 0:e.match(/https?:\/\/[^\s"'<>]+/g))||[]).map((e=>e.replaceAll("&amp;","&"))),i=n.find((e=>{const t=new URL(e,c);return/\/user\/(?:registrationpassword|reset)\//.test(t.pathname)}));return i||d(`Email links found: ${n.join(", ")||"none"}`),o.ok(i,"Drupal account link was not found in the email"),i}))}n("supports browser CORS requests",(()=>e(void 0,void 0,void 0,(function*(){yield _("/oauth/token","POST"),yield _("/user/register-with-password?_format=json","POST",["content-type"]),yield _("/user/register-with-password?_format=json&resendVerificationEmail=true","POST",["content-type"]),yield _("/user/password?_format=json","POST",["content-type"]),yield _("/user/1?_format=json","GET",["authorization"]),yield _("/user/1?_format=json","PATCH",["authorization","content-type"]),yield _("/user/1?_format=json","DELETE",["authorization"]),yield _("/user/login_status?_format=json","GET",["authorization"])})))),n("completes the Drupal user account lifecycle",{timeout:3e5},(t=>e(void 0,void 0,void 0,(function*(){var n,a,r,s,l,u,f,m,g,_,C,O,R,b;d(`Starting test against ${c.origin}`),d("Creating temporary MailSlurp inbox");const P=yield p.createInbox(),A=P.emailAddress,D=`E2e-${crypto.randomUUID()}-aA1!`,q="User",L="Updated",U="E2E User";let I,N,F,J=!1;o.ok(A,"MailSlurp did not create an email address"),t.after((()=>e(void 0,void 0,void 0,(function*(){d("Cleaning up test resources");const e=[p.deleteInbox(P.id)];F&&I&&!J&&(d(`Deleting Drupal account ${F} during cleanup`),e.push(fetch(h(`/user/${F}?_format=json`),{method:"DELETE",headers:{Authorization:`Bearer ${I}`}}).then((e=>{e.ok||d(`Drupal account ${F} requires manual cleanup after delete returned ${e.status}`)})))),!F||I||J||d(`Drupal account ${F} requires manual cleanup because no access token was obtained`),yield Promise.allSettled(e),d("Cleanup complete")})))),d("Creating Drupal account");const z=yield w("/user/register-with-password?_format=json",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:[{value:A}],pass:[{value:D}],mail:[{value:A}],field_first_name:[{value:"E2E"}],field_last_name:[{value:q}]})}),V=yield z.json();F=null===(a=null===(n=V.uid)||void 0===n?void 0:n[0])||void 0===a?void 0:a.value,o.ok(F,"Registration response did not include a user ID"),d(`Created Drupal account ${F}`),d("Following the model registration login before verification");const B=yield w("/oauth/token",{method:"POST",body:$(A,D)}),x=yield B.json();I=x.access_token,N=x.refresh_token,o.ok(I,"Registration login did not return an access token"),o.ok(N,"Registration login did not return a refresh token"),E(I,A,!1),d("Confirmed the account can log in but remains unverified"),d("Waiting for account verification email");const H=yield p.waitForLatestEmail(P.id,i,!0);d("Received account verification email"),yield T(H),d("Validated initial account verification email"),d("Requesting a password reset for the unverified account"),yield w("/user/password?_format=json",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mail:A})}),d("Requesting a verification email for the unverified account"),yield w("/user/register-with-password?_format=json&resendVerificationEmail=true",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mail:[{value:A}]})}),d("Waiting for resent account verification email");const W=yield p.waitForLatestEmail(P.id,i,!0);o.notEqual(W.id,H.id,"Verification email was not resent");const M=yield T(W);d("Received resent account verification email"),d("Opening resent account verification link");const K={redirect:"manual"},G=v(new URL(M),K);let Y;try{Y=yield fetch(M,K)}catch(e){throw y(G),e}let Q=Y.ok||Y.status>=300&&Y.status<400;if(Q||y(G),504===Y.status){d("Checking whether the timed-out verification completed");const e=yield w("/oauth/token",{method:"POST",body:$(A,D)});Q=!0===j((yield e.json()).access_token).email_verified}o.ok(Q,`Verification returned ${Y.status}`),d(`Verified account with response ${Y.status}`),d("Requesting access and refresh tokens");const X=yield w("/oauth/token",{method:"POST",body:$(A,D)}),Z=yield X.json();I=Z.access_token,N=Z.refresh_token,o.ok(I,"Password grant did not return an access token"),o.ok(N,"Password grant did not return a refresh token"),E(I,A,!0),d("Received access and refresh tokens"),d("Fetching and validating account data");const ee=yield w(`/user/${F}?_format=json`,{headers:{Authorization:`Bearer ${I}`}}),te=yield ee.json();o.equal(null===(s=null===(r=te.name)||void 0===r?void 0:r[0])||void 0===s?void 0:s.value,A),o.equal(null===(u=null===(l=te.mail)||void 0===l?void 0:l[0])||void 0===u?void 0:u.value,A),o.equal(null===(m=null===(f=te.field_first_name)||void 0===f?void 0:f[0])||void 0===m?void 0:m.value,"E2E"),o.equal(null===(_=null===(g=te.field_last_name)||void 0===g?void 0:g[0])||void 0===_?void 0:_.value,q),d("Validated account name, email, first name, and last name"),d("Updating account first and last names"),yield w(`/user/${F}?_format=json`,{method:"PATCH",headers:{Authorization:`Bearer ${I}`,"Content-Type":"application/json"},body:JSON.stringify({field_first_name:[{value:L}],field_last_name:[{value:U}]})}),d("Refreshing access token after account update");const oe=yield w("/oauth/token",{method:"POST",body:S(N)}),ne=yield oe.json();I=ne.access_token,N=ne.refresh_token||N,o.ok(I,"Refresh grant did not return an access token"),o.ok(N,"Refresh grant did not retain a refresh token"),E(I,A,!0),d("Refreshed access token after account update"),d("Fetching and validating updated account data");const ie=yield w(`/user/${F}?_format=json`,{headers:{Authorization:`Bearer ${I}`}}),ae=yield ie.json();o.equal(null===(O=null===(C=ae.field_first_name)||void 0===C?void 0:C[0])||void 0===O?void 0:O.value,L),o.equal(null===(b=null===(R=ae.field_last_name)||void 0===R?void 0:R[0])||void 0===b?void 0:b.value,U),d("Updated and validated account data"),d("Requesting password reset email"),yield w("/user/password?_format=json",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mail:A})}),d("Waiting for password reset email");const re=yield p.waitForLatestEmail(P.id,i,!0);o.ok(re.to.includes(A),"Password reset email was not sent to the test account"),d("Received password reset email"),d("Deleting Drupal account"),yield w(`/user/${F}?_format=json`,{method:"DELETE",headers:{Authorization:`Bearer ${I}`}}),J=!0,d("Checking the refresh token after account deletion");const se=S(N),{response:de,curl:le}=yield k("/oauth/token",{method:"POST",body:se});if(de.ok){const e=j((yield de.json()).access_token);o.equal(e.email,void 0,"Deleted account unexpectedly received a usable token"),d("Confirmed the deleted account token has no user email")}else{const e=yield de.text();y(le),o.match(e,/invalid|revoked|user|email/i),d(`Confirmed refresh was rejected with ${de.status}`)}d("Deleted Drupal account; lifecycle complete")}))));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flumens/models",
3
- "version": "0.32.0",
3
+ "version": "0.32.1",
4
4
  "type": "module",
5
5
  "main": "dist/index.mjs",
6
6
  "module": "dist/index.mjs",
@@ -34,10 +34,8 @@
34
34
  "@rollup/plugin-node-resolve": "16.0.0",
35
35
  "@rollup/plugin-terser": "1.0.0",
36
36
  "@rollup/plugin-typescript": "12.1.2",
37
- "@trivago/prettier-plugin-sort-imports": "5.2.2",
38
37
  "@types/wellknown": "^0.5.8",
39
38
  "mailslurp-client": "^17.4.0",
40
- "prettier": "3.5.0",
41
39
  "rollup-plugin-clear": "2.0.7",
42
40
  "rollup-plugin-copy": "3.5.0",
43
41
  "tslib": "2.8.1",