I'm trying to receive SSE data as JSON in my Flutter app. But instead of getting the data I'm getting the following repeated arrays of numbers in my console.
I/flutter (17286): Received streamedResponse.statusCode:200
I/flutter (17286): Received data:[100, 97, 116, 97, 58, 32, 123, 34, 109, 115, 103, 34, 58, 34, 84, 104, 105, 115, 32, 105, 115, 32, 109, 121, 32, 109, 101, 115, 115, 97, 103, 101, 34, 125, 10, 10]
I/flutter (17286): Received data:[100, 97, 116, 97, 58, 32, 123, 34, 109, 115, 103, 34, 58, 34, 84, 104, 105, 115, 32, 105, 115, 32, 109, 121, 32, 109, 101, 115, 115, 97, 103, 101, 34, 125, 10, 10]
Here's what the SSE data looks like on the server
data: {"msg":"This is my message"}
data: {"msg":"This is my message"}
data: {"msg":"This is my message"}
(repeated over and over)
And here's the Flutter code;
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class MyApp extends StatelessWidget {
http.Client _client;
MyApp() : super() {
subscribe();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter SSE',
home: Scaffold(
appBar: AppBar(
title: Text('Receive SSE Events'),
),
body: Center(
child: Text('Ready for events..'),
),
),
);
}
subscribe() async {
print("Subscribing..");
try {
_client = http.Client();
var request = new http.Request("GET", Uri.parse("http://18.224.97.18:8080/connect"));
request.headers["Cache-Control"] = "no-cache";
request.headers["Accept"] = "text/event-stream";
Future<http.StreamedResponse> response = _client.send(request);
response.asStream().listen((streamedResponse) {
print("Received streamedResponse.statusCode:${streamedResponse.statusCode}");
streamedResponse.stream.listen((data) {
print("Received data:$data");
});
});
} catch(e) {
print("Caught $e");
}
}
unsubscribe() {
_client.close();
}
}
I'm not sure why "print("Received data:$data") is giving arrays of numbers instead of the {"msg":"This is my message"} in the SSE stream.
Anyone know why I'm getting these numbers instead of the data?
ByteStream is the data being returned from streamedResponse.stream.listen(). To decode the value, you can use utf8.decode(data) like what has been mentioned in the comments.
use flutter_client_sse
package for the Server-Sent-Event Stream data. It returns parsed model of the event, id and the data.
Related
I want to pass the execSync function of node.js a string that is not in a line (I mean it has a number of new lines). for example:
require('child_process').execSync(`echo hello
world
to
all > /home/kali/Desktop/output`);
but I have the below error:
/bin/sh: 2: world: not found
node:child_process:903
throw err;
^
Error: Command failed: echo hello
world > /home/kali/Desktop/output
/bin/sh: 2: world: not found
at checkExecSyncError (node:child_process:826:11)
at Object.execSync (node:child_process:900:15)
at Object.<anonymous> (/home/kali/Desktop/vm_escape.js:36:26)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47 {
status: 127,
signal: null,
output: [
null,
Buffer(6) [Uint8Array] [ 104, 101, 108, 108, 111, 10 ],
Buffer(29) [Uint8Array] [
47, 98, 105, 110, 47, 115, 104,
58, 32, 50, 58, 32, 119, 111,
114, 108, 100, 58, 32, 110, 111,
116, 32, 102, 111, 117, 110, 100,
10
]
],
pid: 216244,
stdout: Buffer(6) [Uint8Array] [ 104, 101, 108, 108, 111, 10 ],
stderr: Buffer(29) [Uint8Array] [
47, 98, 105, 110, 47, 115, 104,
58, 32, 50, 58, 32, 119, 111,
114, 108, 100, 58, 32, 110, 111,
116, 32, 102, 111, 117, 110, 100,
10
]
}
it is because of new lines. it doesn't execute "echo hello world to all > /home/kali/Desktop/output" as a single command. but It executes the "echo hello", "world", "to", and "all" commands so I have errors. because of some limitations in my project I can't use double quotation and quotation inside back quote. what should I do?
edited:
new line is the delimiter for execSync. is there any way to change the delimiter in execSync? or is there any alternative for execSync that its delimiter is not new line?
you should be able to remove the line breaks with a replace
require('child_process').execSync(`echo hello
world
to
all > /home/kali/Desktop/output`.replace(/(\r\n|\n|\r)/gm, ``));
which would be equivalent to running
require('child_process').execSync(`echo hello world to all > /home/kali/Desktop/output`);
I tried to use two Rust libraries to compute hmacsha1: hmacsha and hmac-sha1.
This functions use different set of params(hmacsha require strings, hmac-sha1 require [u8]) and return different result. I used this online tool to compare. hmacsha return same with online tool result, hmac-sha1 different from both online tool and hmacsha.
This is how I use hmacsha:
const ENCRYPT_KEY: &str = "C2B3723CC6AED9B5343C53EE2F4367CE";
let key = [200, 7, 216, 173, 213, 146, 229, 69, 96, 121, 68, 66, 55, 215, 179, 150, 34, 206, 128, 136, 252, 37, 173, 113, 170, 80, 148, 36, 5, 129, 212, 183, 47, 24, 47, 123, 157, 47, 26, 2];
let hash_key = HmacSha::from(
&encode_hex(&key), // C807D8ADD592E5456079444237D7B39622CE8088FC25AD71AA5094240581D4B72F182F7B9D2F1A02
ENCRYPT_KEY,
Sha1::default()
).compute_digest();
println!("{:?}", encode_hex(&hash_key)); // 545E5C8D754F21DD586BA7378F8AA7AA815F4500
This is my encode_hex function I use for both examples:
pub fn encode_hex(bytes: &[u8]) -> String {
let mut s = String::with_capacity(bytes.len() * 2);
for &b in bytes {
write!(&mut s, "{:02x}", b).unwrap();
}
s.to_uppercase()
}
This is how I use hmac-sha1:
const ENCRYPT_KEY: [u8; 16] = [
0xC2, 0xB3, 0x72, 0x3C, 0xC6, 0xAE, 0xD9, 0xB5, 0x34, 0x3C, 0x53, 0xEE, 0x2F, 0x43, 0x67, 0xCE
];
let key = [200, 7, 216, 173, 213, 146, 229, 69, 96, 121, 68, 66, 55, 215, 179, 150, 34, 206, 128, 136, 252, 37, 173, 113, 170, 80, 148, 36, 5, 129, 212, 183, 47, 24, 47, 123, 157, 47, 26, 2];
let hash_key = &hmac_sha1(&key, &ENCRYPT_KEY2);
println!("{:?}", encode_hex(&hash_key)); // 80FEC15187802FFB4EA8124220A19DD575E45DC3
Could somebody explain what am I doing wrong ?
HmacSha::from from hmac-sha crate takes a string as the key but it does not expect a hex-encoded string. It instead uses the bytes of the string as-is. This seems like a mistake in the API since this will only accept keys that are valid UTF-8 bytes. You should instead use HmacSha::new from the same crate, which accepts a byte slice as the key:
let hash_key = HmacSha::new(
&key, // no encode_hex() here
ENCRYPT_KEY,
Sha1::default()
).compute_digest();
How can I read buffer data from the type script?
I want to use the public key to get all the token lists I own.
I'm trying to get this, but an empty array of objects is being returned.
import {Connection, Keypair} from "#solana/web3.js";
const Solana = new Connection("https://api.testnet.solana.com/","confirmed")
const getInfo = async () => {
const recentInfo = await Solana.getEpochInfo()
const DEMO_FROM_SECRET_KEY = new Uint8Array([
223, 119, 171, 5, 237, 138, 42, 140, 176, 163, 74,
107, 25, 143, 90, 97, 250, 158, 203, 102, 238, 19,
77, 228, 211, 238, 147, 149, 40, 50, 211, 155, 51,
207, 14, 53, 86, 230, 164, 27, 14, 202, 78, 181,
185, 250, 16, 52, 134, 242, 96, 16, 12, 67, 2,
178, 106, 241, 156, 212, 11, 150, 114, 72])
const keypair = Keypair.fromSecretKey(DEMO_FROM_SECRET_KEY)
console.log("=============get account info==============")
async function fetchaccountdata() {
const accountinfo = await Solana.getParsedAccountInfo(keypair.publicKey,"max")
const accountinfodata = JSON.stringify(accountinfo)
const accountinfodata2 = JSON.parse(accountinfodata)
console.log(accountinfo)
console.log("=============get account info==============")
console.log(accountinfodata)
console.log(accountinfodata2)
}
fetchaccountdata()
}
getInfo()
Terminal is
accountinfodata = {"context":{"slot":94636033},"value":{"data":{"type":"Buffer","data":[]},"executable":false,"lamports":42784111360,"owner":{"_bn":"00"},"rentEpoch":231}}
accountinfodata2 = {
context: { slot: 94636033 },
value: {
data: { type: 'Buffer', data: [] },
executable: false,
lamports: 42784111360,
owner: { _bn: '00' },
rentEpoch: 231
}
}
The data of accountinfo object is empty array.
How can I read the information?
This call is fetching the account data for your wallet. Your wallet only holds SOL, which is why the data is nothing!
If you want to get all of the token accounts that you own, you'll be better off using getParsedTokenAccountsByOwner: https://github.com/solana-labs/solana/blob/2a42f8a06edd4d33c6cda4d66add0a2582d37011/web3.js/src/connection.ts#L2310
The buffer contains account info data in no particular format. Borsh has recently been established as a standard, though.
Example borsh serialization from SPL:
https://github.com/solana-labs/solana-program-library/blob/master/token/program/src/state.rs#L128
Example borsh deserialization for metaplex metadata: https://github.com/metaplex-foundation/metaplex-program-library/blob/master/token-metadata/program/src/instruction.rs#L77-L78
If you aren't trying to decode metaplex metadata, you should look elsewhere for the schema, but follow the same principles of the code. If you know the account isn't using borsh, then it's up to you to decode it.
Visit the solana tech discord for more information/help.
https://discord.com/channels/428295358100013066/517163444747894795/917412508418068510
function createData(collegeName, registrarName, phoneNumber, emailAddress, action) {
return {collegeName , registrarName, phoneNumber, emailAddress, action };
}
var rows = [
createData("data", 305, 3.7, 67, 4.3),
createData('Donut', 452, 25.0, 51, 4.9),
createData('Eclair', 262, 16.0, 24, 6.0),
createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
createData('Gingerbread', 356, 16.0, 49, 3.9),
createData('Honeycomb', 408, 3.2, 87, 6.5),
createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
createData('Jelly Bean', 375, 0.0, 94, 0.0),
createData('KitKat', 518, 26.0, 65, 7.0),
createData('Lollipop', 392, 0.2, 98, 0.0),
createData('Marshmallow', 318, 0, 81, 2.0),
createData('Nougat', 360, 19.0, 9, 37.0),
createData('Oreo', 437, 18.0, 63, 4.0),
];
this is static data (you can check using full code for table ) but i want to feed rows by dynamic data :this is the response of database
You shoul use a Map to generate an input for your table rows property:
let list = (data && data.profiles != null) ? data.profiles.map((value, index, array) => {
return {
id: value.id,
key: value.id,
name: value.name,
})
Above code is an example, change variables to your owns.
With the following javascript request:
navigator.credentials.create({
publicKey: {
// random, cryptographically secure, at least 16 bytes
challenge: new Uint8Array(16),
// relying party
rp: {
id: 'localhost',
name: 'My website'
},
user: {
id: new Uint8Array(16),
name: 'Tang',
displayName: 'Tang'
},
pubKeyCredParams: [
{
type: "public-key", alg: -7
}
],
attestation: "direct"
}
})
a FIDO2-compatible Yubikey 5 NFC systematically returns a "fido-u2f" attestation statement:
%{
"attStmt" => %{
"sig" => <<48, 69, 2, 33, 0, 132, 31, 225, 91, 58, 61, 190, 47, 66, 168, 8,
177, 18, 136, 106, 100, 219, 54, 52, 255, 103, 106, 156, 230, 141, 240,
82, 130, 167, 204, 128, 100, 2, 32, 61, 159, 126, 9, 244, 55, 100, 123,
169, ...>>,
"x5c" => [
<<48, 130, 2, 188, 48, 130, 1, 164, 160, 3, 2, 1, 2, 2, 4, 3, 173, 240,
18, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 11, 5, 0, 48, 46, 49,
44, 48, 42, 6, 3, 85, 4, 3, 19, ...>>
]
},
"authData" => <<73, 150, 13, 229, 136, 14, 140, 104, 116, 52, 23, 15, 100,
118, 96, 91, 143, 228, 174, 185, 162, 134, 50, 199, 153, 92, 243, 186, 131,
29, 151, 99, 65, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...>>,
"fmt" => "fido-u2f"
}
How to receive a FIDO2 "packed" attestation statement instead?
Per the current spec/standard I don't think you (acting as a Relying Party) can "select" which attestation statement format you receive from the Authenticator (i.e. "the device"). That is a decision made by the Authenticator.
I think MacBook Pro TouchID platform authenticator via Chrome Desktop is sending "packed" attestation statements, if that helps.
There is no way to select the attestation using such simple keys. To test my implementation for both attestations I simply bought two different keys one from Yibico and one from Nitrokey. Yubico sends fido-u2f, while the Nitrokey sends packed attestations.
And if someone likes to know, this is how I implemented that:
let verifyAuthenticatorAttestationResponse = (webAuthnResponse) => {
let attestationBuffer =
base64url.toBuffer(webAuthnResponse.response.attestationObject);
let ctapMakeCredResp = cbor.decodeAllSync(attestationBuffer)[0];
let authrDataStruct = parseMakeCredAuthData(ctapMakeCredResp.authData);
let response = {'verified': false };
if(ctapMakeCredResp.fmt === 'fido-u2f' || ctapMakeCredResp.fmt === 'packed') {
if(!(authrDataStruct.flags & U2F_USER_PRESENTED))
throw new Error('User was NOT presented durring authentication!');
let clientDataHash =
hash(base64url.toBuffer(webAuthnResponse.response.clientDataJSON))
let publicKey = COSEECDHAtoPKCS(authrDataStruct.COSEPublicKey)
let PEMCertificate = ASN1toPEM(ctapMakeCredResp.attStmt.x5c[0]);
let signature = ctapMakeCredResp.attStmt.sig;
let signatureBase;
if(ctapMakeCredResp.fmt === 'fido-u2f') {
signatureBase = Buffer.concat([Buffer.from([0x00]), authrDataStruct.rpIdHash, clientDataHash, authrDataStruct.credID, publicKey]);
} else {
signatureBase = Buffer.concat([ctapMakeCredResp.authData, clientDataHash]);
}
response.verified = verifySignature(signature, signatureBase, PEMCertificate)
if(response.verified) {
response.authrInfo = {
fmt: `${ctapMakeCredResp.fmt}`,
publicKey: base64url.encode(publicKey),
counter: authrDataStruct.counter,
credID: base64url.encode(authrDataStruct.credID)
}
}
}
return response
}
By default the browser might select U2F. Try forcing UV by setting it to "required". This will force browser to use FIDO2 as U2F does not support UV.