@devtion/backend 0.0.0-bfc9ee4 → 0.0.0-c1f4cbe

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 (37) hide show
  1. package/README.md +28 -2
  2. package/dist/src/functions/index.js +403 -108
  3. package/dist/src/functions/index.mjs +405 -112
  4. package/dist/types/functions/bandada.d.ts +4 -0
  5. package/dist/types/functions/bandada.d.ts.map +1 -0
  6. package/dist/types/functions/ceremony.d.ts.map +1 -1
  7. package/dist/types/functions/circuit.d.ts.map +1 -1
  8. package/dist/types/functions/index.d.ts +2 -0
  9. package/dist/types/functions/index.d.ts.map +1 -1
  10. package/dist/types/functions/siwe.d.ts +4 -0
  11. package/dist/types/functions/siwe.d.ts.map +1 -0
  12. package/dist/types/functions/storage.d.ts.map +1 -1
  13. package/dist/types/functions/timeout.d.ts.map +1 -1
  14. package/dist/types/functions/user.d.ts.map +1 -1
  15. package/dist/types/lib/errors.d.ts +2 -1
  16. package/dist/types/lib/errors.d.ts.map +1 -1
  17. package/dist/types/lib/services.d.ts +7 -0
  18. package/dist/types/lib/services.d.ts.map +1 -1
  19. package/dist/types/lib/utils.d.ts +1 -1
  20. package/dist/types/lib/utils.d.ts.map +1 -1
  21. package/dist/types/types/index.d.ts +57 -1
  22. package/dist/types/types/index.d.ts.map +1 -1
  23. package/package.json +5 -4
  24. package/src/functions/bandada.ts +155 -0
  25. package/src/functions/ceremony.ts +9 -4
  26. package/src/functions/circuit.ts +138 -116
  27. package/src/functions/index.ts +2 -0
  28. package/src/functions/participant.ts +9 -9
  29. package/src/functions/siwe.ts +77 -0
  30. package/src/functions/storage.ts +7 -4
  31. package/src/functions/timeout.ts +4 -3
  32. package/src/functions/user.ts +35 -10
  33. package/src/lib/errors.ts +6 -1
  34. package/src/lib/services.ts +36 -0
  35. package/src/lib/utils.ts +11 -9
  36. package/src/types/declarations.d.ts +1 -0
  37. package/src/types/index.ts +61 -1
@@ -2,7 +2,7 @@ import * as functions from "firebase-functions"
2
2
  import { UserRecord } from "firebase-functions/v1/auth"
3
3
  import admin from "firebase-admin"
4
4
  import dotenv from "dotenv"
5
- import { commonTerms, githubReputation } from "@p0tion/actions"
5
+ import { commonTerms, githubReputation } from "@devtion/actions"
6
6
  import { encode } from "html-entities"
7
7
  import { getGitHubVariables, getCurrentServerTimestampInMillis } from "../lib/utils"
8
8
  import { logAndThrowError, makeError, printLog, SPECIFIC_ERRORS } from "../lib/errors"
@@ -40,8 +40,12 @@ export const registerAuthUser = functions
40
40
  const { uid } = user
41
41
  // Reference to a document using uid.
42
42
  const userRef = firestore.collection(commonTerms.collections.users.name).doc(uid)
43
- // html encode the display name
44
- const encodedDisplayName = encode(displayName)
43
+ // html encode the display name (or put the ID if the name is not displayed)
44
+ const encodedDisplayName =
45
+ user.displayName === "Null" || user.displayName === null ? user.uid : encode(displayName)
46
+
47
+ // store the avatar URL of a contributor
48
+ let avatarUrl: string = ""
45
49
  // we only do reputation check if the user is not a coordinator
46
50
  if (
47
51
  !(
@@ -51,18 +55,19 @@ export const registerAuthUser = functions
51
55
  ) {
52
56
  const auth = admin.auth()
53
57
  // if provider == github.com let's use our functions to check the user's reputation
54
- if (user.providerData[0].providerId === "github.com") {
58
+ if (user.providerData.length > 0 && user.providerData[0].providerId === "github.com") {
55
59
  const vars = getGitHubVariables()
56
60
 
57
61
  // this return true or false
58
62
  try {
59
- const res = await githubReputation(
63
+ const { reputable, avatarUrl: avatarURL } = await githubReputation(
60
64
  user.providerData[0].uid,
61
65
  vars.minimumFollowing,
62
66
  vars.minimumFollowers,
63
- vars.minimumPublicRepos
67
+ vars.minimumPublicRepos,
68
+ vars.minimumAge
64
69
  )
65
- if (!res) {
70
+ if (!reputable) {
66
71
  // Delete user
67
72
  await auth.deleteUser(user.uid)
68
73
  // Throw error
@@ -70,11 +75,22 @@ export const registerAuthUser = functions
70
75
  makeError(
71
76
  "permission-denied",
72
77
  "The user is not allowed to sign up because their Github reputation is not high enough.",
73
- `The user ${user.displayName} is not allowed to sign up because their Github reputation is not high enough. Please contact the administrator if you think this is a mistake.`
78
+ `The user ${
79
+ user.displayName === "Null" || user.displayName === null
80
+ ? user.uid
81
+ : user.displayName
82
+ } is not allowed to sign up because their Github reputation is not high enough. Please contact the administrator if you think this is a mistake.`
74
83
  )
75
84
  )
76
85
  }
77
- printLog(`Github reputation check passed for user ${user.displayName}`, LogLevel.DEBUG)
86
+ // store locally
87
+ avatarUrl = avatarURL
88
+ printLog(
89
+ `Github reputation check passed for user ${
90
+ user.displayName === "Null" || user.displayName === null ? user.uid : user.displayName
91
+ }`,
92
+ LogLevel.DEBUG
93
+ )
78
94
  } catch (error: any) {
79
95
  // Delete user
80
96
  await auth.deleteUser(user.uid)
@@ -89,19 +105,28 @@ export const registerAuthUser = functions
89
105
  }
90
106
  }
91
107
  // Set document (nb. we refer to providerData[0] because we use Github OAuth provider only).
108
+ // In future releases we might want to loop through the providerData array as we support
109
+ // more providers.
92
110
  await userRef.set({
93
111
  name: encodedDisplayName,
94
112
  encodedDisplayName,
95
113
  // Metadata.
96
114
  creationTime,
97
- lastSignInTime,
115
+ lastSignInTime: lastSignInTime || creationTime,
98
116
  // Optional.
99
117
  email: email || "",
100
118
  emailVerified: emailVerified || false,
101
119
  photoURL: photoURL || "",
102
120
  lastUpdated: getCurrentServerTimestampInMillis()
103
121
  })
122
+
123
+ // we want to create a new collection for the users to store the avatars
124
+ const avatarRef = firestore.collection(commonTerms.collections.avatars.name).doc(uid)
125
+ await avatarRef.set({
126
+ avatarUrl: avatarUrl || ""
127
+ })
104
128
  printLog(`Authenticated user document with identifier ${uid} has been correctly stored`, LogLevel.DEBUG)
129
+ printLog(`Authenticated user avatar with identifier ${uid} has been correctly stored`, LogLevel.DEBUG)
105
130
  })
106
131
  /**
107
132
  * Set custom claims for role-based access control on the newly created user.
package/src/lib/errors.ts CHANGED
@@ -7,7 +7,7 @@ import { LogLevel } from "../types/enums"
7
7
  * @notice the set of Firebase Functions status codes. The codes are the same at the
8
8
  * ones exposed by {@link https://github.com/grpc/grpc/blob/master/doc/statuscodes.md | gRPC}.
9
9
  * @param errorCode <FunctionsErrorCode> - the set of possible error codes.
10
- * @param message <string> - the error messge.
10
+ * @param message <string> - the error message.
11
11
  * @param [details] <string> - the details of the error (optional).
12
12
  * @returns <HttpsError>
13
13
  */
@@ -184,6 +184,11 @@ export const SPECIFIC_ERRORS = {
184
184
  "unavailable",
185
185
  "VM command execution has been delayed since there were no available instance at the moment",
186
186
  "Please, contact the coordinator if this error persists."
187
+ ),
188
+ SE_VM_UNKNOWN_COMMAND_STATUS: makeError(
189
+ "unavailable",
190
+ "VM command execution has failed due to an unknown status code",
191
+ "Please, contact the coordinator if this error persists."
187
192
  )
188
193
  }
189
194
 
@@ -1,6 +1,11 @@
1
+ import dotenv from "dotenv"
2
+ import ethers from "ethers"
1
3
  import { S3Client } from "@aws-sdk/client-s3"
2
4
  import { COMMON_ERRORS, logAndThrowError } from "./errors"
3
5
 
6
+ dotenv.config()
7
+ let provider: ethers.providers.Provider
8
+
4
9
  /**
5
10
  * Return a configured and connected instance of the AWS S3 client.
6
11
  * @dev this method check and utilize the environment variables to configure the connection
@@ -26,3 +31,34 @@ export const getS3Client = async (): Promise<S3Client> => {
26
31
  region: process.env.AWS_REGION!
27
32
  })
28
33
  }
34
+
35
+ /**
36
+ * Returns a Prvider, connected via a configured JSON URL or else
37
+ * the ethers.js default provider, using configured API keys.
38
+ * @returns <ethers.providers.Provider> An Eth node provider
39
+ */
40
+ export const setEthProvider = (): ethers.providers.Provider => {
41
+ if (provider) return provider
42
+ console.log(`setting new provider`)
43
+
44
+ // Use JSON URL if defined
45
+ // if ((hardhat as any).ethers) {
46
+ // console.log(`using hardhat.ethers provider`)
47
+ // provider = (hardhat as any).ethers.provider
48
+ // } else
49
+ if (process.env.ETH_PROVIDER_JSON_URL) {
50
+ console.log(`JSON URL provider at ${process.env.ETH_PROVIDER_JSON_URL}`)
51
+ provider = new ethers.providers.JsonRpcProvider({
52
+ url: process.env.ETH_PROVIDER_JSON_URL,
53
+ skipFetchSetup: true
54
+ })
55
+ } else {
56
+ // Otherwise, connect the default provider with ALchemy, Infura, or both
57
+ provider = ethers.providers.getDefaultProvider("homestead", {
58
+ alchemy: process.env.ETH_PROVIDER_ALCHEMY_API_KEY!,
59
+ infura: process.env.ETH_PROVIDER_INFURA_API_KEY!
60
+ })
61
+ }
62
+
63
+ return provider
64
+ }
package/src/lib/utils.ts CHANGED
@@ -10,7 +10,7 @@ import admin from "firebase-admin"
10
10
  import dotenv from "dotenv"
11
11
  import { DeleteObjectCommand, GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3"
12
12
  import { getSignedUrl } from "@aws-sdk/s3-request-presigner"
13
- import { createWriteStream, fstat } from "node:fs"
13
+ import { createWriteStream } from "node:fs"
14
14
  import { pipeline } from "node:stream"
15
15
  import { promisify } from "node:util"
16
16
  import { readFileSync } from "fs"
@@ -25,7 +25,7 @@ import {
25
25
  CeremonyState,
26
26
  finalContributionIndex,
27
27
  CircuitDocument
28
- } from "@p0tion/actions"
28
+ } from "@devtion/actions"
29
29
  import fetch from "@adobe/node-fetch-retry"
30
30
  import path from "path"
31
31
  import os from "os"
@@ -166,7 +166,7 @@ export const getCircuitDocumentByPosition = async (
166
166
  // Query for all ceremony circuits.
167
167
  const circuits = await getCeremonyCircuits(ceremonyId)
168
168
 
169
- // Apply a filter using the sequence postion.
169
+ // Apply a filter using the sequence position.
170
170
  const matchedCircuits = circuits.filter(
171
171
  (circuit: DocumentData) => circuit.data().sequencePosition === sequencePosition
172
172
  )
@@ -217,7 +217,7 @@ export const downloadArtifactFromS3Bucket = async (bucketName: string, objectKey
217
217
  const streamPipeline = promisify(pipeline)
218
218
  await streamPipeline(response.body, writeStream)
219
219
 
220
- writeStream.on('finish', () => {
220
+ writeStream.on("finish", () => {
221
221
  writeStream.end()
222
222
  })
223
223
  }
@@ -305,7 +305,7 @@ export const deleteObject = async (bucketName: string, objectKey: string) => {
305
305
 
306
306
  // Prepare command.
307
307
  const command = new DeleteObjectCommand({ Bucket: bucketName, Key: objectKey })
308
-
308
+
309
309
  // Execute command.
310
310
  const data = await client.send(command)
311
311
 
@@ -385,14 +385,16 @@ export const getGitHubVariables = (): any => {
385
385
  if (
386
386
  !process.env.GITHUB_MINIMUM_FOLLOWERS ||
387
387
  !process.env.GITHUB_MINIMUM_FOLLOWING ||
388
- !process.env.GITHUB_MINIMUM_PUBLIC_REPOS
388
+ !process.env.GITHUB_MINIMUM_PUBLIC_REPOS ||
389
+ !process.env.GITHUB_MINIMUM_AGE
389
390
  )
390
391
  logAndThrowError(COMMON_ERRORS.CM_WRONG_CONFIGURATION)
391
392
 
392
393
  return {
393
394
  minimumFollowers: Number(process.env.GITHUB_MINIMUM_FOLLOWERS),
394
395
  minimumFollowing: Number(process.env.GITHUB_MINIMUM_FOLLOWING),
395
- minimumPublicRepos: Number(process.env.GITHUB_MINIMUM_PUBLIC_REPOS)
396
+ minimumPublicRepos: Number(process.env.GITHUB_MINIMUM_PUBLIC_REPOS),
397
+ minimumAge: Number(process.env.GITHUB_MINIMUM_AGE)
396
398
  }
397
399
  }
398
400
 
@@ -404,7 +406,7 @@ export const getAWSVariables = (): any => {
404
406
  if (
405
407
  !process.env.AWS_ACCESS_KEY_ID ||
406
408
  !process.env.AWS_SECRET_ACCESS_KEY ||
407
- !process.env.AWS_ROLE_ARN ||
409
+ !process.env.AWS_INSTANCE_PROFILE_ARN ||
408
410
  !process.env.AWS_AMI_ID ||
409
411
  !process.env.AWS_SNS_TOPIC_ARN
410
412
  )
@@ -414,7 +416,7 @@ export const getAWSVariables = (): any => {
414
416
  accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
415
417
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
416
418
  region: process.env.AWS_REGION || "eu-central-1",
417
- roleArn: process.env.AWS_ROLE_ARN!,
419
+ instanceProfileArn: process.env.AWS_INSTANCE_PROFILE_ARN!,
418
420
  amiId: process.env.AWS_AMI_ID!,
419
421
  snsTopic: process.env.AWS_SNS_TOPIC_ARN!
420
422
  }
@@ -0,0 +1 @@
1
+ declare module "@bandada/api-sdk"
@@ -1,4 +1,5 @@
1
- import { CeremonyInputData, CircuitDocument, ETagWithPartNumber } from "@p0tion/actions"
1
+ import { CeremonyInputData, CircuitDocument, ETagWithPartNumber } from "@devtion/actions"
2
+ import type { Groth16Proof, PublicSignals } from "snarkjs"
2
3
 
3
4
  /**
4
5
  * Group all the necessary data needed for running the `setupCeremony` cloud function.
@@ -138,3 +139,62 @@ export type FinalizeCircuitData = {
138
139
  bucketName: string
139
140
  beacon: string
140
141
  }
142
+
143
+ /**
144
+ * Group all the necessary data needed for running the `bandadaValidateProof` cloud function.
145
+ * @typedef {Object} BandadaValidateProof
146
+ * @property {string} merkleTreeRoot - the merkle tree root of the group.
147
+ * @property {string} nullifierHash - the nullifier hash of the member.
148
+ * @property {string} externalNullifier - the external nullifier of the member.
149
+ * @property {PackedProof} proof - the packed proof generated on the client.
150
+ */
151
+ export type BandadaValidateProof = {
152
+ proof: Groth16Proof
153
+ publicSignals: PublicSignals
154
+ }
155
+
156
+ /**
157
+ * Define the return object of the function that verifies the Bandada membership and proof.
158
+ * @typedef {Object} VerifiedBandadaResponse
159
+ * @property {boolean} valid - true if the proof is valid and the user is a member of the group; otherwise false.
160
+ * @property {string} message - a message describing the result of the verification.
161
+ * @property {string} token - the custom access token.
162
+ */
163
+ export type VerifiedBandadaResponse = {
164
+ valid: boolean
165
+ message: string
166
+ token: string
167
+ }
168
+
169
+ /**
170
+ * Define the check nonce object for the cloud function
171
+ * @typedef {Object} CheckNonceOfSIWEAddressRequest
172
+ * @property {string} auth0Token - token from the device flow authentication
173
+ */
174
+ export type CheckNonceOfSIWEAddressRequest = {
175
+ auth0Token: string
176
+ }
177
+
178
+ /**
179
+ * Define the check nonce response object of the cloud function
180
+ * @typedef {Object} CheckNonceOfSIWEAddressResponse
181
+ * @property {boolean} valid - if the checking result was valid or not
182
+ * @property {string} message - informative message
183
+ * @property {string} token - token to sign in
184
+ */
185
+ export type CheckNonceOfSIWEAddressResponse = {
186
+ valid: boolean
187
+ message?: string
188
+ token?: string
189
+ }
190
+ /**
191
+ * Define the response from auth0 /userinfo endpoint
192
+ *
193
+ */
194
+ export type Auth0UserInfo = {
195
+ sub: string
196
+ nickname: string
197
+ name: string
198
+ picture: string
199
+ updated_at: string
200
+ }