Github Actions: Build Failing for NEXT JS PWA App - github-actions

I have set up Unit tests to be run before pushing to the main branch via GitHub-actions. All the Unit tests are running successfully but for some reason during the build:
Ran all test suites.
info - Checking validity of types...
info - Creating an optimized production build...
warn - using beta Middleware (not covered by semver)
After this step, it fails with the error:
> Build error occurred
Error: Service account object must contain a string "project_id" property.
This error comes from the Firebase Admin SDK Configuration file as shown below:
import admin from 'firebase-admin';
const keyString = process.env.FB_ADMIN_PRIVATE_KEY ?? '{"privateKey": ""}';
const { privateKey } = JSON.parse(keyString);
if (privateKey === '') {
console.log('FIREBASE_PRIVATE_KEY is not set');
if (process.env.NODE_ENV === 'development')
throw new Error('FIREBASE_PRIVATE_KEY is not set');
else console.log('Firebase Private Key Error');
}
if (admin.apps.length === 0)
admin.initializeApp({
credential: admin.credential.cert({
clientEmail: process.env.FB_ADMIN_CLIENT_EMAIL,
privateKey: privateKey,
projectId: process.env.NEXT_PUBLIC_FB_CLIENT_PROJECT_ID,
}),
databaseURL: process.env.FB_ADMIN_RTDB_URL,
});
const db = admin.firestore();
const auth = admin.auth();
const storage = admin.storage();
const rdb = admin.database();
const Server = { auth, db, storage, rdb };
export default Server;
However, I am not sure why is this method even called? Since I have my .env secrets stored in the local, the build seems to succeed there and fail in Github actions. What should I do to resolve this error?

Since NEXT JS Generates static pages and so I was using Admin SDK to fetch some metadata at the server-side and that's why the function was triggered causing it to fail in Github Actions, seems like the only way out here will be to somehow mock the data in order for the actions to run smoothly.

Related

Error.invalid json response Unexpected token T in JSON at position 0 sanity nextjs typscript [duplicate]

This question already has an answer here:
Fetch error when building Next.js static website in production
(1 answer)
Closed 4 months ago.
hey i guys i have a question i did the build with react and typscript and sanity cms but the problems is when im trying to deploy the build to varcel it keeps rejecting it sayning that FetchError: invalid json response body at https://portfolio2-1-wn3v.vercel.app/api/getExperience reason: Unexpected token T in JSON at position 0 while it works on my local machine it find all the data and everything ... i read that it might be a problem somewhere down the line with getStaticProps or when fetching json and yes i did change the enviroment varibals from base_url in http 3000 to the varcel ones but other than that i have no idea what else i should do .... if anyone has any expirince with this kind of errors ? here is my code for the
`import {Experience} from '../typings'
export const fetchExperiences = async () =>{
const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getExperience`)
const data = await res.json()
const projects:Experience[] = data.experience
return experience
}`
the getExercise.ts file has all the api request
import type{NextApiRequest,NextApiResponse} from 'next'
import {groq} from 'next-sanity';
import {sanityClient} from '../../sanity';
import {Experience} from '../../typings'
const query = groq`
*[_type == "experience"]{
...,
technologies[]->
}
`;
type Data ={
experience:Experience[]
}
export default async function handler(
req:NextApiRequest,
res:NextApiResponse<Data>,
){
const experience:Experience[]= await sanityClient.fetch(query)
res.status(200).json(JSON.parse(JSON.stringify({experience})))
}
and this is the index.ts file part
export const getStaticProps: GetStaticProps<Props> = async() => {
const experience : Experience[] = await fetchExperiences();
const skills : Skill[] = await fetchSkills();
const projects : Project[] = await fetchProjects();
const socials : Social[] = await fetchSocials();
return{
props:{
experience,
skills,
projects,
socials,
},
revalidate:10
}
}
The error link you see (https://portfolio2-1-wn3v.vercel.app/api/getExperience) is the preview deployment link from vercel. That means, everytime you deploy to vercel it will create this preview link: https:// yourappname-(some unique deployment link).vercel.app.
However, in your api you pass ${process.env.NEXT_PUBLIC_BASE_URL} which will work on your local and probable on production, but it will not on your preview deployments (staging).
To avoid this, unfortunately you cannot only give /api/getExperience as only absolute URL's are supported. Therefore, I suggest the following approach by avoiding the API call as suggested in the [nextjs docs][1]:
you create an experience-queries.ts file in lib/
you add your GROQ query in there
export const getExperiences = groq`*[_type == "experience"]{..., technologies[]->}`
In index.ts, in getStaticProps you call getExperiences
const experiences = await sanityClient.fetch(getExperiences);
Note: Be careful with naming between experience (one single item) and experiences (a list of items) -> make sure you name if as you intend to get them.
[1]: https://nextjs.org/docs/basic-features/data-fetching/get-static-props#write-server-side-code-directly

CredentialsError: Could not load credentials from ChainableTemporaryCredentials in AWS-SDK v2 for Javascript

I am trying to set up temporary credentials in the AWS-SDK v2 for Javascript:
const aws = require('aws-sdk')
aws.config = new aws.Config({
credentials: new aws.ChainableTemporaryCredentials({
params: {
RoleArn: roleArn, // Defined earlier
RoleSessionName: sessionName, // Defined earlier
DurationSeconds: 15 * 60
},
masterCredentials: new aws.Credentials({
accessKeyId: accessKeyId, // Defined earlier
secretAccessKey: awsSecretAccessKey // Defined earlier
})
}),
region: 'us-east-1',
signatureVersion: 'v4'
})
aws.config.getCredentials(function (err) {
if (err) console.log(err.stack)
else console.log('Access key:', aws.config.credentials.accessKeyId)
})
However, I'm keep getting the following error, which occurs when calling getCredentials:
CredentialsError: Could not load credentials from ChainableTemporaryCredentials
Note that it works fine if I set the credentials parameter to the master credentials instead of the temporary credentials, as shown below:
aws.config = new aws.Config({
credentials: new aws.Credentials({
accessKeyId: accessKeyId, // Defined earlier
secretAccessKey: awsSecretAccessKey // Defined earlier
}),
region: 'us-east-1',
signatureVersion: 'v4'
})
Does anyone know what's causing this issue? Here's the documentation I was referencing:
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Config.html
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/ChainableTemporaryCredentials.html
I was finally able to figure out the cause of this error.
What led me to figure out the cause of the error was when I printed out the full error instead of just the most recent error. One of the properties of the error was:
originalError: {
message: 'The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.',
code: 'SignatureDoesNotMatch',
time: 2021-12-11T19:49:52.395Z,
requestId: '402e4c32-7989-4287-a6a9-628bfc93f60f',
statusCode: 403,
retryable: false,
retryDelay: 39.60145242362791
}
So I realized the problem was that my masters credentials I provided were not correct!
I have actually always known that these credentials weren't correct, but for unit-testing purposes it seemed to work fine with these incorrect credentials as long as I didn't also supply the temporary credentials. But now I understand that the getCredentials function verifies the credentials with AWS if you're using temporary credentials, but doesn't verify with AWS when using just master credentials. That explains that strange behavior I was seeing.

Firebase cloud functions / One works, other (same function) not works

I am very nervous.. I can't test normally firebase cloud functions, because a lot of things don't work. I tested it, I copied same function with a different name, the new function don't work.
Why????
Why working helloworld and why not working tryhello???
cloud functions nodejs index.js:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.tryHello = functions.https.onCall((data, context) => {
let dataexample = {
name: 'examplename',
state: 'examplestate',
country: 'examplecountry'
};
let setDoc = db.collection('newexample').doc(data.text).set(dataexample);
return { text : "success. uid:" + context.auth.uid }
});
exports.helloWorld = functions.https.onCall((data, context) => {
let dataexample = {
name: 'examplename',
state: 'examplestate',
country: 'examplecountry'
};
let setDoc = db.collection('newexample').doc(data.text).set(dataexample);
return { text : "success. uid:" + context.auth.uid }
});
Unity C#:
public void testbutton()
{
var data = new Dictionary<string, object>();
data["text"] = "example";
//I tested "tryHello" and helloWorld"
FirebaseFunctions.DefaultInstance.GetHttpsCallable("tryHello")
.CallAsync(data).ContinueWith((task) =>
{
if (task.IsFaulted)
{
// Handle the error...
print("error");
}
else if (task.IsCompleted)
{
IDictionary snapshot = (IDictionary)task.Result.Data;
print("Result: " + snapshot["text"]);
}
}
Result:
1. First, I write unity: GetHttpsCallable("helloWorld") and save.
I start game, login, then I click testbutton.
result: firebase console: success create example collection, example document, country:examplecountry, name:examplename, state:examplestate. Ok good.
unity log:
1. User signed in successfully: Jane Q. User (qQC3wEOU95eDFw8UuBjb0O1o20G2)
UnityEngine.Debug:LogFormat(String, Object[])
loginfire:b__10_0(Task1) (at Assets/loginfire.cs:155)
2. Result: success. uid:qQC3wEOU95eDFw8UuBjb0O1o20G2
UnityEngine.MonoBehaviour:print(Object)
<>c:<testbutton>b__16_0(Task1) (at Assets/loginfire.cs:411)
System.Threading._ThreadPoolWaitCallback:PerformWaitCallback()
cloud functions "helloWorld" log:
Function execution started
Function execution took 3020 ms, finished with status code: 200
Ok. I delete "example" collection in firebase console.
2. Second, I write unity: GetHttpsCallable("tryHello") and save.
I start game, login, then I click testbutton.
result: not create collection.
unity log:
*1. User signed in successfully: Jane Q. User (qQC3wEOU95eDFw8UuBjb0O1o20G2)
UnityEngine.Debug:LogFormat(String, Object[])
loginfire:b__10_0(Task`1) (at Assets/loginfire.cs:155)
System.Threading._ThreadPoolWaitCallback:PerformWaitCallback()
error
UnityEngine.MonoBehaviour:print(Object)
<>c:b__16_0(Task`1) (at Assets/loginfire.cs:396)
System.Threading._ThreadPoolWaitCallback:PerformWaitCallback()*
cloud functions "tryHello" log:
nothing...
Why?
I don't understand. same, only the name is different!
And.. in many cases it show success but still does not update the database. or just much later. why? Lately, "helloWorld" also often writes an error, if I don't press the testbutton immediately after logging in, it can't read the uid.
I start to get tired of the system right from the start.
Thanks..
Solved!
I needed it configured to cloud console "tryHello" permission settings. (Not same helloworld settings.)
Lately, "helloWorld" also often writes an error, if I don't press the testbutton immediately after logging in, it can't read the uid.
-> I needed declared Firebasauth within testbutton().
Sorry for the question, thanks.

web3.eth.accounts.create method doesn't actually create new account

I try to create an eth account via RPC in private network.
What I have done so far are:
launch geth node and create private network.
create simple javascript program using web3 1.0.0, typescript
run and get result as below but the account isn't created
Code:
const result = await web3.eth.personal.unlockAccount(senderId, senderPassword, duration)
if (result === true) {
// const newAccountResult = await web3.eth.personal.newAccount('password')
const newAccountResult = await web3.eth.accounts.create('user01')
console.log(newAccountResult)
}
Result:
web3.eth.accounts.create returns the following result
{ address: '0xf10105f862C1cB10550F4EeB38697308c7A290Fc',
privateKey: '0x5cba6b397fc8a96d006988388553ec17a000f7da9783d906979a2e1c482e7fcb',
signTransaction: [Function: signTransaction],
sign: [Function: sign],
encrypt: [Function: encrypt] }
But web3.eth.getAccounts method returns only 1 account.
[ '0xaf0034c41928Db81E570061c58c249f61CFF57f2' ]
Seems web3.eth.accounts.create method has succeeded as the result includes account address and private key.
But I don't understand why web3.eth.getAccounts method doesn't include the created account.
I also checked geth via console, the result is same.
> eth.accounts
["0xaf0034c41928db81e570061c58c249f61cff57f2"]
And eth.personal.newAccount didn't work.
Do I need to do something after web3.eth.accounts.create?
I appreciate any help.
If i got it right, web.eth.accounts.create is a way to create accounts without storing them on the local node, so its basically a way to get a valid keypair on-the-fly without storing anything on the keystore)
web3.eth.personal.newAccount() should be availabel if you have the personal-API activated on your geth node (which is default behavior for ganache, with geth you need to activate it via geth --dev/testnet --rpc --rpcapi eth,web3,personal (note: of course you should be very careful with allowing personal-API on mainnet, make sure that RPC access is restricted so only you/privileged users can access it)
(async () => {
let newAccount = await web3.eth.personal.newAccount();
console.log(newAccount);
let accounts = await web3.eth.getAccounts();
console.log(accounts);
})();
Should give something like
0xb71DCf0191E2B90efCD2638781DE40797895De66
[
...
'0xb71DCf0191E2B90efCD2638781DE40797895De66' ]
Refs https://medium.com/#andthentherewere0/should-i-use-web3-eth-accounts-or-web3-eth-personal-for-account-creation-15eded74d0eb

#feathersjs/socketio-client connection timeout. Why?

I maked follow:
feathers g app # with socket and rest
feathers g service # todos & NeDB
npm start
and simple client for this. I copy code from documentation
https://docs.feathersjs.com/api/client/socketio.
const feathers = require('#feathersjs/feathers');
const socketio = require('#feathersjs/socketio-client');
const io = require('socket.io-client');
const socket = io('http://localhost:3030');
const app = feathers();
app.configure(socketio(socket));
app.service('todos')
.on('created', message => console.log('New message created', message));
app.service('todos').find().then(r => {
console.log(r)
}).catch(e => console.log('error',e))
app.service('todos').create({
title: 'A message from a REST client'
});
this client code get me timeout errors for find() and create() methods
But if I make POST request by CURL, I have onCreated message in console
Why I got errors on create() and find() calls?
UPDATE:
I maked git repo for easy reproduce this problem
https://github.com/tolyanor/feathersjs-error
UPDATE2:
I change autogenerated file src/app.js like in feathers example chat application https://github.com/feathersjs/feathers-chat/blob/master/src/app.js
Now I CAN call service method create on client, but CAN NOT receive onCreated message. So, this code
app.service('/todos')
.on('created', message => console.log('New todos created', message));
never calling
You are using a Feathers v3 client with a Feathers v2 server. Old clients will be backwards compatible with new servers but not the other way around. Follow the migration guide to upgrade your server or generate a new application using #feathersjs/cli (feathers --version on the command line should show v3.5.0 or later).