Skip to content

Commit

Permalink
chore(platform): use Environment object as an individual entity
Browse files Browse the repository at this point in the history
  • Loading branch information
szkl committed Oct 23, 2023
1 parent cd7a99c commit 2e3c1b9
Show file tree
Hide file tree
Showing 86 changed files with 262 additions and 197 deletions.
2 changes: 1 addition & 1 deletion platform/account/src/jsonrpc/methods/generateEmailOTP.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const generateEmailOTPMethod = async ({
ctx: Context
}): Promise<string> => {
const { email, themeProps, preview } = input
const emailAccountNode = new EmailAccount(ctx.account as AccountNode, ctx)
const emailAccountNode = new EmailAccount(ctx.account as AccountNode, ctx.env)

const state = generateRandomString(EMAIL_VERIFICATION_OPTIONS.STATE_LENGTH)

Expand Down
6 changes: 5 additions & 1 deletion platform/account/src/jsonrpc/methods/getAccountAvatar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ export const getAccountAvatarMethod: GetAccountAvatarMethod = async ({
}

if (type == OAuthAccountType.Microsoft) {
const oAuthNode = new MicrosoftAccount(nodeClient, ctx)
const oAuthNode = new MicrosoftAccount(
nodeClient,
ctx.hashedIdref!,
ctx.env
)
return oAuthNode.getAvatar()
}

Expand Down
14 changes: 7 additions & 7 deletions platform/account/src/jsonrpc/methods/getAccountProfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export const getAccountProfileBatchMethod = async ({
const resultPromises = []
for (const accountURN of input) {
const baseURN = AccountURNSpace.getBaseURN(accountURN)
const nodeClient = initAccountNodeByName(baseURN, ctx.Account)
const nodeClient = initAccountNodeByName(baseURN, ctx.env.Account)
resultPromises.push(getProfile(ctx, nodeClient, accountURN))
}
return await Promise.all(resultPromises)
Expand Down Expand Up @@ -103,19 +103,19 @@ async function getProfile(
case CryptoAccountType.Wallet:
return new ContractAccount(nodeClient)
case EmailAccountType.Email:
return new EmailAccount(nodeClient, ctx)
return new EmailAccount(nodeClient, ctx.env)
case WebauthnAccountType.WebAuthN:
return new WebauthnAccount(nodeClient, ctx)
return new WebauthnAccount(nodeClient)
case OAuthAccountType.Apple:
return new AppleAccount(nodeClient, ctx)
return new AppleAccount(nodeClient, ctx.env)
case OAuthAccountType.Discord:
return new DiscordAccount(nodeClient, ctx)
return new DiscordAccount(nodeClient, ctx.env)
case OAuthAccountType.GitHub:
return new GithubAccount(nodeClient)
case OAuthAccountType.Google:
return new GoogleAccount(nodeClient, ctx)
return new GoogleAccount(nodeClient, ctx.env)
case OAuthAccountType.Microsoft:
return new MicrosoftAccount(nodeClient, ctx)
return new MicrosoftAccount(nodeClient, ctx.hashedIdref!, ctx.env)
case OAuthAccountType.Twitter:
return new TwitterAccount(nodeClient)
}
Expand Down
2 changes: 1 addition & 1 deletion platform/account/src/jsonrpc/methods/getWebAuthNData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const getWebAuthNDataMethod = async ({
input: unknown
ctx: Context
}): Promise<z.infer<typeof GetWebAuthNDataOutput>> => {
const nodeClient = new WebauthnAccount(ctx.account as AccountNode, ctx)
const nodeClient = new WebauthnAccount(ctx.account as AccountNode)
const data = await nodeClient.getData()
return data
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export const connectIdentityGroupEmail = async ({
ctx.waitUntil?.(
createAnalyticsEvent({
eventName: 'group_email_connected',
apiKey: ctx.POSTHOG_API_KEY,
apiKey: ctx.env.POSTHOG_API_KEY,
distinctId: identityGroupURN,
properties: {
$groups: { group: identityGroupURN },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export const initSmartContractWalletMethod = async ({

const smartContractWallet = await getZeroDevSigner({
skipFetchSetup: true,
projectId: ctx.SECRET_ZERODEV_PROJECTID,
projectId: ctx.env.SECRET_ZERODEV_PROJECTID,
owner,
})

Expand All @@ -60,10 +60,10 @@ export const initSmartContractWalletMethod = async ({

const smartContractWalletNode = initAccountNodeByName(
baseAccountURN,
ctx.Account
ctx.env.Account
)

const imageClient = createImageClient(ctx.Images, {
const imageClient = createImageClient(ctx.env.Images, {
headers: generateTraceContextHeaders(ctx.traceSpan),
})
const gradient = await imageClient.getGradient.mutate({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const registerSessionKeyMethod = async ({

const smartContractWalletNode = initAccountNodeByName(
baseAccountURN,
ctx.Account
ctx.env.Account
)

const ownerPrivateKey = (await smartContractWalletNode.storage.get(
Expand Down
2 changes: 1 addition & 1 deletion platform/account/src/jsonrpc/methods/resolveIdentity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export const resolveIdentityMethod = async ({

ctx.waitUntil?.(
createAnalyticsEvent({
apiKey: ctx.POSTHOG_API_KEY,
apiKey: ctx.env.POSTHOG_API_KEY,
eventName,
distinctId: resultURN,
properties: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export const revokeWalletSessionKeyMethod = async ({
}): Promise<void> => {
const smartContractWalletNode = initAccountNodeByName(
ctx.accountURN as AccountURN,
ctx.Account
ctx.env.Account
)

await revokeWalletSessionKey({
Expand All @@ -66,7 +66,10 @@ export const revokeWalletSessionKeyBatchMethod = async ({
const resultPromises = []
for (const smartWalletSessionKey of input.smartWalletSessionKeys) {
const baseURN = AccountURNSpace.getBaseURN(smartWalletSessionKey.urn)
const smartContractWalletNode = initAccountNodeByName(baseURN, ctx.Account)
const smartContractWalletNode = initAccountNodeByName(
baseURN,
ctx.env.Account
)
resultPromises.push(
revokeWalletSessionKey({
smartContractWalletNode,
Expand Down
2 changes: 1 addition & 1 deletion platform/account/src/jsonrpc/methods/setWebAuthNData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ export const setWebAuthNDataMethod = async ({
input: z.infer<typeof SetWebAuthNInput>
ctx: Context
}): Promise<void> => {
const nodeClient = new WebauthnAccount(ctx.account as AccountNode, ctx)
const nodeClient = new WebauthnAccount(ctx.account as AccountNode)
await nodeClient.setData(input)
}
2 changes: 1 addition & 1 deletion platform/account/src/jsonrpc/methods/verifyEmailOTP.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const verifyEmailOTPMethod = async ({
ctx: Context
}): Promise<z.infer<typeof VerifyEmailOTPOutput>> => {
const { code, state } = input
const emailAccountNode = new EmailAccount(ctx.account as AccountNode, ctx)
const emailAccountNode = new EmailAccount(ctx.account as AccountNode, ctx.env)
const successfulVerification = await emailAccountNode.verifyCode(code, state)

return successfulVerification
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const initAccountNode: BaseMiddlewareFunction<Context> = async ({
if (!ctx.alias) {
throw new Error('missing alias')
}
const imageClient = createImageClient(ctx.Images, {
const imageClient = createImageClient(ctx.env.Images, {
headers: generateTraceContextHeaders(ctx.traceSpan),
})
const gradient = await imageClient.getGradient.mutate({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const setAccountNodeClient: BaseMiddlewareFunction<Context> = async ({

const node = initAccountNodeByName(
AccountURNSpace.getBaseURN(ctx.accountURN),
ctx.Account
ctx.env.Account
)

return next({
Expand Down
2 changes: 0 additions & 2 deletions platform/account/src/nodes/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ import { DOProxy, DurableObjectStubProxy } from 'do-proxy'

import { IdentityURN } from '@proofzero/urns/identity'
import { AccountType, NodeType } from '@proofzero/types/account'

import type { Environment } from '@proofzero/platform.core'

import ContractAccount from './contract'
import CryptoAccount from './crypto'
import OAuthAccount from './oauth'
import EmailAccount from './email'
Expand Down
9 changes: 4 additions & 5 deletions platform/account/src/nodes/apple.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { DurableObjectStubProxy } from 'do-proxy'

import { InternalServerError } from '@proofzero/errors'

import { OAuthAccountType } from '@proofzero/types/account'
import type { Environment } from '@proofzero/platform.core'

import { Context } from '../context'
import { AccountProfile, AppleOAuthProfile } from '../types'

import Account from './account'
Expand All @@ -19,10 +18,10 @@ export default class AppleAccount extends OAuthAccount {
declare clientId: string
declare clientSecret: string

constructor(node: AccountNode, ctx: Context) {
constructor(node: AccountNode, env: Environment) {
super(node)
this.clientId = ctx.INTERNAL_APPLE_OAUTH_CLIENT_ID
this.clientSecret = ctx.SECRET_APPLE_OAUTH_CLIENT_SECRET
this.clientId = env.INTERNAL_APPLE_OAUTH_CLIENT_ID
this.clientSecret = env.SECRET_APPLE_OAUTH_CLIENT_SECRET
}

async getProfile(): Promise<AppleAccountProfile> {
Expand Down
1 change: 0 additions & 1 deletion platform/account/src/nodes/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { DurableObjectStubProxy } from 'do-proxy'

import { InternalServerError } from '@proofzero/errors'
import { CryptoAccountType } from '@proofzero/types/account'
import ENSUtils from '@proofzero/platform-clients/ens-utils'

import { AccountNode } from '.'
import { AccountProfile } from '../types'
Expand Down
8 changes: 4 additions & 4 deletions platform/account/src/nodes/discord.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { DurableObjectStubProxy } from 'do-proxy'

import { InternalServerError } from '@proofzero/errors'
import { OAuthAccountType } from '@proofzero/types/account'
import type { Environment } from '@proofzero/platform.core'

import type { Context } from '../context'
import type { AccountProfile, DiscordOAuthProfile } from '../types'

import Account from './account'
Expand All @@ -16,10 +16,10 @@ const TOKEN_URL = 'https://discord.com/api/v10/oauth2/token'
const USERINFO_URL = 'https://discord.com/api/v10/users/@me'

export default class DiscordAccount extends OAuthAccount {
constructor(node: AccountNode, ctx: Context) {
constructor(node: AccountNode, env: Environment) {
super(node)
this.clientId = ctx.INTERNAL_DISCORD_OAUTH_CLIENT_ID
this.clientSecret = ctx.SECRET_DISCORD_OAUTH_CLIENT_SECRET
this.clientId = env.INTERNAL_DISCORD_OAUTH_CLIENT_ID
this.clientSecret = env.SECRET_DISCORD_OAUTH_CLIENT_SECRET
}

async getRequestHeaders() {
Expand Down
34 changes: 17 additions & 17 deletions platform/account/src/nodes/email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import { DurableObjectStubProxy } from 'do-proxy'
import { BadRequestError, InternalServerError } from '@proofzero/errors'
import { EmailAccountType, NodeType } from '@proofzero/types/account'
import generateRandomString from '@proofzero/utils/generateRandomString'
import type { Environment } from '@proofzero/platform.core'

import { AccountProfile } from '../types'

import { EMAIL_VERIFICATION_OPTIONS } from '../constants'

import { AccountNode } from '.'
import Account from './account'
import { Context } from '../context'

type EmailAccountProfile = AccountProfile<EmailAccountType.Email>

Expand All @@ -28,11 +28,11 @@ const OTP_KEY_NAME = 'otp'

export default class EmailAccount {
declare node: AccountNode
declare ctx: Context
declare env: Environment

constructor(node: AccountNode, ctx: Context) {
constructor(node: AccountNode, env: Environment) {
this.node = node
this.ctx = ctx
this.env = env
}

private createCode = async ({
Expand All @@ -44,7 +44,7 @@ export default class EmailAccount {
delayMiliseconds,
}: VerificationPayload) => {
if (
firstAttemptTimestamp + this.ctx.MAX_ATTEMPTS_TIME_PERIOD_IN_MS <=
firstAttemptTimestamp + this.env.MAX_ATTEMPTS_TIME_PERIOD_IN_MS <=
Date.now()
) {
numberOfAttempts = 1
Expand All @@ -68,7 +68,7 @@ export default class EmailAccount {
delayMiliseconds?: number
): Promise<string> {
if (!delayMiliseconds) {
delayMiliseconds = this.ctx.DELAY_BETWEEN_REGENERATION_ATTEMPTS_IN_MS
delayMiliseconds = this.env.DELAY_BETWEEN_REGENERATION_ATTEMPTS_IN_MS
}

const verificationPayload =
Expand All @@ -92,28 +92,28 @@ export default class EmailAccount {
} = verificationPayload

// Extracted common calculations and constants for better readability
const isAboveMaxAttempts = numberOfAttempts + 1 > this.ctx.MAX_ATTEMPTS
const isAboveMaxAttempts = numberOfAttempts + 1 > this.env.MAX_ATTEMPTS
const isCooldownPeriodActive =
creationTimestamp + this.ctx.REGENERATION_COOLDOWN_PERIOD_IN_MS >
creationTimestamp + this.env.REGENERATION_COOLDOWN_PERIOD_IN_MS >
currentTime
const isRegenDelayActive =
creationTimestamp + delayMiliseconds > currentTime
const isMaxAttemptsReachedWithinTimePeriod =
firstAttemptTimestamp + this.ctx.MAX_ATTEMPTS_TIME_PERIOD_IN_MS >
firstAttemptTimestamp + this.env.MAX_ATTEMPTS_TIME_PERIOD_IN_MS >
currentTime

// After limit for 5 attempts is hit, we set a cool down 10 minutes from the last attempt
if (isAboveMaxAttempts && isCooldownPeriodActive) {
const timeLeft =
verificationPayload.creationTimestamp +
this.ctx.REGENERATION_COOLDOWN_PERIOD_IN_MS -
this.env.REGENERATION_COOLDOWN_PERIOD_IN_MS -
currentTime

throw new BadRequestError({
message: `Cannot generate new code for the address. You can only generate ${
this.ctx.MAX_ATTEMPTS
this.env.MAX_ATTEMPTS
} new codes within ${
this.ctx.MAX_ATTEMPTS_TIME_PERIOD_IN_MS / 1000 / 60
this.env.MAX_ATTEMPTS_TIME_PERIOD_IN_MS / 1000 / 60
}
minutes. Try again in ${Math.ceil(timeLeft / 1000 / 60)} minutes`,
})
Expand All @@ -132,15 +132,15 @@ export default class EmailAccount {
// once the limit of 5 attempts is hit, we set a cool down 10 minutes from the last attempt
// and we set new alarm
if (
numberOfAttempts + 1 === this.ctx.MAX_ATTEMPTS &&
numberOfAttempts + 1 === this.env.MAX_ATTEMPTS &&
isMaxAttemptsReachedWithinTimePeriod
) {
await this.node.storage.setAlarm(
currentTime + this.ctx.REGENERATION_COOLDOWN_PERIOD_IN_MS
currentTime + this.env.REGENERATION_COOLDOWN_PERIOD_IN_MS
)
} else {
// If limit wasn't hit, we set this alarm
await this.node.storage.setAlarm(currentTime + this.ctx.TTL_IN_MS)
await this.node.storage.setAlarm(currentTime + this.env.TTL_IN_MS)
}

// we increment the number of attempts independently of any conditions
Expand All @@ -155,7 +155,7 @@ export default class EmailAccount {

return code
}
await this.node.storage.setAlarm(currentTime + this.ctx.TTL_IN_MS)
await this.node.storage.setAlarm(currentTime + this.env.TTL_IN_MS)

await this.createCode({
state,
Expand Down Expand Up @@ -188,7 +188,7 @@ export default class EmailAccount {
}

if (
emailVerification.creationTimestamp + this.ctx.TTL_IN_MS <=
emailVerification.creationTimestamp + this.env.TTL_IN_MS <=
Date.now()
) {
//We anticipate we'll encounter this only if an address has multiple OTP codes in the
Expand Down
8 changes: 4 additions & 4 deletions platform/account/src/nodes/google.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { DurableObjectStubProxy } from 'do-proxy'

import { OAuthAccountType } from '@proofzero/types/account'
import type { Environment } from '@proofzero/platform.core'

import type { Context } from '../context'
import { AccountProfile, GoogleOAuthProfile } from '../types'

import Account from './account'
Expand All @@ -18,10 +18,10 @@ export default class GoogleAccount extends OAuthAccount {
declare clientId: string
declare clientSecret: string

constructor(node: AccountNode, ctx: Context) {
constructor(node: AccountNode, env: Environment) {
super(node)
this.clientId = ctx.INTERNAL_GOOGLE_OAUTH_CLIENT_ID
this.clientSecret = ctx.SECRET_GOOGLE_OAUTH_CLIENT_SECRET
this.clientId = env.INTERNAL_GOOGLE_OAUTH_CLIENT_ID
this.clientSecret = env.SECRET_GOOGLE_OAUTH_CLIENT_SECRET
}

getTokenURL(): string {
Expand Down
Loading

0 comments on commit 2e3c1b9

Please sign in to comment.