Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add siwe auth endpoints #177

Merged
merged 4 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions src/endpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,38 +16,42 @@ export function postEndpoint<T extends keyof paths>(
baseUrl: string,
path: T,
params?: paths[T] extends PostEndpoint ? paths[T]['post']['parameters'] : never,
includeCredentials?: boolean,
): Promise<paths[T] extends PostEndpoint ? paths[T]['post']['responses'][200]['schema'] : never> {
const url = makeUrl(baseUrl, path as string, params?.path, params?.query)
return fetchData(url, 'POST', params?.body, params?.headers)
return fetchData(url, 'POST', params?.body, params?.headers, includeCredentials)
}

export function putEndpoint<T extends keyof paths>(
baseUrl: string,
path: T,
params?: paths[T] extends PutEndpoint ? paths[T]['put']['parameters'] : never,
includeCredentials?: boolean,
): Promise<paths[T] extends PutEndpoint ? paths[T]['put']['responses'][200]['schema'] : never> {
const url = makeUrl(baseUrl, path as string, params?.path, params?.query)
return fetchData(url, 'PUT', params?.body, params?.headers)
return fetchData(url, 'PUT', params?.body, params?.headers, includeCredentials)
}

export function deleteEndpoint<T extends keyof paths>(
baseUrl: string,
path: T,
params?: paths[T] extends DeleteEndpoint ? paths[T]['delete']['parameters'] : never,
includeCredentials?: boolean,
): Promise<paths[T] extends DeleteEndpoint ? paths[T]['delete']['responses'][200]['schema'] : never> {
const url = makeUrl(baseUrl, path as string, params?.path, params?.query)
return fetchData(url, 'DELETE', params?.body, params?.headers)
return fetchData(url, 'DELETE', params?.body, params?.headers, includeCredentials)
}

export function getEndpoint<T extends keyof paths>(
baseUrl: string,
path: T,
params?: paths[T] extends GetEndpoint ? paths[T]['get']['parameters'] : never,
rawUrl?: string,
includeCredentials?: boolean,
): Promise<paths[T] extends GetEndpoint ? paths[T]['get']['responses'][200]['schema'] : never> {
if (rawUrl) {
return getData(rawUrl)
return getData(rawUrl, undefined, includeCredentials)
}
const url = makeUrl(baseUrl, path as string, params?.path, params?.query)
return getData(url, params?.headers)
return getData(url, params?.headers, includeCredentials)
}
16 changes: 16 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import type { DelegateResponse, DelegatesRequest } from './types/delegates'
import type { GetEmailResponse } from './types/emails'
import type { RelayCountResponse, RelayTransactionResponse } from './types/relay'
import type { Contract } from './types/contracts'
import type { AuthNonce } from './types/auth'

export * from './types/safe-info'
export * from './types/safe-apps'
Expand Down Expand Up @@ -640,4 +641,19 @@ export function getContract(chainId: string, contractAddress: string): Promise<C
})
}

export function getAuthNonce(): Promise<AuthNonce> {
return getEndpoint(baseUrl, '/v1/auth/nonce', undefined, undefined, true)
}

export function verifyAuth(body: operations['verify_auth']['parameters']['body']) {
return postEndpoint(
baseUrl,
'/v1/auth/verify',
{
body,
},
true,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be good to make the credentials flag part of the endpoint type in api.ts.

)
}

/* eslint-enable @typescript-eslint/explicit-module-boundary-types */
38 changes: 38 additions & 0 deletions src/types/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import type {
import type { RelayCountResponse, RelayTransactionRequest, RelayTransactionResponse } from './relay'
import type { RegisterRecoveryModuleRequestBody } from './recovery'
import type { Contract } from './contracts'
import type { AuthNonce } from './auth'

export type Primitive = string | number | boolean | null

Expand Down Expand Up @@ -452,6 +453,22 @@ export interface paths extends PathRegistry {
}
}
}
'/v1/auth/nonce': {
get: operations['get_auth_nonce']
parameters: {
path: null
}
}
'/v1/auth/verify': {
post: operations['verify_auth']
parameters: {
path: null
body: {
message: string
signature: string
}
}
}
}

export interface operations {
Expand Down Expand Up @@ -1179,4 +1196,25 @@ export interface operations {
}
}
}
get_auth_nonce: {
parameters: null
responses: {
200: {
schema: AuthNonce
}
}
}
verify_auth: {
parameters: {
body: {
message: string
signature: string
}
}
responses: {
200: {
schema: void
}
}
}
}
3 changes: 3 additions & 0 deletions src/types/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export type AuthNonce = {
nonce: string
}
15 changes: 14 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export async function fetchData<T>(
method: 'POST' | 'PUT' | 'DELETE',
body?: unknown,
headers?: Record<string, string>,
includeCredentials?: boolean,
): Promise<T> {
const requestHeaders: Record<string, string> = {
'Content-Type': 'application/json',
Expand All @@ -73,6 +74,10 @@ export async function fetchData<T>(
headers: requestHeaders,
}

if (includeCredentials) {
options['credentials'] = 'include'
}

if (body != null) {
options.body = typeof body === 'string' ? body : JSON.stringify(body)
}
Expand All @@ -82,7 +87,11 @@ export async function fetchData<T>(
return parseResponse<T>(resp)
}

export async function getData<T>(url: string, headers?: Record<string, string>): Promise<T> {
export async function getData<T>(
url: string,
headers?: Record<string, string>,
includeCredentials?: boolean,
): Promise<T> {
const options: RequestInit = {
method: 'GET',
}
Expand All @@ -94,6 +103,10 @@ export async function getData<T>(url: string, headers?: Record<string, string>):
}
}

if (includeCredentials) {
options['credentials'] = 'include'
}

const resp = await fetch(url, options)

return parseResponse<T>(resp)
Expand Down
14 changes: 10 additions & 4 deletions tests/endpoint.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ describe('getEndpoint', () => {
success: true,
})

expect(getData).toHaveBeenCalledWith('https://test.test/v1/balances/supported-fiat-codes', undefined)
expect(getData).toHaveBeenCalledWith('https://test.test/v1/balances/supported-fiat-codes', undefined, undefined)
})

it('should accept a path param', async () => {
Expand All @@ -28,7 +28,7 @@ describe('getEndpoint', () => {
}),
).resolves.toEqual({ success: true })

expect(getData).toHaveBeenCalledWith('https://test.test/v1/chains/4/safes/0x123', undefined)
expect(getData).toHaveBeenCalledWith('https://test.test/v1/chains/4/safes/0x123', undefined, undefined)
})

it('should accept several path params', async () => {
Expand All @@ -39,7 +39,7 @@ describe('getEndpoint', () => {
}),
).resolves.toEqual({ success: true })

expect(getData).toHaveBeenCalledWith('https://test.test/v1/chains/4/safes/0x123/balances/usd', undefined)
expect(getData).toHaveBeenCalledWith('https://test.test/v1/chains/4/safes/0x123/balances/usd', undefined, undefined)
})

it('should accept query params', async () => {
Expand All @@ -53,6 +53,7 @@ describe('getEndpoint', () => {
expect(getData).toHaveBeenCalledWith(
'https://test.test/v1/chains/4/safes/0x123/balances/usd?exclude_spam=true',
undefined,
undefined,
)
})

Expand Down Expand Up @@ -86,6 +87,7 @@ describe('getEndpoint', () => {
'POST',
body,
undefined,
undefined,
)
})

Expand All @@ -99,7 +101,7 @@ describe('getEndpoint', () => {
),
).resolves.toEqual({ success: true })

expect(getData).toHaveBeenCalledWith('/test-url?raw=true')
expect(getData).toHaveBeenCalledWith('/test-url?raw=true', undefined, undefined)
})

it('should call a data decoder POST endpoint', async () => {
Expand All @@ -115,6 +117,7 @@ describe('getEndpoint', () => {
'POST',
{ data: '0x123' },
undefined,
undefined,
)
})

Expand All @@ -131,6 +134,7 @@ describe('getEndpoint', () => {
'POST',
{ data: '0x456' },
undefined,
undefined,
)
})

Expand All @@ -157,6 +161,7 @@ describe('getEndpoint', () => {
'PUT',
body,
headers,
undefined,
)
})

Expand All @@ -177,6 +182,7 @@ describe('getEndpoint', () => {
'DELETE',
body,
undefined,
undefined,
)
})
})
Loading