Skip to content

Commit

Permalink
feat: add session
Browse files Browse the repository at this point in the history
  • Loading branch information
HunnySajid committed Sep 10, 2024
1 parent 037364f commit b533ceb
Show file tree
Hide file tree
Showing 6 changed files with 158 additions and 112 deletions.
2 changes: 1 addition & 1 deletion src/components/ui/radio/radio.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ interface IRadio {
const StyledRadio = styled.input`
width: 16px;
height: 16px;
accent-color: #61783e;
accent-color: ${({ theme }) => theme?.colors?.primary};
`;

const StyledRadioLabel = styled.label`
Expand Down
5 changes: 2 additions & 3 deletions src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,10 @@ export interface ISession {
origin: string;
aidName: string;
signinId: string;
maxReq?: number;
// maxReq?: number;
currentReq?: number;
}

export interface ISessionConfig {
sessionTime: number;
maxReq: number;
sessionOneTime: boolean;
}
40 changes: 20 additions & 20 deletions src/pages/background/services/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,17 @@ const Session = () => {
if (session.origin !== origin) {
throw new Error("Session origin mismatch");
}
if (
session?.maxReq &&
session?.currentReq !== undefined &&
session?.currentReq !== null &&
session?.currentReq >= 0
) {
if (session?.currentReq >= session.maxReq) {
await remove(tabId);
throw new Error("Session max request limit reached");
}
}
// if (
// session?.maxReq &&
// session?.currentReq !== undefined &&
// session?.currentReq !== null &&
// session?.currentReq >= 0
// ) {
// if (session?.currentReq >= session.maxReq) {
// await remove(tabId);
// throw new Error("Session max request limit reached");
// }
// }

if (session.expiry < new Date().getTime()) {
await remove(tabId);
Expand All @@ -50,29 +50,29 @@ const Session = () => {
tabId,
origin,
aidName,
config,
// config,
}: Pick<
ISession,
"origin" | "aidName" | "tabId" | "signinId"
>): Promise<ISession> => {
const sessions = await getSessionsObject();
const expiry = new Date();
// expiry.setSeconds(expiry.getSeconds() + 50);
const sessionTime = config?.sessionTime
? Math.min(config.sessionTime, SESSION_ENUMS.EXPIRY_IN_MINS)
: SESSION_ENUMS.EXPIRY_IN_MINS;
expiry.setMinutes(expiry.getMinutes() + sessionTime);
// const sessionTime = config?.sessionTime
// ? Math.min(config.sessionTime, SESSION_ENUMS.EXPIRY_IN_MINS)
// : SESSION_ENUMS.EXPIRY_IN_MINS;
expiry.setMinutes(expiry.getMinutes() + SESSION_ENUMS.EXPIRY_IN_MINS);

const sessionMaxRequests = config?.maxReq
? Math.min(SESSION_ENUMS.MAX_REQUESTS, config?.maxReq)
: undefined;
// const sessionMaxRequests = config?.maxReq
// ? Math.min(SESSION_ENUMS.MAX_REQUESTS, config?.maxReq)
// : undefined;
sessions[tabId] = {
origin,
aidName,
tabId,
expiry: expiry.getTime(),
signinId,
maxReq: sessionMaxRequests,
// maxReq: sessionMaxRequests,
currentReq: 0,
};
await browserStorageService.setValue(SESSION_ENUMS.SESSIONS, sessions);
Expand Down
161 changes: 102 additions & 59 deletions src/pages/background/services/signify.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,28 @@
import browser from "webextension-polyfill";
import * as signinResource from "@pages/background/resource/signin";
import { SignifyClient, Tier, ready, randomPasscode, Saider, IssueCredentialResult, CredentialData } from "signify-ts";
import {
SignifyClient,
Tier,
ready,
randomPasscode,
Saider,
IssueCredentialResult,
CredentialData,
} from "signify-ts";
import { sendMessage } from "@src/shared/browser/runtime-utils";
import { sendMessageTab, getCurrentTab } from "@src/shared/browser/tabs-utils";
import { userService } from "@pages/background/services/user";
import { configService } from "@pages/background/services/config";
import { sessionService } from "@pages/background/services/session";
import { IIdentifier, ISignin, ISessionConfig } from "@config/types";
import { SW_EVENTS } from "@config/event-types";
import { formatAsCredentialEdgeOrRuleObject, getSchemaFieldOfEdge, parseSchemaEdgeOrRuleSection, setNodeValueInEdge, waitOperation } from "@src/shared/signify-utils";
import {
formatAsCredentialEdgeOrRuleObject,
getSchemaFieldOfEdge,
parseSchemaEdgeOrRuleSection,
setNodeValueInEdge,
waitOperation,
} from "@src/shared/signify-utils";

const PASSCODE_TIMEOUT = 5;

Expand Down Expand Up @@ -140,7 +154,10 @@ const Signify = () => {
};

// credential identifier => credential.sad.d
const getCredential = async (credentialIdentifier: string, includeCESR: boolean = false) => {
const getCredential = async (
credentialIdentifier: string,
includeCESR: boolean = false
) => {
validateClient();
return await _client?.credentials().get(credentialIdentifier, includeCESR);
};
Expand Down Expand Up @@ -182,24 +199,35 @@ const Signify = () => {
const response = {
credential: credentialResp,
identifier: signin?.identifier,
// autoSignin: signin?.autoSignin,
};

const sessionInfo = await sessionService.create({
tabId,
origin,
aidName: aidName!,
signinId: signin.id,
config
});
if (sessionInfo?.expiry) {
response.expiry = sessionInfo.expiry;
if (config?.sessionOneTime) {
const sreq = await _client?.createSignedRequest(aidName!, origin, {});
let jsonHeaders: { [key: string]: string } = {};
if (sreq?.headers) {
for (const pair of sreq.headers.entries()) {
jsonHeaders[pair[0]] = pair[1];
}
}
response.headers = jsonHeaders;
} else {
const sessionInfo = await sessionService.create({
tabId,
origin,
aidName: aidName!,
signinId: signin.id,
config,
});
if (sessionInfo?.expiry) {
response.expiry = sessionInfo.expiry;
}

await sendMessageTab(tabId, {
type: "tab",
subtype: "session-info",
data: response,
});
}
await sendMessageTab(tabId, {
type: "tab",
subtype: "session-info",
data: response,
});

resetTimeoutAlarm();
return response;
Expand Down Expand Up @@ -320,23 +348,23 @@ const Signify = () => {
};

/**
* Create a data attestation credential, it is an untargeted ACDC credential i.e. there is no issuee.
*
* @param origin - origin url from where request is being made -- required
* @param credData - credential data object containing the credential attributes -- required
* @param schemaSaid - SAID of the schema -- required
* @param signin - signin object containing identifier or credential -- required
* @returns Promise<Request> - returns a signed headers request object
*/
* Create a data attestation credential, it is an untargeted ACDC credential i.e. there is no issuee.
*
* @param origin - origin url from where request is being made -- required
* @param credData - credential data object containing the credential attributes -- required
* @param schemaSaid - SAID of the schema -- required
* @param signin - signin object containing identifier or credential -- required
* @returns Promise<Request> - returns a signed headers request object
*/
const createAttestationCredential = async ({
origin,
credData,
schemaSaid,
tabId
tabId,
}: {
origin: string;
credData: any,
schemaSaid: string,
credData: any;
schemaSaid: string;
tabId: number;
}): Promise<any> => {
// in case the client is not connected, try to connect
Expand All @@ -347,63 +375,78 @@ const Signify = () => {
}

const session = await sessionService.get({ tabId, origin });
let { aid, registry, rules, edge } = await getCreateCredentialPrerequisites(session.aidName, schemaSaid);
let { aid, registry, rules, edge } = await getCreateCredentialPrerequisites(
session?.aidName!,
schemaSaid
);
if (isGroupAid(aid) === true) {
throw new Error(`Attestation credential issuance by multisig identifier ${session.aidName} is not supported yet!`);
throw new Error(
`Attestation credential issuance by multisig identifier ${session.aidName} is not supported yet!`
);
}

let credArgs: CredentialData = {
i: aid.prefix,
ri: registry.regk,
s: schemaSaid,
a: credData,
r: rules
? Object.keys(rules).length > 0
? Saider.saidify({ d: '', ...rules })[1]
? Saider.saidify({ d: "", ...rules })[1]
: undefined
: undefined,
e: edge
? Object.keys(edge).length > 0
? Saider.saidify({ d: '', ...edge })[1]
? Saider.saidify({ d: "", ...edge })[1]
: undefined
: undefined
}
: undefined,
};
console.log("create credential args: ", credArgs);
let credResult = await createCredential(session.aidName, credArgs)
let credResult = await createCredential(session.aidName, credArgs);
if (credResult && _client) {
await waitOperation(_client, credResult.op)
await waitOperation(_client, credResult.op);
}

return credResult;
};

const getCreateCredentialPrerequisites = async (aidName: string, schemaSaid: string):
Promise<{ aid: any | undefined; schema: any; registry: any, rules: any, edge: any }> => {
const getCreateCredentialPrerequisites = async (
aidName: string,
schemaSaid: string
): Promise<{
aid: any | undefined;
schema: any;
registry: any;
rules: any;
edge: any;
}> => {
const aid = await _client?.identifiers().get(aidName);

let registries = await _client?.registries().list(aidName)
let registries = await _client?.registries().list(aidName);
if (registries == undefined || registries.length === 0) {
throw new Error(`No credential registries found for the AID ${aidName}`);
}

let schema = await _client?.schemas().get(schemaSaid)
if (!schema || schema?.title == '404 Not Found') {
let schema = await _client?.schemas().get(schemaSaid);
if (!schema || schema?.title == "404 Not Found") {
throw new Error(`Schema not found!`);
}

const edgeObject = parseSchemaEdgeOrRuleSection(schema.properties?.e)
let edge = formatAsCredentialEdgeOrRuleObject(edgeObject)
let edgeSchema = getSchemaFieldOfEdge(edge)
const edgeObject = parseSchemaEdgeOrRuleSection(schema.properties?.e);
let edge = formatAsCredentialEdgeOrRuleObject(edgeObject);
let edgeSchema = getSchemaFieldOfEdge(edge);
if (edge && edgeSchema) {
let filter = { '-s': edgeSchema, '-a-i': aid?.prefix }
let creds = await _client?.credentials().list({ filter: filter, limit: 50 })
let filter = { "-s": edgeSchema, "-a-i": aid?.prefix };
let creds = await _client
?.credentials()
.list({ filter: filter, limit: 50 });
if (creds && creds?.length > 0) {
edge = setNodeValueInEdge(edge, creds[0]?.sad.d)
edge = setNodeValueInEdge(edge, creds[0]?.sad.d);
}
}

let parsedRules = parseSchemaEdgeOrRuleSection(schema.properties?.r)
let rules = formatAsCredentialEdgeOrRuleObject(parsedRules)
let parsedRules = parseSchemaEdgeOrRuleSection(schema.properties?.r);
let rules = formatAsCredentialEdgeOrRuleObject(parsedRules);

return { aid, schema, registry: registries[0], rules, edge };
};
Expand All @@ -424,17 +467,17 @@ const Signify = () => {
name: string,
args: CredentialData
): Promise<IssueCredentialResult | undefined> => {
const result = await _client?.credentials().issue(name, args)
return result
}
const result = await _client?.credentials().issue(name, args);
return result;
};

const isGroupAid = (aid: any): boolean => {
return (
aid.hasOwnProperty('group') &&
typeof aid.group === 'object' &&
aid.hasOwnProperty("group") &&
typeof aid.group === "object" &&
aid.group !== null
)
}
);
};

return {
connect,
Expand All @@ -451,7 +494,7 @@ const Signify = () => {
authorizeSelectedSignin,
getSessionInfo,
removeSessionInfo,
createAttestationCredential
createAttestationCredential,
};
};

Expand Down
Loading

0 comments on commit b533ceb

Please sign in to comment.