Skip to content

Commit

Permalink
With known issues. See signify-ts #284 WebOfTrust/signify-ts#284
Browse files Browse the repository at this point in the history
  • Loading branch information
edeykholt committed Oct 16, 2024
1 parent 2c6b391 commit f23ab97
Show file tree
Hide file tree
Showing 14 changed files with 118 additions and 110 deletions.
3 changes: 2 additions & 1 deletion KeriAuth.BrowserExtension.sln
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
.editorconfig = .editorconfig
KERIAuthArchitecture.jpg = KERIAuthArchitecture.jpg
README.md = README.md
PAGE-CS-MESSAGES.md = PAGE-CS-MESSAGES.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KeriAuth.BrowserExtension.Tests", "KeriAuth.BrowserExtension.Tests\KeriAuth.BrowserExtension.Tests.csproj", "{3DA9AB88-7EFD-460F-A919-3D8BCE0EA95D}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KeriAuth.BrowserExtension.Tests", "KeriAuth.BrowserExtension.Tests\KeriAuth.BrowserExtension.Tests.csproj", "{3DA9AB88-7EFD-460F-A919-3D8BCE0EA95D}"
ProjectSection(ProjectDependencies) = postProject
{118B1C27-1F19-4566-849E-D2EA618A6988} = {118B1C27-1F19-4566-849E-D2EA618A6988}
EndProjectSection
Expand Down
2 changes: 1 addition & 1 deletion KeriAuth.BrowserExtension/KeriAuth.BrowserExtension.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
<PackageReference Include="Polly" Version="8.4.1" />
<PackageReference Include="Stateless" Version="5.16.0" />
<PackageReference Include="System.Reactive" Version="6.0.1" />
<PackageReference Include="System.Text.Json" Version="8.0.2" />
<PackageReference Include="System.Text.Json" Version="8.0.5" />
<PackageReference Include="WebExtensions.Net" Version="2.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="8.0.7" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="8.0.7" PrivateAssets="all" />
Expand Down
23 changes: 23 additions & 0 deletions KeriAuth.BrowserExtension/Models/ApiRequest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Text.Json.Serialization;

namespace KeriAuth.BrowserExtension.Models
{
public record ApiRequest
{
[JsonPropertyName("url")]
public string Url { get; init; } = string.Empty;

[JsonPropertyName("method")]
public string Method { get; init; } = "GET";

// Default constructor
public ApiRequest() { }

// Constructor with parameters (if needed)
public ApiRequest(string url, string method)
{
Url = url;
Method = method;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -352,21 +352,9 @@ async Task<Result<string>> ISignifyClientService.SignRequestHeader(string origin
logger.LogInformation("SignRequestHeader: jsonInputHeaders: `{i}`", jsonInputHeaders);
logger.LogInformation("SignRequestHeader: invoke params: origin: `{o}` rurl: `{r}` method: `{m}` jsonInputHeaders: `{i}` prefix: `{p}`", origin, rurl, method, jsonInputHeaders, prefix);


// tmp test
//var aidJson = await Signify_ts_shim.GetAID(prefix);
//logger.LogWarning("SignRequestHeader: aidJson: {s}", aidJson);
// end tmp test


// TODO consider timeout, e.g. await TimeoutHelper.WithTimeout<string>(...



var signedHeadersAsJsonBase64 = await Signify_ts_shim.GetSignedHeadersWithJsonHeaders(origin, rurl, method, jsonInputHeaders, prefix);
logger.LogInformation("SignRequestHeader: signedHeadersAsJsonBase64: {s}", signedHeadersAsJsonBase64);


// Step 1: Decode the Base64 string
byte[] jsonBytes = Convert.FromBase64String(signedHeadersAsJsonBase64);
string jsonString = Encoding.UTF8.GetString(jsonBytes);
Expand All @@ -380,7 +368,6 @@ async Task<Result<string>> ISignifyClientService.SignRequestHeader(string origin
string json = JsonConvert.SerializeObject(jsonObject, Formatting.Indented);
logger.LogInformation("SignRequestHeader: signedHeaders as json-like: {p}", json);


return Result.Ok(json);
}
catch (JSException e)
Expand Down
2 changes: 1 addition & 1 deletion KeriAuth.BrowserExtension/Services/StorageService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ public async Task NotifyStorageChanged(Dictionary<string, Dictionary<string, Jso
case "managed":
case "session":
default:
logger.LogError("Responding to storage area not yet implemented: {areaname}", areaname);
logger.LogError("Responding to storage area not implemented: {areaname}", areaname);
break;
}
}
Expand Down
77 changes: 29 additions & 48 deletions KeriAuth.BrowserExtension/UI/Pages/RequestSignPage.razor
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
@using System;
@using System.Collections.Generic;


@implements IDisposable

@inject IStorageService storageService
Expand Down Expand Up @@ -54,12 +53,12 @@
{
try
{
var x = new Uri(OriginStr);
return x;
var uri = new Uri(OriginStr);
return uri;
}
catch (Exception ex)
{
logger.LogError("Error parsing OriginStr '{o}': {e}", OriginStr, ex);
logger.LogError("GetOriginUri: Error parsing OriginStr '{o}': {e}", OriginStr, ex);
return null;
}
}
Expand All @@ -84,15 +83,6 @@

WebsiteConfig? ThisWebsiteConfig { get; set; }

// async Task updateSelectedPrefix(string prefix)
// {
// SelectedPrefix = prefix;
// TODO following should be just un/resubscribe to another websiteConfig? ... and this UI is made responsive to an IObserver<WebsiteConfig>
// Debug.Assert(GetOriginUri() is not null);
// await getWebsiteConfig(GetOriginUri()!);
// StateHasChanged();
// }
async Task updateIsCredentialRemembered(bool isChecked)
{
IsCredentialRemembered = isChecked;
Expand Down Expand Up @@ -226,10 +216,6 @@

string jsonString = decodedMsg2.ToString(); // Convert StringValues to string




// Parse the JSON string
// TODO write exception handling around the following
JsonDocument jsonDocument = JsonDocument.Parse(jsonString);
Expand All @@ -240,7 +226,6 @@
RequestId = requestId.ToString();

return;

}
else
{
Expand Down Expand Up @@ -321,7 +306,6 @@
this.StateHasChanged();
}


List<Dictionary<string, object>> credentials = new();

private async Task getCredentials()
Expand All @@ -347,57 +331,51 @@
}
}

// TODO move into Models directory file
public record ApiRequest
{
[JsonPropertyName("url")]
public string Url { get; init; }

[JsonPropertyName("method")]
public string Method { get; init; }
}

/*
/ SignRequest()
*/
async Task SignRequest(SignInMode RequestedSignInMode, string requestId2, string? SelectedName, string payloadJson)
{

logger.LogInformation("SignRequest: payloadJson: {d}", payloadJson);

ApiRequest? request = JsonSerializer.Deserialize<ApiRequest>(payloadJson);
if (request is null)
{
logger.LogError("Error in SignRequest: {0}", "Invalid payloadJson");
logger.LogError("SignRequest: Error: {0}", "Invalid payloadJson");
return;
}
logger.LogInformation("SignRequest: request: {d}", request.ToString());

// headers is intentionally empty for now
Dictionary<string, string> inputHeadersDict = new Dictionary<string, string>();
var inputHeadersDict = new Dictionary<string, string>();

var replyMessageDataRes = await signifyClientService.SignRequestHeader(OriginStr, request.Url, request.Method, inputHeadersDict, SelectedName!);
if (replyMessageDataRes.IsFailed || replyMessageDataRes.Value is null)
var signedRequestResultJsonRes = await signifyClientService.SignRequestHeader(OriginStr, request.Url, request.Method, inputHeadersDict, SelectedName!);
if (signedRequestResultJsonRes.IsFailed || signedRequestResultJsonRes.Value is null)
{
logger.LogError("Error in SignRequest: {0}", replyMessageDataRes.Errors);
logger.LogError("SignRequest: Error: {0}", signedRequestResultJsonRes.Errors);
return;
}
else
{
var replyMessageData = replyMessageDataRes.Value;
logger.LogInformation("replyMessageData: {r}", replyMessageData);
var signedRequestResultJson = signedRequestResultJsonRes.Value;
logger.LogInformation("SignRequest: replyMessageData: {r}", signedRequestResultJson);

var tmp = JsonSerializer.Deserialize<SignedRequestResult>(replyMessageData);
if (tmp is null)
var signedRequestResult = JsonSerializer.Deserialize<SignedRequestResult>(signedRequestResultJson);
if (signedRequestResult is null)
{
// TODO: return an error in ReplyMessageData instead
throw new Exception("cannot deserialize replyMessageData");
var errMsg = "KeriAuth could not deserialize signedRequestResult";
logger.LogError("SignRequest error: {e}", errMsg);
var replyMessageDataErr = new ReplyMessageData<SignedRequestResult>("/signify/reply", null, requestId2, null, errMsg);
await appSwMessagingService.SendToServiceWorkerAsync<SignedRequestResult>(replyMessageDataErr);
}
else
{
// var tmp = new SignedHeadersResult("1", "2", "3", "4");
var tmp2 = new ReplyMessageData<SignedRequestResult>("/signify/reply", tmp, requestId2, null, "KeriAuth");
await appSwMessagingService.SendToServiceWorkerAsync<SignedRequestResult>(tmp2);
var replyMessageData = new ReplyMessageData<SignedRequestResult>(
"/signify/reply",
signedRequestResult,
requestId2,
null,
"KeriAuth");
await appSwMessagingService.SendToServiceWorkerAsync<SignedRequestResult>(replyMessageData);
// TODO close commented out to help with debugging
// UIHelper.CloseWindow();
}
Expand All @@ -406,12 +384,14 @@

async Task Cancel()
{
var cr = new ReplyMessageData<AuthorizeResult>(
var replyMessageData = new ReplyMessageData<AuthorizeResult>(
"/KeriAuth/signify/replyCancel",
new AuthorizeResult(null, null),
requestId: RequestId
requestId: RequestId,
null,
"KeriAuth"
);
await appSwMessagingService.SendToServiceWorkerAsync<AuthorizeResult>(cr);
await appSwMessagingService.SendToServiceWorkerAsync<AuthorizeResult>(replyMessageData);
// Close blazor application
UIHelper.CloseWindow();
}
Expand All @@ -422,6 +402,7 @@
;
}

// TODO remove or create helper?
static bool IsJsonValid(string jsonString)
{
try
Expand Down
3 changes: 1 addition & 2 deletions KeriAuth.BrowserExtension/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion KeriAuth.BrowserExtension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"ecdsa-secp256r1": "^1.3.3",
"esbuild": "^0.19.12",
"esbuild-plugin-alias": "^0.2.1",
"eslint": "^9.5.0",
"eslint": "^9.12.0",
"path": "^0.12.7",
"signify-ts": "github:WebOfTrust/signify-ts",
"polaris-web": "github:WebOfTrust/polaris-web",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ export const CsToPageMsgIndicator = "KeriAuthCs";

export interface KeriAuthMessageData<T = unknown> extends MessageData<T> {
source: typeof CsToPageMsgIndicator;
rurl?: string;
}

// Signing related types from signify-browser-extension config/types.ts. Here because we don't want dependencies on signify-browser-extension,
Expand Down
32 changes: 9 additions & 23 deletions KeriAuth.BrowserExtension/wwwroot/scripts/es6/service-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,15 +190,16 @@ async function isWindowOpen(windowId: number): Promise<boolean> {
});
}

function serializeAndEncode(obj: object): string {
function serializeAndEncode(obj: any): string {
// TODO assumes the payload obj is simple
const jsonString: string = JSON.stringify(obj);
const encodedString: string = encodeURIComponent(jsonString);
return encodedString;
}

function handleSignRequest(msg: any, csTabPort: chrome.runtime.Port) {
function handleSignRequest(payload: any, csTabPort: chrome.runtime.Port) {
// ICsSwMsgSignRequest
console.log("SW handleSignRequest: ", msg);
console.log("SW handleSignRequest: ", payload);
// TODO EE! temporary placeholder. Should request user to sign request


Expand All @@ -208,33 +209,17 @@ function handleSignRequest(msg: any, csTabPort: chrome.runtime.Port) {
const tabId = Number(csTabPort.sender.tab.id);
//chrome.action.setBadgeText({ text: "3", tabId: tabId });
//chrome.action.setBadgeTextColor({ color: '#FF0000', tabId: tabId });
// TODO Could alternately implement the msg passing via messaging versus the URL
// TODO Could alternately implement the payload passing via messaging versus the URL
// TODO should start a timer so the webpage doesn't need to wait forever for a response from the user? Then return an error.

// TODO EE! add msgRequestId
const jsonOrigin = JSON.stringify(csTabPort.sender.origin);
console.log("SW handleSignRequest: tabId: ", tabId, "message value: ", msg, "origin: ", jsonOrigin);
console.log("SW handleSignRequest: tabId: ", tabId, "payload value: ", payload, "origin: ", jsonOrigin);

const encodedMsg = serializeAndEncode(msg);
const encodedMsg = serializeAndEncode(payload);

try {
useActionPopup(tabId, [{ key: "message", value: encodedMsg }, { key: "origin", value: jsonOrigin }, { key: "popupType", value: "SignRequest" }]);
//const credObject = JSON.parse(msg.payload.credential.rawJson);
//const expiry = Math.floor((new Date().getTime() + 30 * 60 * 1000) / 1000);
//const authorizeResultCredential = { credential: { raw: credObject, cesr: msg.payload.credential.cesr }, expiry: expiry };

// const authorizeResult = {
// type: SwCsMsgType.REPLY,
// payload: {
// "signature": "indexed=\"?0\";signify=\"0BCUmN5EAYdT3okIb8yEIG9sVepXwlQQSqcuZd7wQYEFDzVNkIPwYUX679lYNHS1YCdSPATJGTHfdTLTHjZoPO8F\"",
// "signature-input": "signify=(\"@method\" \"@path\" \"signify-resource\" \"signify-timestamp\");created=1727719612;keyid=\"BJF5YenWeqMPGU2iL2hsn9D8PSGXRDXSZbM7Znvh1XvI\";alg=\"ed25519\"",
// "signify-resource": "EO0KSgpgvjNFoc8KoFfb0qgjbrVieMVbBhNit7ZtEue3",
// "signify-timestamp": "2024-10-01T18:06:52.193000+00:00"
// },
// requestId: msg.requestId,
// };
// console.log("TMP SW from App: SignDataResult?? authorizeResult", authorizeResult);
// csTabPort.postMessage(authorizeResult);
}
catch (error) {
console.error("SW handleSignRequest: error invoking useActionPopup: ", error);
Expand Down Expand Up @@ -395,7 +380,8 @@ async function handleMessageFromApp(message: any, appPort: chrome.runtime.Port,
const authorizeResult = {
type: SwCsMsgType.REPLY,
requestId: message.requestId,
payload: authorizeResultCredential
payload: authorizeResultCredential,
rurl: "" // TODO rurl should not be fixed
};
console.log("SW from App: authorizeResult", authorizeResult);
cSConnection.port.postMessage(authorizeResult);
Expand Down
Loading

0 comments on commit f23ab97

Please sign in to comment.