passkey.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. export function base64UrlToBuffer(base64url) {
  2. if (!base64url) return new ArrayBuffer(0);
  3. let padding = '='.repeat((4 - (base64url.length % 4)) % 4);
  4. const base64 = (base64url + padding).replace(/-/g, '+').replace(/_/g, '/');
  5. const rawData = window.atob(base64);
  6. const buffer = new ArrayBuffer(rawData.length);
  7. const uintArray = new Uint8Array(buffer);
  8. for (let i = 0; i < rawData.length; i += 1) {
  9. uintArray[i] = rawData.charCodeAt(i);
  10. }
  11. return buffer;
  12. }
  13. export function bufferToBase64Url(buffer) {
  14. if (!buffer) return '';
  15. const uintArray = new Uint8Array(buffer);
  16. let binary = '';
  17. for (let i = 0; i < uintArray.byteLength; i += 1) {
  18. binary += String.fromCharCode(uintArray[i]);
  19. }
  20. return window
  21. .btoa(binary)
  22. .replace(/\+/g, '-')
  23. .replace(/\//g, '_')
  24. .replace(/=+$/g, '');
  25. }
  26. export function prepareCredentialCreationOptions(payload) {
  27. const options = payload?.publicKey || payload?.PublicKey || payload?.response || payload?.Response;
  28. if (!options) {
  29. throw new Error('无法从服务端响应中解析 Passkey 注册参数');
  30. }
  31. const publicKey = {
  32. ...options,
  33. challenge: base64UrlToBuffer(options.challenge),
  34. user: {
  35. ...options.user,
  36. id: base64UrlToBuffer(options.user?.id),
  37. },
  38. };
  39. if (Array.isArray(options.excludeCredentials)) {
  40. publicKey.excludeCredentials = options.excludeCredentials.map((item) => ({
  41. ...item,
  42. id: base64UrlToBuffer(item.id),
  43. }));
  44. }
  45. if (Array.isArray(options.attestationFormats) && options.attestationFormats.length === 0) {
  46. delete publicKey.attestationFormats;
  47. }
  48. return publicKey;
  49. }
  50. export function prepareCredentialRequestOptions(payload) {
  51. const options = payload?.publicKey || payload?.PublicKey || payload?.response || payload?.Response;
  52. if (!options) {
  53. throw new Error('无法从服务端响应中解析 Passkey 登录参数');
  54. }
  55. const publicKey = {
  56. ...options,
  57. challenge: base64UrlToBuffer(options.challenge),
  58. };
  59. if (Array.isArray(options.allowCredentials)) {
  60. publicKey.allowCredentials = options.allowCredentials.map((item) => ({
  61. ...item,
  62. id: base64UrlToBuffer(item.id),
  63. }));
  64. }
  65. return publicKey;
  66. }
  67. export function buildRegistrationResult(credential) {
  68. if (!credential) return null;
  69. const { response } = credential;
  70. const transports = typeof response.getTransports === 'function' ? response.getTransports() : undefined;
  71. return {
  72. id: credential.id,
  73. rawId: bufferToBase64Url(credential.rawId),
  74. type: credential.type,
  75. authenticatorAttachment: credential.authenticatorAttachment,
  76. response: {
  77. attestationObject: bufferToBase64Url(response.attestationObject),
  78. clientDataJSON: bufferToBase64Url(response.clientDataJSON),
  79. transports,
  80. },
  81. clientExtensionResults: credential.getClientExtensionResults?.() ?? {},
  82. };
  83. }
  84. export function buildAssertionResult(assertion) {
  85. if (!assertion) return null;
  86. const { response } = assertion;
  87. return {
  88. id: assertion.id,
  89. rawId: bufferToBase64Url(assertion.rawId),
  90. type: assertion.type,
  91. authenticatorAttachment: assertion.authenticatorAttachment,
  92. response: {
  93. authenticatorData: bufferToBase64Url(response.authenticatorData),
  94. clientDataJSON: bufferToBase64Url(response.clientDataJSON),
  95. signature: bufferToBase64Url(response.signature),
  96. userHandle: response.userHandle ? bufferToBase64Url(response.userHandle) : null,
  97. },
  98. clientExtensionResults: assertion.getClientExtensionResults?.() ?? {},
  99. };
  100. }
  101. export async function isPasskeySupported() {
  102. if (typeof window === 'undefined' || !window.PublicKeyCredential) {
  103. return false;
  104. }
  105. if (typeof window.PublicKeyCredential.isConditionalMediationAvailable === 'function') {
  106. try {
  107. const available = await window.PublicKeyCredential.isConditionalMediationAvailable();
  108. if (available) return true;
  109. } catch (error) {
  110. // ignore
  111. }
  112. }
  113. if (typeof window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable === 'function') {
  114. try {
  115. return await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
  116. } catch (error) {
  117. return false;
  118. }
  119. }
  120. return true;
  121. }