Browse Source

change all copied contact URLs to contact-import, and handle multiples & singles separately

master
Trent Larson 1 week ago
parent
commit
6514f52b92
  1. 13
      src/libs/crypto/index.ts
  2. 20
      src/libs/endorserServer.ts
  3. 45
      src/views/ContactImportView.vue
  4. 19
      src/views/ContactQRScanShowView.vue
  5. 81
      src/views/ContactsView.vue

13
src/libs/crypto/index.ts

@ -11,7 +11,6 @@ import {
CONTACT_IMPORT_ONE_URL_PATH_TIME_SAFARI,
} from "@/libs/endorserServer";
import { DEFAULT_DID_PROVIDER_NAME } from "../veramo/setup";
import { decodeEndorserJwt } from "@/libs/crypto/vc";
export const DEFAULT_ROOT_DERIVATION_PATH = "m/84737769'/0'/0'/0'";
@ -103,11 +102,9 @@ export const accessToken = async (did?: string) => {
};
/**
@return payload of JWT pulled out of any recognized URL path (if any) and decoded:
{ iat: number, iss: string (DID), own: { name, publicEncKey (base64-encoded key) } }
... or an array of such as { contacts: [ contact, ... ] }
@return payload of JWT pulled out of any recognized URL path (if any)
*/
export const getContactPayloadFromJwtUrl = (jwtUrlText: string) => {
export const getContactJwtFromJwtUrl = (jwtUrlText: string) => {
let jwtText = jwtUrlText;
const appImportConfirmUrlLoc = jwtText.indexOf(
CONTACT_IMPORT_CONFIRM_URL_PATH_TIME_SAFARI,
@ -132,11 +129,7 @@ export const getContactPayloadFromJwtUrl = (jwtUrlText: string) => {
endorserUrlPathLoc + CONTACT_URL_PATH_ENDORSER_CH_OLD.length,
);
}
// JWT format: { header, payload, signature, data }
const jwt = decodeEndorserJwt(jwtText);
return jwt.payload;
return jwtText;
};
export const nextDerivationPath = (origDerivPath: string) => {

20
src/libs/endorserServer.ts

@ -294,7 +294,12 @@ export interface ErrorResult extends ResultWithType {
export type CreateAndSubmitClaimResult = SuccessResult | ErrorResult;
/**
* This is similar to Contact but it grew up in different logic paths.
* We may want to change this to be a Contact.
*/
export interface UserInfo {
did: string;
name: string;
publicEncKey: string;
registered: boolean;
@ -609,7 +614,17 @@ const planCache: LRUCache<string, PlanSummaryRecord> = new LRUCache({
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function errorStringForLog(error: any) {
let fullError = "" + error + " - JSON: " + JSON.stringify(error);
let stringifiedError = "" + error;
try {
stringifiedError = JSON.stringify(error);
} catch (e) {
// can happen with Dexie, eg:
// TypeError: Converting circular structure to JSON
// --> starting at object with constructor 'DexieError2'
// | property '_promise' -> object with constructor 'DexiePromise'
// --- property '_value' closes the circle
}
let fullError = "" + error + " - JSON: " + stringifiedError;
const errorResponseText = JSON.stringify(error.response);
// for some reason, error.response is not included in stringify result (eg. for 400 errors on invite redemptions)
if (!R.empty(errorResponseText) && !fullError.includes(errorResponseText)) {
@ -1112,6 +1127,7 @@ export async function generateEndorserJwtUrlForAccount(
iat: Date.now(),
iss: account.did,
own: {
did: account.did,
name: name ?? "",
publicEncKey,
registered: !!isRegistered,
@ -1137,7 +1153,7 @@ export async function generateEndorserJwtUrlForAccount(
const vcJwt = await createEndorserJwtForDid(account.did, contactInfo);
const viewPrefix = APP_SERVER + CONTACT_IMPORT_ONE_URL_PATH_TIME_SAFARI;
const viewPrefix = APP_SERVER + CONTACT_IMPORT_CONFIRM_URL_PATH_TIME_SAFARI;
return viewPrefix + vcJwt;
}

45
src/views/ContactImportView.vue

@ -122,7 +122,6 @@
</template>
<script lang="ts">
import { JWTPayload, JWTVerified } from "did-jwt";
import * as R from "ramda";
import { Component, Vue } from "vue-facing-decorator";
import { RouteLocationNormalizedLoaded, Router } from "vue-router";
@ -138,13 +137,13 @@ import {
} from "@/db/index";
import { Contact, ContactMethod } from "@/db/tables/contacts";
import * as libsUtil from "@/libs/util";
import { decodeAndVerifyJwt } from "@/libs/crypto/vc";
import { decodeEndorserJwt } from "@/libs/crypto/vc";
import {
capitalizeAndInsertSpacesBeforeCaps,
errorStringForLog,
setVisibilityUtil,
} from "@/libs/endorserServer";
import { getContactPayloadFromJwtUrl } from "@/libs/crypto";
import { getContactJwtFromJwtUrl } from "@/libs/crypto";
@Component({
components: { EntityIcon, OfferDialog, QuickNav },
@ -182,7 +181,7 @@ export default class ContactImportView extends Vue {
this.activeDid = settings.activeDid || "";
this.apiServer = settings.apiServer || "";
// look for any imported contacts from the query parameter
// look for any imported contact array from the query parameter
const importedContacts = (this.$route as RouteLocationNormalizedLoaded)
.query["contacts"] as string;
if (importedContacts) {
@ -194,10 +193,36 @@ export default class ContactImportView extends Vue {
/\/contact-import\/(ey.+)$/,
)?.[1];
if (jwt) {
// decode the JWT
// would prefer to validate but we've got an error with JWTs on QR codes generated in the future
// eslint-disable-next-line prettier/prettier
const parsedJwt: Omit<JWTVerified, "didResolutionResult" | "signer" | "jwt"> = await decodeAndVerifyJwt(jwt);
await this.setContactsSelected(parsedJwt.payload.contacts as Contact[]);
// const parsedJwt: Omit<JWTVerified, "didResolutionResult" | "signer" | "jwt"> = await decodeAndVerifyJwt(jwt);
// decode the JWT
const parsedJwt = decodeEndorserJwt(jwt);
const contacts: Array<Contact> =
parsedJwt.payload.contacts || // someday this will be the only payload sent to this page
(Array.isArray(parsedJwt.payload) ? parsedJwt.payload : undefined);
if (!contacts && parsedJwt.payload.own) {
// handle this single-contact JWT in the contacts page, better suited to single additions
(this.$router as Router).push({
name: "contacts",
query: { contactJwt: jwt },
});
}
if (contacts) {
await this.setContactsSelected(contacts);
} else {
// no contacts found so default message should be OK
}
}
if (
this.contactsImporting.length === 1 &&
R.isEmpty(this.contactsExisting)
) {
// if there is only one contact and it's new, then we will automatically import it
this.contactsSelected[0] = true;
this.importContacts(); // ... which routes to the contacts list
}
}
@ -269,7 +294,10 @@ export default class ContactImportView extends Vue {
try {
// (For another approach used with invites, see InviteOneAcceptView.processInvite)
const payload: JWTPayload = getContactPayloadFromJwtUrl(jwtInput);
const jwt: string = getContactJwtFromJwtUrl(jwtInput);
// JWT format: { header, payload, signature, data }
const payload = decodeEndorserJwt(jwt).payload;
if (Array.isArray(payload.contacts)) {
await this.setContactsSelected(payload.contacts);
} else {
@ -304,6 +332,7 @@ export default class ContactImportView extends Vue {
updatedCount++;
} else {
// without explicit clone on the Proxy, we get: DataCloneError: Failed to execute 'add' on 'IDBObjectStore': #<Object> could not be cloned.
// DataError: Failed to execute 'add' on 'IDBObjectStore': Evaluating the object store's key path yielded a value that is not a valid key.
await db.contacts.add(R.clone(contact));
importedCount++;
}

19
src/views/ContactQRScanShowView.vue

@ -93,7 +93,6 @@ import { AxiosError } from "axios";
import QRCodeVue3 from "qr-code-generator-vue3";
import { Component, Vue } from "vue-facing-decorator";
import { QrcodeStream } from "vue-qrcode-reader";
import { Router } from "vue-router";
import { useClipboard } from "@vueuse/core";
import QuickNav from "@/components/QuickNav.vue";
@ -102,14 +101,14 @@ import { NotificationIface } from "@/constants/app";
import { db, retrieveSettingsForActiveAccount } from "@/db/index";
import { Contact } from "@/db/tables/contacts";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import { getContactPayloadFromJwtUrl } from "@/libs/crypto";
import { getContactJwtFromJwtUrl } from "@/libs/crypto";
import {
generateEndorserJwtUrlForAccount,
isDid,
register,
setVisibilityUtil,
} from "@/libs/endorserServer";
import { ETHR_DID_PREFIX } from "@/libs/crypto/vc";
import { decodeEndorserJwt, ETHR_DID_PREFIX } from "@/libs/crypto/vc";
import { retrieveAccountMetadata } from "@/libs/util";
@Component({
@ -180,8 +179,8 @@ export default class ContactQRScanShow extends Vue {
if (url) {
let newContact: Contact;
try {
const payload = getContactPayloadFromJwtUrl(url);
if (!payload) {
const jwt = getContactJwtFromJwtUrl(url);
if (!jwt) {
this.$notify(
{
group: "alert",
@ -193,15 +192,9 @@ export default class ContactQRScanShow extends Vue {
);
return;
}
if (Array.isArray(payload.contacts)) {
// reroute to the ContactsImport
(this.$router as Router).push({
path: "/contact-import/" + url.substring(url.lastIndexOf("/") + 1),
});
return;
}
const { payload } = decodeEndorserJwt(jwt);
newContact = {
did: payload.iss as string,
did: payload.own.did || payload.iss, // ".own.did" is reliable as of v 0.3.49
name: payload.own.name,
nextPubKeyHashB64: payload.own.nextPublicEncKeyHash,
profileImageUrl: payload.own.profileImageUrl,

81
src/views/ContactsView.vue

@ -344,7 +344,7 @@ import {
updateDefaultSettings,
} from "@/db/index";
import { Contact } from "@/db/tables/contacts";
import { getContactPayloadFromJwtUrl } from "@/libs/crypto";
import { getContactJwtFromJwtUrl } from "@/libs/crypto";
import { decodeEndorserJwt } from "@/libs/crypto/vc";
import {
CONTACT_CSV_HEADER,
@ -416,6 +416,11 @@ export default class ContactsView extends Vue {
this.apiServer = settings.apiServer || "";
this.isRegistered = !!settings.isRegistered;
// if these detect a query parameter, they can and then redirect to this URL without a query parameter
// to avoid problems when they reload or they go forward & back and it tries to reprocess
await this.processContactJwt();
await this.processInviteJwt();
this.showGiveNumbers = !!settings.showContactGivesInline;
this.hideRegisterPromptOnNewContact =
!!settings.hideRegisterPromptOnNewContact;
@ -430,11 +435,13 @@ export default class ContactsView extends Vue {
this.contacts = baseContacts.sort((a, b) =>
(a.name || "").localeCompare(b.name || ""),
);
}
private async processContactJwt() {
// handle a contact sent via URL
//
// Prefer use of /contact-import/:jwt with a JWT that has an array of contacts
// unless you want them to import a single contact without confirmation.
// For external links, use /contact-import/:jwt with a JWT that has an array of contacts
// because that will do better error checking for things like missing data on iOS platforms.
const importedContactJwt = (this.$route as RouteLocationNormalizedLoaded)
.query["contactJwt"] as string;
if (importedContactJwt) {
@ -442,21 +449,25 @@ export default class ContactsView extends Vue {
const { payload } = decodeEndorserJwt(importedContactJwt);
const userInfo = payload["own"] as UserInfo;
const newContact = {
did: payload["iss"],
did: userInfo.did || payload["iss"], // ".did" is reliable as of v 0.3.49
name: userInfo.name,
nextPubKeyHashB64: userInfo.nextPublicEncKeyHash,
profileImageUrl: userInfo.profileImageUrl,
publicKeyBase64: userInfo.publicEncKey,
registered: userInfo.registered,
} as Contact;
this.addContact(newContact);
await this.addContact(newContact);
// if we're here, they haven't redirected anywhere, so we'll redirect here without a query parameter
(this.$router as Router).push({ path: "/contacts" });
}
}
private async processInviteJwt() {
// handle an invite JWT sent via URL
const importedInviteJwt = (this.$route as RouteLocationNormalizedLoaded)
.query["inviteJwt"] as string;
if (importedInviteJwt === "") {
// this happens when a platform (usually iOS) doesn't include anything after the "=" in a shared link.
// this happens when a platform (eg iOS) doesn't include anything after the "=" in a shared link.
this.$notify(
{
group: "alert",
@ -555,6 +566,8 @@ export default class ContactsView extends Vue {
5000,
);
}
// if we're here, they haven't redirected anywhere, so we'll redirect here without a query parameter
(this.$router as Router).push({ path: "/contacts" });
}
}
@ -717,12 +730,30 @@ export default class ContactsView extends Vue {
return;
}
if (contactInput.includes(CONTACT_IMPORT_CONFIRM_URL_PATH_TIME_SAFARI)) {
const jwt = getContactJwtFromJwtUrl(contactInput);
(this.$router as Router).push({
path: "/contact-import/" + jwt,
});
return;
}
if (
contactInput.includes(CONTACT_IMPORT_CONFIRM_URL_PATH_TIME_SAFARI) ||
contactInput.includes(CONTACT_IMPORT_ONE_URL_PATH_TIME_SAFARI) ||
contactInput.includes(CONTACT_URL_PATH_ENDORSER_CH_OLD)
) {
await this.addContactFromScan(contactInput);
const jwt = getContactJwtFromJwtUrl(contactInput);
const { payload } = decodeEndorserJwt(jwt);
const userInfo = payload["own"] as UserInfo;
const newContact = {
did: userInfo.did || payload["iss"], // "did" is reliable as of v 0.3.49
name: userInfo.name,
nextPubKeyHashB64: userInfo.nextPublicEncKeyHash,
profileImageUrl: userInfo.profileImageUrl,
publicKeyBase64: userInfo.publicEncKey,
registered: userInfo.registered,
} as Contact;
await this.addContact(newContact);
return;
}
@ -870,38 +901,6 @@ export default class ContactsView extends Vue {
return db.contacts.add(newContact);
}
private async addContactFromScan(url: string): Promise<void> {
const payload = getContactPayloadFromJwtUrl(url);
if (!payload) {
this.$notify(
{
group: "alert",
type: "danger",
title: "No Contact Info",
text: "The contact info could not be parsed.",
},
3000,
);
return;
} else {
if (Array.isArray(payload.contacts)) {
// reroute to the ContactsImport
(this.$router as Router).push({
path: "/contact-import/" + url.substring(url.lastIndexOf("/") + 1),
});
return;
}
return this.addContact({
did: payload.iss,
name: payload.own.name,
nextPubKeyHashB64: payload.own.nextPublicEncKeyHash,
profileImageUrl: payload.own.profileImageUrl,
publicKeyBase64: payload.own.publicEncKey,
registered: payload.own.registered,
} as Contact);
}
}
private async addContact(newContact: Contact) {
if (!newContact.did) {
this.danger("Cannot add a contact without a DID.", "Incomplete Contact");
@ -961,7 +960,7 @@ export default class ContactsView extends Vue {
},
-1,
);
}, 500);
}, 1000);
}
}
this.$notify(

Loading…
Cancel
Save