File size: 4,381 Bytes
4ef3a0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
export function base64UrlToBuffer(base64url) {
  if (!base64url) return new ArrayBuffer(0);
  let padding = '='.repeat((4 - (base64url.length % 4)) % 4);
  const base64 = (base64url + padding).replace(/-/g, '+').replace(/_/g, '/');
  const rawData = window.atob(base64);
  const buffer = new ArrayBuffer(rawData.length);
  const uintArray = new Uint8Array(buffer);
  for (let i = 0; i < rawData.length; i += 1) {
    uintArray[i] = rawData.charCodeAt(i);
  }
  return buffer;
}

export function bufferToBase64Url(buffer) {
  if (!buffer) return '';
  const uintArray = new Uint8Array(buffer);
  let binary = '';
  for (let i = 0; i < uintArray.byteLength; i += 1) {
    binary += String.fromCharCode(uintArray[i]);
  }
  return window
    .btoa(binary)
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/g, '');
}

export function prepareCredentialCreationOptions(payload) {
  const options = payload?.publicKey || payload?.PublicKey || payload?.response || payload?.Response;
  if (!options) {
    throw new Error('无法从服务端响应中解析 Passkey 注册参数');
  }
  const publicKey = {
    ...options,
    challenge: base64UrlToBuffer(options.challenge),
    user: {
      ...options.user,
      id: base64UrlToBuffer(options.user?.id),
    },
  };

  if (Array.isArray(options.excludeCredentials)) {
    publicKey.excludeCredentials = options.excludeCredentials.map((item) => ({
      ...item,
      id: base64UrlToBuffer(item.id),
    }));
  }

  if (Array.isArray(options.attestationFormats) && options.attestationFormats.length === 0) {
    delete publicKey.attestationFormats;
  }

  return publicKey;
}

export function prepareCredentialRequestOptions(payload) {
  const options = payload?.publicKey || payload?.PublicKey || payload?.response || payload?.Response;
  if (!options) {
    throw new Error('无法从服务端响应中解析 Passkey 登录参数');
  }
  const publicKey = {
    ...options,
    challenge: base64UrlToBuffer(options.challenge),
  };

  if (Array.isArray(options.allowCredentials)) {
    publicKey.allowCredentials = options.allowCredentials.map((item) => ({
      ...item,
      id: base64UrlToBuffer(item.id),
    }));
  }

  return publicKey;
}

export function buildRegistrationResult(credential) {
  if (!credential) return null;

  const { response } = credential;
  const transports = typeof response.getTransports === 'function' ? response.getTransports() : undefined;

  return {
    id: credential.id,
    rawId: bufferToBase64Url(credential.rawId),
    type: credential.type,
    authenticatorAttachment: credential.authenticatorAttachment,
    response: {
      attestationObject: bufferToBase64Url(response.attestationObject),
      clientDataJSON: bufferToBase64Url(response.clientDataJSON),
      transports,
    },
    clientExtensionResults: credential.getClientExtensionResults?.() ?? {},
  };
}

export function buildAssertionResult(assertion) {
  if (!assertion) return null;

  const { response } = assertion;

  return {
    id: assertion.id,
    rawId: bufferToBase64Url(assertion.rawId),
    type: assertion.type,
    authenticatorAttachment: assertion.authenticatorAttachment,
    response: {
      authenticatorData: bufferToBase64Url(response.authenticatorData),
      clientDataJSON: bufferToBase64Url(response.clientDataJSON),
      signature: bufferToBase64Url(response.signature),
      userHandle: response.userHandle ? bufferToBase64Url(response.userHandle) : null,
    },
    clientExtensionResults: assertion.getClientExtensionResults?.() ?? {},
  };
}

export async function isPasskeySupported() {
  if (typeof window === 'undefined' || !window.PublicKeyCredential) {
    return false;
  }
  if (typeof window.PublicKeyCredential.isConditionalMediationAvailable === 'function') {
    try {
      const available = await window.PublicKeyCredential.isConditionalMediationAvailable();
      if (available) return true;
    } catch (error) {
      // ignore
    }
  }
  if (typeof window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable === 'function') {
    try {
      return await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
    } catch (error) {
      return false;
    }
  }
  return true;
}