UNPKG

@passageidentity/passage-flex-node

Version:

Passkey Flex for Node.js - Add passkey authentication to your own Node.js authentication flows with Passage by 1Password

2 lines (1 loc) 19.4 kB
var ce="https://api.passage.id/v1".replace(/\/+$/,""),m=class{constructor(r={}){this.configuration=r}set config(r){this.configuration=r}get basePath(){return this.configuration.basePath!=null?this.configuration.basePath:ce}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||_}get username(){return this.configuration.username}get password(){return this.configuration.password}get apiKey(){let r=this.configuration.apiKey;if(r)return typeof r=="function"?r:()=>r}get accessToken(){let r=this.configuration.accessToken;if(r)return typeof r=="function"?r:async()=>r}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}},de=new m,h=class h{constructor(r=de){this.configuration=r;this.fetchApi=async(r,n)=>{let t={url:r,init:n};for(let i of this.middleware)i.pre&&(t=await i.pre({fetch:this.fetchApi,...t})||t);let o;try{o=await(this.configuration.fetchApi||fetch)(t.url,t.init)}catch(i){for(let s of this.middleware)s.onError&&(o=await s.onError({fetch:this.fetchApi,url:t.url,init:t.init,error:i,response:o?o.clone():void 0})||o);if(o===void 0)throw i instanceof Error?new C(i,"The request failed and the interceptors did not return an alternative response"):i}for(let i of this.middleware)i.post&&(o=await i.post({fetch:this.fetchApi,url:t.url,init:t.init,response:o.clone()})||o);return o};this.middleware=r.middleware}withMiddleware(...r){let n=this.clone();return n.middleware=n.middleware.concat(...r),n}withPreMiddleware(...r){let n=r.map(t=>({pre:t}));return this.withMiddleware(...n)}withPostMiddleware(...r){let n=r.map(t=>({post:t}));return this.withMiddleware(...n)}isJsonMime(r){return r?h.jsonRegex.test(r):!1}async request(r,n){let{url:t,init:o}=await this.createFetchParams(r,n),i=await this.fetchApi(t,o);if(i&&i.status>=200&&i.status<300)return i;throw new p(i,"Response returned an error code")}async createFetchParams(r,n){let t=this.configuration.basePath+r.path;r.query!==void 0&&Object.keys(r.query).length!==0&&(t+="?"+this.configuration.queryParamsStringify(r.query));let o=Object.assign({},this.configuration.headers,r.headers);Object.keys(o).forEach(J=>o[J]===void 0?delete o[J]:{});let i=typeof n=="function"?n:async()=>n,s={method:r.method,headers:o,body:r.body,credentials:this.configuration.credentials},a={...s,...await i({init:s,context:r})},y;pe(a.body)||a.body instanceof URLSearchParams||ue(a.body)?y=a.body:this.isJsonMime(o["Content-Type"])?y=JSON.stringify(a.body):y=a.body;let ae={...a,body:y};return{url:t,init:ae}}clone(){let r=this.constructor,n=new r(this.configuration);return n.middleware=this.middleware.slice(),n}};h.jsonRegex=new RegExp("^(:?application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(:?;.*)?$","i");var u=h;function ue(e){return typeof Blob<"u"&&e instanceof Blob}function pe(e){return typeof FormData<"u"&&e instanceof FormData}var p=class extends Error{constructor(n,t){super(t);this.response=n;this.name="ResponseError"}},C=class extends Error{constructor(n,t){super(t);this.cause=n;this.name="FetchError"}},c=class extends Error{constructor(n,t){super(t);this.field=n;this.name="RequiredError"}};function _(e,r=""){return Object.keys(e).map(n=>D(n,e[n],r)).filter(n=>n.length>0).join("&")}function D(e,r,n=""){let t=n+(n.length?`[${e}]`:e);if(r instanceof Array){let o=r.map(i=>encodeURIComponent(String(i))).join(`&${encodeURIComponent(t)}=`);return`${encodeURIComponent(t)}=${o}`}if(r instanceof Set){let o=Array.from(r);return D(e,o,n)}return r instanceof Date?`${encodeURIComponent(t)}=${encodeURIComponent(r.toISOString())}`:r instanceof Object?_(r,t):`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`}var d=class{constructor(r,n=t=>t){this.raw=r;this.transformer=n}async value(){return this.transformer(await this.raw.json())}},g=class{constructor(r){this.raw=r}async value(){}};function P(e){return fe(e,!1)}function fe(e,r){return e==null?e:{providerId:e.provider_id,createdAt:new Date(e.created_at),lastLoginAt:new Date(e.last_login_at),providerIdentifier:e.provider_identifier}}function M(e){return le(e,!1)}function le(e,r){return e==null?e:{externalId:e.external_id}}function F(e){return me(e,!1)}function me(e,r=!1){return e==null?e:{external_id:e.externalId}}function w(e){return ye(e,!1)}function ye(e,r){return e==null?e:{transactionId:e.transaction_id}}function L(e){return ge(e,!1)}function ge(e,r){return e==null?e:{providerId:e.provider_id,createdAt:new Date(e.created_at),lastLoginAt:new Date(e.last_login_at),providerIdentifier:e.provider_identifier}}function k(e){return he(e,!1)}function he(e,r){return e==null?e:{providerId:e.provider_id,createdAt:new Date(e.created_at),lastLoginAt:new Date(e.last_login_at),providerIdentifier:e.provider_identifier}}function f(e){return Te(e,!1)}function Te(e,r){return e==null?e:{href:e.href}}function q(e){return Se(e,!1)}function Se(e,r){return e==null?e:{light:e.light,dark:e.dark}}var Ae={Passkey:"passkey",SecurityKey:"security_key",Platform:"platform"};function S(e){return xe(e,!1)}function xe(e,r){return e}function A(e){return be(e,!1)}function be(e,r){return e==null?e:{createdAt:new Date(e.created_at),credId:e.cred_id,friendlyName:e.friendly_name,id:e.id,lastLoginAt:new Date(e.last_login_at),type:S(e.type),updatedAt:new Date(e.updated_at),usageCount:e.usage_count,icons:q(e.icons)}}function W(e){return Ne(e,!1)}function Ne(e,r){return e==null?e:{devices:e.devices.map(A)}}var Ue={Active:"active",Inactive:"inactive",Pending:"pending"};function x(e){return Re(e,!1)}function Re(e,r){return e}function V(e){return Ce(e,!1)}function Ce(e,r){return e==null?e:{createdAt:new Date(e.created_at),email:e.email,emailVerified:e.email_verified,externalId:e.external_id,id:e.id,lastLoginAt:new Date(e.last_login_at),loginCount:e.login_count,phone:e.phone,phoneVerified:e.phone_verified,status:x(e.status),updatedAt:new Date(e.updated_at),userMetadata:e.user_metadata}}function v(e){return we(e,!1)}function we(e,r){return e==null?e:{first:f(e.first),last:f(e.last),next:f(e.next),previous:f(e.previous),self:f(e.self)}}function G(e){return Je(e,!1)}function Je(e,r){return e==null?e:{links:v(e._links),createdBefore:e.created_before,limit:e.limit,page:e.page,totalUsers:e.total_users,users:e.users.map(V)}}var H={InvalidRequest:"invalid_request",CustomProviderRequired:"custom_provider_required"};var B={AccessToken:"invalid_access_token",Nonce:"invalid_nonce"};var $={CannotCreateOrganizationBillingPortalSession:"cannot_create_organization_billing_portal_session",CannotCreateTransaction:"cannot_create_transaction",CannotDeleteAdmin:"cannot_delete_admin",CannotDeleteOrganizationMember:"cannot_delete_organization_member",CannotSelfUpdateOrganizationMember:"cannot_self_update_organization_member",OperationNotAllowed:"operation_not_allowed"};var z={AdminNotFound:"admin_not_found",ApiKeyNotFound:"api_key_not_found",AppNotFound:"app_not_found",DeviceNotFound:"device_not_found",DomainNotFound:"domain_not_found",EmailProviderNotFound:"email_provider_not_found",EmailTemplateNotFound:"email_template_not_found",EventNotFound:"event_not_found",FunctionNotFound:"function_not_found",FunctionSecretKeyNotFound:"function_secret_key_not_found",FunctionVersionNotFound:"function_version_not_found",MetadataFieldNotFound:"metadata_field_not_found",Oauth2AppNotFound:"oauth2_app_not_found",OrganizationMemberNotFound:"organization_member_not_found",SmsProviderNotFound:"sms_provider_not_found",SmsTemplateNotFound:"sms_template_not_found",SocialConnectionNotFound:"social_connection_not_found",UserNotFound:"user_not_found",NativeClientNotFound:"native_client_not_found"};var K={UserAlreadyAdmin:"user_already_admin",UserAlreadyOrganizationMember:"user_already_organization_member",UserHasNoPasskeys:"user_has_no_passkeys",NativeClientAlreadyExists:"native_client_already_exists",FailedToSyncEmailPreferences:"failed_to_sync_email_preferences"};var Q={InternalServerError:"internal_server_error"};function Y(e){return _e(e,!1)}function _e(e,r=!1){return e==null?e:{external_id:e.externalId,passkey_display_name:e.passkeyDisplayName}}function X(e){return De(e,!1)}function De(e,r){return e}function Z(e){return Pe(e,!1)}function Pe(e,r){return e}function j(e){return Me(e,!1)}function Me(e,r){return e}function ee(e){return Fe(e,!1)}function Fe(e,r){return e==null?e:{createdAt:new Date(e.created_at),completedAt:e.completed_at==null?null:new Date(e.completed_at),id:e.id,ipAddr:e.ip_addr,status:j(e.status),type:e.type,userAgent:e.user_agent,userAgentDisplay:e.user_agent_display,action:Z(e.action),socialLoginType:X(e.social_login_type)}}function re(e){return Le(e,!1)}function Le(e,r){return e==null?e:{apple:e.apple==null?void 0:P(e.apple),github:e.github==null?void 0:L(e.github),google:e.google==null?void 0:k(e.google)}}function ne(e){return ke(e,!1)}function ke(e,r){return e==null?e:{createdAt:new Date(e.created_at),email:e.email,emailVerified:e.email_verified,externalId:e.external_id,id:e.id,lastLoginAt:new Date(e.last_login_at),loginCount:e.login_count,phone:e.phone,phoneVerified:e.phone_verified,recentEvents:e.recent_events.map(ee),socialConnections:re(e.social_connections),status:x(e.status),updatedAt:new Date(e.updated_at),userMetadata:e.user_metadata,webauthn:e.webauthn,webauthnDevices:e.webauthn_devices.map(A),webauthnTypes:e.webauthn_types.map(S)}}function te(e){return qe(e,!1)}function qe(e,r){return e==null?e:{user:ne(e.user)}}var O=class extends u{async authenticateVerifyNonceRaw(r,n){if(r.appId==null)throw new c("appId",'Required parameter "appId" was null or undefined when calling authenticateVerifyNonce().');if(r.body==null)throw new c("body",'Required parameter "body" was null or undefined when calling authenticateVerifyNonce().');let t={},o={};if(o["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){let s=this.configuration.accessToken,a=await s("bearerAuth",[]);a&&(o.Authorization=`Bearer ${a}`)}let i=await this.request({path:"/apps/{app_id}/authenticate/verify".replace("{app_id}",encodeURIComponent(String(r.appId))),method:"POST",headers:o,query:t,body:r.body},n);return new d(i,s=>M(s))}async authenticateVerifyNonce(r,n){return await(await this.authenticateVerifyNonceRaw(r,n)).value()}};var b=class extends u{async createAuthenticateTransactionRaw(r,n){if(r.appId==null)throw new c("appId",'Required parameter "appId" was null or undefined when calling createAuthenticateTransaction().');if(r.createTransactionAuthenticateRequest==null)throw new c("createTransactionAuthenticateRequest",'Required parameter "createTransactionAuthenticateRequest" was null or undefined when calling createAuthenticateTransaction().');let t={},o={};if(o["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){let s=this.configuration.accessToken,a=await s("bearerAuth",[]);a&&(o.Authorization=`Bearer ${a}`)}let i=await this.request({path:"/apps/{app_id}/transactions/authenticate".replace("{app_id}",encodeURIComponent(String(r.appId))),method:"POST",headers:o,query:t,body:F(r.createTransactionAuthenticateRequest)},n);return new d(i,s=>w(s))}async createAuthenticateTransaction(r,n){return await(await this.createAuthenticateTransactionRaw(r,n)).value()}async createRegisterTransactionRaw(r,n){if(r.appId==null)throw new c("appId",'Required parameter "appId" was null or undefined when calling createRegisterTransaction().');if(r.registerTransactionArgs==null)throw new c("registerTransactionArgs",'Required parameter "registerTransactionArgs" was null or undefined when calling createRegisterTransaction().');let t={},o={};if(o["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){let s=this.configuration.accessToken,a=await s("bearerAuth",[]);a&&(o.Authorization=`Bearer ${a}`)}let i=await this.request({path:"/apps/{app_id}/transactions/register".replace("{app_id}",encodeURIComponent(String(r.appId))),method:"POST",headers:o,query:t,body:Y(r.registerTransactionArgs)},n);return new d(i,s=>w(s))}async createRegisterTransaction(r,n){return await(await this.createRegisterTransactionRaw(r,n)).value()}};var E=class extends u{async deleteUserDevicesRaw(r,n){if(r.appId==null)throw new c("appId",'Required parameter "appId" was null or undefined when calling deleteUserDevices().');if(r.userId==null)throw new c("userId",'Required parameter "userId" was null or undefined when calling deleteUserDevices().');if(r.deviceId==null)throw new c("deviceId",'Required parameter "deviceId" was null or undefined when calling deleteUserDevices().');let t={},o={};if(this.configuration&&this.configuration.accessToken){let s=this.configuration.accessToken,a=await s("bearerAuth",[]);a&&(o.Authorization=`Bearer ${a}`)}let i=await this.request({path:"/apps/{app_id}/users/{user_id}/devices/{device_id}".replace("{app_id}",encodeURIComponent(String(r.appId))).replace("{user_id}",encodeURIComponent(String(r.userId))).replace("{device_id}",encodeURIComponent(String(r.deviceId))),method:"DELETE",headers:o,query:t},n);return new g(i)}async deleteUserDevices(r,n){await this.deleteUserDevicesRaw(r,n)}async listUserDevicesRaw(r,n){if(r.appId==null)throw new c("appId",'Required parameter "appId" was null or undefined when calling listUserDevices().');if(r.userId==null)throw new c("userId",'Required parameter "userId" was null or undefined when calling listUserDevices().');let t={},o={};if(this.configuration&&this.configuration.accessToken){let s=this.configuration.accessToken,a=await s("bearerAuth",[]);a&&(o.Authorization=`Bearer ${a}`)}let i=await this.request({path:"/apps/{app_id}/users/{user_id}/devices".replace("{app_id}",encodeURIComponent(String(r.appId))).replace("{user_id}",encodeURIComponent(String(r.userId))),method:"GET",headers:o,query:t},n);return new d(i,s=>W(s))}async listUserDevices(r,n){return await(await this.listUserDevicesRaw(r,n)).value()}};var N=class extends u{async getUserRaw(r,n){if(r.appId==null)throw new c("appId",'Required parameter "appId" was null or undefined when calling getUser().');if(r.userId==null)throw new c("userId",'Required parameter "userId" was null or undefined when calling getUser().');let t={},o={};if(this.configuration&&this.configuration.accessToken){let s=this.configuration.accessToken,a=await s("bearerAuth",[]);a&&(o.Authorization=`Bearer ${a}`)}let i=await this.request({path:"/apps/{app_id}/users/{user_id}".replace("{app_id}",encodeURIComponent(String(r.appId))).replace("{user_id}",encodeURIComponent(String(r.userId))),method:"GET",headers:o,query:t},n);return new d(i,s=>te(s))}async getUser(r,n){return await(await this.getUserRaw(r,n)).value()}async listPaginatedUsersRaw(r,n){if(r.appId==null)throw new c("appId",'Required parameter "appId" was null or undefined when calling listPaginatedUsers().');let t={};r.page!=null&&(t.page=r.page),r.limit!=null&&(t.limit=r.limit),r.createdBefore!=null&&(t.created_before=r.createdBefore),r.orderBy!=null&&(t.order_by=r.orderBy),r.identifier!=null&&(t.identifier=r.identifier),r.id!=null&&(t.id=r.id),r.loginCount!=null&&(t.login_count=r.loginCount),r.status!=null&&(t.status=r.status),r.createdAt!=null&&(t.created_at=r.createdAt),r.updatedAt!=null&&(t.updated_at=r.updatedAt),r.lastLoginAt!=null&&(t.last_login_at=r.lastLoginAt);let o={};if(this.configuration&&this.configuration.accessToken){let s=this.configuration.accessToken,a=await s("bearerAuth",[]);a&&(o.Authorization=`Bearer ${a}`)}let i=await this.request({path:"/apps/{app_id}/users".replace("{app_id}",encodeURIComponent(String(r.appId))),method:"GET",headers:o,query:t},n);return new d(i,s=>G(s))}async listPaginatedUsers(r,n){return await(await this.listPaginatedUsersRaw(r,n)).value()}};import We from"node-fetch";function oe(e){return new m({accessToken:e.accessToken,fetchApi:We,headers:{...e.headers,"Passage-Version":`passage-flex-node ${process.env.npm_package_version??"v0.0.0"}`},middleware:[]})}var ie={...H,...B,...$,...z,...K,...Q};var U=class e extends Error{constructor(n,t,o){super(o);this.statusCode=n;this.errorCode=t;this.message=o;this.name="PassageError"}static async fromResponseError(n){let t;try{t=await n.response.json()}catch{t={code:ie.InternalServerError,error:"Unknown error occured."}}return new e(n.response.status,t.code,t.error)}};var l=class{constructor(r){this.config=r}async parseError(r){return r instanceof p?await U.fromResponseError(r):r}};var R=class extends l{constructor(r){super(r),this.transactionClient=new b(r.apiConfiguration),this.authClient=new O(r.apiConfiguration)}async createRegisterTransaction(r,n){if(!r)throw new Error("externalId is required.");if(!n)throw new Error("passkeyDisplayName is required.");try{return(await this.transactionClient.createRegisterTransaction({appId:this.config.appId,registerTransactionArgs:{externalId:r,passkeyDisplayName:n}})).transactionId}catch(t){throw await this.parseError(t)}}async createAuthenticateTransaction(r){if(!r)throw new Error("externalId is required.");try{return(await this.transactionClient.createAuthenticateTransaction({appId:this.config.appId,createTransactionAuthenticateRequest:{externalId:r}})).transactionId}catch(n){throw await this.parseError(n)}}async verifyNonce(r){if(!r)throw new Error("nonce is required.");try{return(await this.authClient.authenticateVerifyNonce({appId:this.config.appId,body:{nonce:r}})).externalId}catch(n){throw await this.parseError(n)}}};var I=class extends l{constructor(r){super(r),this.userClient=new N(r.apiConfiguration),this.deviceClient=new E(r.apiConfiguration)}async get(r){if(!r)throw new Error("externalId is required.");try{let t=(await this.userClient.listPaginatedUsers({appId:this.config.appId,limit:1,identifier:r})).users;if(!t.length)throw new p(new Response('{"code":"user_not_found","error":"User not found."}',{status:404}));return await this.getUserById(t[0].id)}catch(n){throw await this.parseError(n)}}async listDevices(r){if(!r)throw new Error("externalId is required.");try{let n=await this.get(r);return(await this.deviceClient.listUserDevices({appId:this.config.appId,userId:n.id})).devices}catch(n){throw await this.parseError(n)}}async revokeDevice(r,n){if(!r)throw new Error("externalId is required.");if(!n)throw new Error("deviceId is required.");try{let t=await this.get(r);await this.deviceClient.deleteUserDevices({appId:this.config.appId,userId:t.id,deviceId:n})}catch(t){throw await this.parseError(t)}}async getUserById(r){if(!r)throw new Error("userId is required.");let n=await this.userClient.getUser({appId:this.config.appId,userId:r});return this.mapUserInfoToPassageUser(n.user)}mapUserInfoToPassageUser(r){return{createdAt:r.createdAt,externalId:r.externalId,id:r.id,lastLoginAt:r.lastLoginAt,loginCount:r.loginCount,status:r.status,updatedAt:r.updatedAt,userMetadata:r.userMetadata,webauthn:r.webauthn,webauthnDevices:r.webauthnDevices,webauthnTypes:r.webauthnTypes}}};var se=class{constructor(r){if(!r.appId)throw Error("A Passage App ID is required. Please include {appId: YOUR_APP_ID, apiKey: YOUR_APP_ID}.");if(!r.apiKey)throw Error("A Passage API key is required. Please include {appId: YOUR_APP_ID, apiKey: YOUR_APP_ID}.");let{appId:n,apiKey:t}=r,o={appId:n,apiConfiguration:oe({accessToken:t})};this.auth=new R(o),this.user=new I(o)}};export{R as Auth,U as PassageError,ie as PassageErrorCode,se as PassageFlex,I as User,Ue as UserStatus,Ae as WebAuthnType};