-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathauth.ts
More file actions
149 lines (131 loc) · 4.01 KB
/
auth.ts
File metadata and controls
149 lines (131 loc) · 4.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import type { SignIdentity, Signature } from "@dfinity/agent";
import {
Delegation,
DelegationChain,
DelegationIdentity,
SignedDelegation,
} from "@dfinity/identity";
import { Principal } from "@dfinity/principal";
// The type of response from II as per the spec
interface AuthResponseSuccess {
kind: "authorize-client-success";
delegations: {
delegation: {
pubkey: Uint8Array;
expiration: bigint;
targets?: Principal[];
};
signature: Uint8Array;
}[];
userPublicKey: Uint8Array;
authnMethod: "pin" | "passkey" | "recovery";
}
// Perform a sign in to II using parameters set in this app
export const authWithII = async ({
url: url_,
maxTimeToLive,
allowPinAuthentication,
derivationOrigin,
sessionIdentity,
autoSelectionPrincipal,
}: {
url: string;
maxTimeToLive?: bigint;
allowPinAuthentication?: boolean;
derivationOrigin?: string;
autoSelectionPrincipal?: string;
sessionIdentity: SignIdentity;
}): Promise<{ identity: DelegationIdentity; authnMethod: string }> => {
// Figure out the II URL to use
const iiUrl = new URL(url_);
iiUrl.hash = "#authorize";
// Open an II window and kickstart the flow
const win = window.open(iiUrl, "ii-window");
if (win === null) {
throw new Error(`Could not open window for '${iiUrl}'`);
}
// Wait for II to say it's ready
const evnt = await new Promise<MessageEvent>((resolve) => {
const readyHandler = (e: MessageEvent) => {
if (e.origin !== iiUrl.origin) {
// Ignore messages from other origins (e.g. from a metamask extension)
return;
}
window.removeEventListener("message", readyHandler);
resolve(e);
};
window.addEventListener("message", readyHandler);
});
if (evnt.data.kind !== "authorize-ready") {
throw new Error("Bad message from II window: " + JSON.stringify(evnt));
}
// Send the request to II
const sessionPublicKey: Uint8Array = new Uint8Array(
sessionIdentity.getPublicKey().toDer(),
);
const request = {
kind: "authorize-client",
sessionPublicKey,
maxTimeToLive,
derivationOrigin,
allowPinAuthentication,
autoSelectionPrincipal,
};
win.postMessage(request, iiUrl.origin);
// Wait for the II response and update the local state
const response = await new Promise<MessageEvent>((resolve) => {
const responseHandler = (e: MessageEvent) => {
if (e.origin !== iiUrl.origin) {
// Ignore messages from other origins (e.g. from a metamask extension)
return;
}
window.removeEventListener("message", responseHandler);
win.close();
resolve(e);
};
window.addEventListener("message", responseHandler);
});
const message = response.data;
if (message.kind !== "authorize-client-success") {
throw new Error("Bad reply: " + JSON.stringify(message));
}
const identity = identityFromResponse({
response: message as AuthResponseSuccess,
sessionIdentity,
});
return { identity, authnMethod: message.authnMethod };
};
// Read delegations the delegations from the response
const identityFromResponse = ({
sessionIdentity,
response,
}: {
sessionIdentity: SignIdentity;
response: AuthResponseSuccess;
}): DelegationIdentity => {
const delegations = response.delegations.map(extractDelegation);
const delegationChain = DelegationChain.fromDelegations(
delegations,
response.userPublicKey.buffer,
);
const identity = DelegationIdentity.fromDelegation(
sessionIdentity,
delegationChain,
);
return identity;
};
// Infer the type of an array's elements
type ElementOf<Arr> = Arr extends readonly (infer ElementOf)[]
? ElementOf
: "argument is not an array";
export const extractDelegation = (
signedDelegation: ElementOf<AuthResponseSuccess["delegations"]>,
): SignedDelegation => ({
delegation: new Delegation(
signedDelegation.delegation.pubkey,
signedDelegation.delegation.expiration,
signedDelegation.delegation.targets,
),
signature: signedDelegation.signature
.buffer as Signature /* brand type for agent-js */,
});