@technomoron/api-server-base 1.1.13 → 2.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.txt +25 -2
  2. package/dist/cjs/api-server-base.cjs +448 -111
  3. package/dist/cjs/api-server-base.d.ts +91 -34
  4. package/dist/cjs/auth-api/auth-module.d.ts +105 -0
  5. package/dist/cjs/auth-api/auth-module.js +1180 -0
  6. package/dist/cjs/auth-api/compat-auth-storage.d.ts +57 -0
  7. package/dist/cjs/auth-api/compat-auth-storage.js +128 -0
  8. package/dist/cjs/auth-api/mem-auth-store.d.ts +68 -0
  9. package/dist/cjs/auth-api/mem-auth-store.js +141 -0
  10. package/dist/cjs/{auth-module.d.ts → auth-api/module.d.ts} +7 -7
  11. package/dist/cjs/{auth-module.cjs → auth-api/module.js} +1 -1
  12. package/dist/cjs/auth-api/sql-auth-store.d.ts +77 -0
  13. package/dist/cjs/auth-api/sql-auth-store.js +172 -0
  14. package/dist/cjs/auth-api/storage.d.ts +38 -0
  15. package/dist/cjs/{auth-storage.cjs → auth-api/storage.js} +17 -7
  16. package/dist/cjs/auth-api/types.d.ts +34 -0
  17. package/dist/cjs/auth-api/types.js +2 -0
  18. package/dist/cjs/index.cjs +41 -7
  19. package/dist/cjs/index.d.ts +29 -5
  20. package/dist/cjs/oauth/base.d.ts +10 -0
  21. package/dist/cjs/oauth/base.js +6 -0
  22. package/dist/cjs/oauth/memory.d.ts +16 -0
  23. package/dist/cjs/oauth/memory.js +99 -0
  24. package/dist/cjs/oauth/models.d.ts +45 -0
  25. package/dist/cjs/oauth/models.js +58 -0
  26. package/dist/cjs/oauth/sequelize.d.ts +68 -0
  27. package/dist/cjs/oauth/sequelize.js +210 -0
  28. package/dist/cjs/oauth/types.d.ts +50 -0
  29. package/dist/cjs/oauth/types.js +3 -0
  30. package/dist/cjs/passkey/base.d.ts +16 -0
  31. package/dist/cjs/passkey/base.js +6 -0
  32. package/dist/cjs/passkey/memory.d.ts +27 -0
  33. package/dist/cjs/passkey/memory.js +86 -0
  34. package/dist/cjs/passkey/models.d.ts +25 -0
  35. package/dist/cjs/passkey/models.js +115 -0
  36. package/dist/cjs/passkey/sequelize.d.ts +55 -0
  37. package/dist/cjs/passkey/sequelize.js +220 -0
  38. package/dist/cjs/passkey/service.d.ts +20 -0
  39. package/dist/cjs/passkey/service.js +356 -0
  40. package/dist/cjs/passkey/types.d.ts +78 -0
  41. package/dist/cjs/passkey/types.js +2 -0
  42. package/dist/cjs/token/base.d.ts +38 -0
  43. package/dist/cjs/token/base.js +114 -0
  44. package/dist/cjs/token/memory.d.ts +19 -0
  45. package/dist/cjs/token/memory.js +149 -0
  46. package/dist/cjs/token/sequelize.d.ts +58 -0
  47. package/dist/cjs/token/sequelize.js +404 -0
  48. package/dist/cjs/token/types.d.ts +27 -0
  49. package/dist/cjs/token/types.js +2 -0
  50. package/dist/cjs/user/base.d.ts +26 -0
  51. package/dist/cjs/user/base.js +45 -0
  52. package/dist/cjs/user/memory.d.ts +35 -0
  53. package/dist/cjs/user/memory.js +173 -0
  54. package/dist/cjs/user/sequelize.d.ts +41 -0
  55. package/dist/cjs/user/sequelize.js +182 -0
  56. package/dist/cjs/user/types.d.ts +11 -0
  57. package/dist/cjs/user/types.js +2 -0
  58. package/dist/esm/api-server-base.d.ts +91 -34
  59. package/dist/esm/api-server-base.js +447 -110
  60. package/dist/esm/auth-api/auth-module.d.ts +105 -0
  61. package/dist/esm/auth-api/auth-module.js +1178 -0
  62. package/dist/esm/auth-api/compat-auth-storage.d.ts +57 -0
  63. package/dist/esm/auth-api/compat-auth-storage.js +124 -0
  64. package/dist/esm/auth-api/mem-auth-store.d.ts +68 -0
  65. package/dist/esm/auth-api/mem-auth-store.js +137 -0
  66. package/dist/esm/{auth-module.d.ts → auth-api/module.d.ts} +7 -7
  67. package/dist/esm/{auth-module.js → auth-api/module.js} +1 -1
  68. package/dist/esm/auth-api/sql-auth-store.d.ts +77 -0
  69. package/dist/esm/auth-api/sql-auth-store.js +168 -0
  70. package/dist/esm/auth-api/storage.d.ts +38 -0
  71. package/dist/esm/{auth-storage.js → auth-api/storage.js} +15 -5
  72. package/dist/esm/auth-api/types.d.ts +34 -0
  73. package/dist/esm/auth-api/types.js +1 -0
  74. package/dist/esm/index.d.ts +29 -5
  75. package/dist/esm/index.js +19 -2
  76. package/dist/esm/oauth/base.d.ts +10 -0
  77. package/dist/esm/oauth/base.js +2 -0
  78. package/dist/esm/oauth/memory.d.ts +16 -0
  79. package/dist/esm/oauth/memory.js +92 -0
  80. package/dist/esm/oauth/models.d.ts +45 -0
  81. package/dist/esm/oauth/models.js +51 -0
  82. package/dist/esm/oauth/sequelize.d.ts +68 -0
  83. package/dist/esm/oauth/sequelize.js +199 -0
  84. package/dist/esm/oauth/types.d.ts +50 -0
  85. package/dist/esm/oauth/types.js +2 -0
  86. package/dist/esm/passkey/base.d.ts +16 -0
  87. package/dist/esm/passkey/base.js +2 -0
  88. package/dist/esm/passkey/memory.d.ts +27 -0
  89. package/dist/esm/passkey/memory.js +82 -0
  90. package/dist/esm/passkey/models.d.ts +25 -0
  91. package/dist/esm/passkey/models.js +108 -0
  92. package/dist/esm/passkey/sequelize.d.ts +55 -0
  93. package/dist/esm/passkey/sequelize.js +216 -0
  94. package/dist/esm/passkey/service.d.ts +20 -0
  95. package/dist/esm/passkey/service.js +319 -0
  96. package/dist/esm/passkey/types.d.ts +78 -0
  97. package/dist/esm/passkey/types.js +1 -0
  98. package/dist/esm/token/base.d.ts +38 -0
  99. package/dist/esm/token/base.js +107 -0
  100. package/dist/esm/token/memory.d.ts +19 -0
  101. package/dist/esm/token/memory.js +145 -0
  102. package/dist/esm/token/sequelize.d.ts +58 -0
  103. package/dist/esm/token/sequelize.js +400 -0
  104. package/dist/esm/token/types.d.ts +27 -0
  105. package/dist/esm/token/types.js +1 -0
  106. package/dist/esm/user/base.d.ts +26 -0
  107. package/dist/esm/user/base.js +38 -0
  108. package/dist/esm/user/memory.d.ts +35 -0
  109. package/dist/esm/user/memory.js +169 -0
  110. package/dist/esm/user/sequelize.d.ts +41 -0
  111. package/dist/esm/user/sequelize.js +176 -0
  112. package/dist/esm/user/types.d.ts +11 -0
  113. package/dist/esm/user/types.js +1 -0
  114. package/package.json +13 -3
  115. package/dist/cjs/auth-storage.d.ts +0 -133
  116. package/dist/esm/auth-storage.d.ts +0 -133
@@ -0,0 +1,220 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SequelizePasskeyStore = void 0;
4
+ const sequelize_1 = require("sequelize");
5
+ const base_js_1 = require("./base.js");
6
+ const DIALECTS_SUPPORTING_UNSIGNED = new Set(['mysql', 'mariadb']);
7
+ function integerIdType(sequelize) {
8
+ return DIALECTS_SUPPORTING_UNSIGNED.has(sequelize.getDialect()) ? sequelize_1.DataTypes.INTEGER.UNSIGNED : sequelize_1.DataTypes.INTEGER;
9
+ }
10
+ function encodeCredentialId(value) {
11
+ return Buffer.isBuffer(value) ? value.toString('base64') : value;
12
+ }
13
+ function normalizeUserId(identifier) {
14
+ if (typeof identifier === 'number' && Number.isFinite(identifier)) {
15
+ return identifier;
16
+ }
17
+ if (typeof identifier === 'string' && /^\d+$/.test(identifier)) {
18
+ return Number(identifier);
19
+ }
20
+ throw new Error(`Unable to normalise user identifier: ${identifier}`);
21
+ }
22
+ class PasskeyCredentialModel extends sequelize_1.Model {
23
+ }
24
+ class PasskeyChallengeModel extends sequelize_1.Model {
25
+ }
26
+ function initPasskeyCredentialModel(sequelize) {
27
+ const idType = integerIdType(sequelize);
28
+ return PasskeyCredentialModel.init({
29
+ credentialId: {
30
+ field: 'credential_id',
31
+ type: sequelize_1.DataTypes.STRING(768),
32
+ primaryKey: true,
33
+ allowNull: false,
34
+ get() {
35
+ const raw = this.getDataValue('credentialId');
36
+ if (!raw) {
37
+ return raw;
38
+ }
39
+ if (Buffer.isBuffer(raw)) {
40
+ return raw;
41
+ }
42
+ return Buffer.from(raw, 'base64');
43
+ },
44
+ set(value) {
45
+ const encoded = typeof value === 'string' ? value : value.toString('base64');
46
+ this.setDataValue('credentialId', encoded);
47
+ }
48
+ },
49
+ userId: {
50
+ field: 'user_id',
51
+ type: idType,
52
+ allowNull: false
53
+ },
54
+ publicKey: {
55
+ field: 'public_key',
56
+ type: sequelize_1.DataTypes.BLOB,
57
+ allowNull: false
58
+ },
59
+ counter: {
60
+ type: sequelize_1.DataTypes.INTEGER,
61
+ allowNull: false,
62
+ defaultValue: 0
63
+ },
64
+ transports: {
65
+ type: sequelize_1.DataTypes.JSON,
66
+ allowNull: true
67
+ },
68
+ backedUp: {
69
+ field: 'backed_up',
70
+ type: sequelize_1.DataTypes.BOOLEAN,
71
+ allowNull: false,
72
+ defaultValue: false
73
+ },
74
+ deviceType: {
75
+ field: 'device_type',
76
+ type: sequelize_1.DataTypes.STRING(32),
77
+ allowNull: false,
78
+ defaultValue: 'multiDevice'
79
+ }
80
+ }, {
81
+ sequelize,
82
+ tableName: 'passkey_credentials',
83
+ timestamps: true,
84
+ underscored: true
85
+ });
86
+ }
87
+ function initPasskeyChallengeModel(sequelize) {
88
+ const idType = integerIdType(sequelize);
89
+ return PasskeyChallengeModel.init({
90
+ challenge: {
91
+ type: sequelize_1.DataTypes.STRING(255),
92
+ primaryKey: true,
93
+ allowNull: false
94
+ },
95
+ action: {
96
+ type: sequelize_1.DataTypes.STRING(16),
97
+ allowNull: false
98
+ },
99
+ userId: {
100
+ field: 'user_id',
101
+ type: idType,
102
+ allowNull: true
103
+ },
104
+ login: {
105
+ type: sequelize_1.DataTypes.STRING(128),
106
+ allowNull: true
107
+ },
108
+ metadata: {
109
+ type: sequelize_1.DataTypes.JSON,
110
+ allowNull: true
111
+ },
112
+ expiresAt: {
113
+ field: 'expires_at',
114
+ type: sequelize_1.DataTypes.DATE,
115
+ allowNull: false
116
+ }
117
+ }, {
118
+ sequelize,
119
+ tableName: 'passkey_challenges',
120
+ timestamps: true,
121
+ underscored: true,
122
+ indexes: [{ fields: ['expires_at'] }, { fields: ['user_id'] }]
123
+ });
124
+ }
125
+ class SequelizePasskeyStore extends base_js_1.PasskeyStore {
126
+ constructor(options) {
127
+ super();
128
+ if (!options?.sequelize) {
129
+ throw new Error('SequelizePasskeyStore requires an initialised Sequelize instance');
130
+ }
131
+ this.resolveUserFn = options.resolveUser;
132
+ this.credentials =
133
+ options.credentialModel ??
134
+ (options.credentialModelFactory ?? initPasskeyCredentialModel)(options.sequelize);
135
+ this.challenges =
136
+ options.challengeModel ?? (options.challengeModelFactory ?? initPasskeyChallengeModel)(options.sequelize);
137
+ }
138
+ async resolveUser(params) {
139
+ return this.resolveUserFn(params);
140
+ }
141
+ async listUserCredentials(userId) {
142
+ const models = await this.credentials.findAll({ where: { userId: normalizeUserId(userId) } });
143
+ return models.map((model) => ({
144
+ userId: model.userId,
145
+ credentialId: model.credentialId,
146
+ publicKey: model.publicKey,
147
+ counter: model.counter,
148
+ transports: (model.transports ?? undefined),
149
+ backedUp: model.backedUp,
150
+ deviceType: model.deviceType,
151
+ createdAt: model.createdAt ?? undefined,
152
+ updatedAt: model.updatedAt ?? undefined
153
+ }));
154
+ }
155
+ async deleteCredential(credentialId) {
156
+ const encoded = Buffer.isBuffer(credentialId) ? credentialId.toString('base64') : credentialId;
157
+ const deleted = await this.credentials.destroy({ where: { credentialId: encoded } });
158
+ return deleted > 0;
159
+ }
160
+ async findCredentialById(credentialId) {
161
+ const model = await this.credentials.findByPk(encodeCredentialId(credentialId));
162
+ if (!model) {
163
+ return null;
164
+ }
165
+ return {
166
+ userId: model.userId,
167
+ credentialId: model.credentialId,
168
+ publicKey: model.publicKey,
169
+ counter: model.counter,
170
+ transports: (model.transports ?? undefined),
171
+ backedUp: model.backedUp,
172
+ deviceType: model.deviceType,
173
+ createdAt: model.createdAt ?? undefined,
174
+ updatedAt: model.updatedAt ?? undefined
175
+ };
176
+ }
177
+ async saveCredential(record) {
178
+ await this.credentials.upsert({
179
+ credentialId: record.credentialId,
180
+ userId: normalizeUserId(record.userId),
181
+ publicKey: record.publicKey,
182
+ counter: record.counter,
183
+ transports: record.transports ?? null,
184
+ backedUp: record.backedUp,
185
+ deviceType: record.deviceType
186
+ });
187
+ }
188
+ async updateCredentialCounter(credentialId, counter) {
189
+ await this.credentials.update({ counter }, { where: { credentialId: encodeCredentialId(credentialId) } });
190
+ }
191
+ async saveChallenge(record) {
192
+ await this.challenges.upsert({
193
+ challenge: record.challenge,
194
+ action: record.action,
195
+ userId: record.userId !== undefined ? normalizeUserId(record.userId) : null,
196
+ login: record.login ?? null,
197
+ metadata: (record.metadata ?? {}),
198
+ expiresAt: record.expiresAt
199
+ });
200
+ }
201
+ async consumeChallenge(challenge) {
202
+ const model = await this.challenges.findByPk(challenge);
203
+ if (!model) {
204
+ return null;
205
+ }
206
+ await model.destroy();
207
+ return {
208
+ challenge: model.challenge,
209
+ action: model.action,
210
+ userId: model.userId ?? undefined,
211
+ login: model.login ?? undefined,
212
+ expiresAt: model.expiresAt,
213
+ metadata: model.metadata ?? {}
214
+ };
215
+ }
216
+ async cleanupChallenges(now) {
217
+ await this.challenges.destroy({ where: { expiresAt: { [sequelize_1.Op.lte]: now } } });
218
+ }
219
+ }
220
+ exports.SequelizePasskeyStore = SequelizePasskeyStore;
@@ -0,0 +1,20 @@
1
+ import type { PasskeyChallenge, PasskeyChallengeParams, PasskeyStorageAdapter, PasskeyVerificationParams, PasskeyVerificationResult, PasskeyServiceConfig, StoredPasskeyCredential } from './types.js';
2
+ import type { AuthIdentifier } from '../auth-api/types.js';
3
+ export type { CredentialDeviceType, PasskeyChallenge, PasskeyChallengeParams, PasskeyChallengeRecord, PasskeyChallengeMetadata, PasskeyUserDescriptor, PasskeyVerificationParams, PasskeyVerificationResult, PasskeyServiceConfig, PasskeyStorageAdapter, StoredPasskeyCredential } from './types.js';
4
+ type Logger = Pick<typeof console, 'error' | 'warn'>;
5
+ export declare class PasskeyService {
6
+ private readonly config;
7
+ private readonly adapter;
8
+ private readonly logger;
9
+ constructor(config: PasskeyServiceConfig, adapter: PasskeyStorageAdapter, logger?: Logger);
10
+ listUserCredentials(userId: AuthIdentifier): Promise<StoredPasskeyCredential[]>;
11
+ deleteCredential(credentialId: Buffer | string): Promise<boolean>;
12
+ createChallenge(params: PasskeyChallengeParams): Promise<PasskeyChallenge>;
13
+ verifyResponse(params: PasskeyVerificationParams): Promise<PasskeyVerificationResult>;
14
+ private createRegistrationChallenge;
15
+ private createAuthenticationChallenge;
16
+ private verifyRegistration;
17
+ private verifyAuthentication;
18
+ private requireUser;
19
+ private createExpiry;
20
+ }
@@ -0,0 +1,356 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.PasskeyService = void 0;
37
+ const server_1 = require("@simplewebauthn/server");
38
+ const helpers_1 = require("@simplewebauthn/server/helpers");
39
+ const ALLOWED_TRANSPORTS = [
40
+ 'ble',
41
+ 'cable',
42
+ 'hybrid',
43
+ 'internal',
44
+ 'nfc',
45
+ 'smart-card',
46
+ 'usb'
47
+ ];
48
+ function sanitizeTransports(input) {
49
+ if (!Array.isArray(input)) {
50
+ return undefined;
51
+ }
52
+ const filtered = input
53
+ .map((value) => String(value))
54
+ .filter((value) => ALLOWED_TRANSPORTS.includes(value));
55
+ return filtered.length > 0 ? filtered : undefined;
56
+ }
57
+ function toBase64Url(buffer) {
58
+ return helpers_1.isoBase64URL.fromBuffer(new Uint8Array(buffer));
59
+ }
60
+ function fromBase64Url(value) {
61
+ return Buffer.from(helpers_1.isoBase64URL.toBuffer(value));
62
+ }
63
+ function toBuffer(value) {
64
+ if (Buffer.isBuffer(value)) {
65
+ return value;
66
+ }
67
+ const view = value instanceof Uint8Array ? value : new Uint8Array(value);
68
+ return Buffer.from(view);
69
+ }
70
+ function toBufferOrNull(value) {
71
+ if (!value) {
72
+ return null;
73
+ }
74
+ if (Buffer.isBuffer(value)) {
75
+ return value;
76
+ }
77
+ if (value instanceof ArrayBuffer || value instanceof Uint8Array) {
78
+ return toBuffer(value);
79
+ }
80
+ if (typeof value === 'string') {
81
+ try {
82
+ return fromBase64Url(value);
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ }
88
+ return null;
89
+ }
90
+ async function spkiToCosePublicKey(spki) {
91
+ try {
92
+ const subtle = globalThis.crypto?.subtle ?? (await Promise.resolve().then(() => __importStar(require('crypto')))).webcrypto?.subtle;
93
+ if (!subtle) {
94
+ return null;
95
+ }
96
+ const key = await subtle.importKey('spki', spki, { name: 'ECDSA', namedCurve: 'P-256' }, true, ['verify']);
97
+ const raw = Buffer.from(await subtle.exportKey('raw', key));
98
+ if (raw.length !== 65 || raw[0] !== 0x04) {
99
+ return null;
100
+ }
101
+ const x = raw.slice(1, 33);
102
+ const y = raw.slice(33, 65);
103
+ const coseMap = new Map([
104
+ [1, 2], // kty: EC2
105
+ [3, -7], // alg: ES256
106
+ [-1, 1], // crv: P-256
107
+ [-2, x],
108
+ [-3, y]
109
+ ]);
110
+ return Buffer.from(helpers_1.isoCBOR.encode(coseMap));
111
+ }
112
+ catch {
113
+ return null;
114
+ }
115
+ }
116
+ class PasskeyService {
117
+ constructor(config, adapter, logger = console) {
118
+ this.config = config;
119
+ this.adapter = adapter;
120
+ this.logger = logger;
121
+ }
122
+ async listUserCredentials(userId) {
123
+ return this.adapter.listUserCredentials(userId);
124
+ }
125
+ async deleteCredential(credentialId) {
126
+ return this.adapter.deleteCredential(credentialId);
127
+ }
128
+ async createChallenge(params) {
129
+ await this.adapter.cleanupChallenges?.(new Date());
130
+ const metadata = {
131
+ domain: typeof params.domain === 'string' ? params.domain : undefined,
132
+ fingerprint: typeof params.fingerprint === 'string' ? params.fingerprint : undefined,
133
+ label: typeof params.label === 'string' ? params.label : undefined,
134
+ userAgent: typeof params.userAgent === 'string' ? params.userAgent : undefined
135
+ };
136
+ if (params.action === 'register') {
137
+ return this.createRegistrationChallenge(params, metadata);
138
+ }
139
+ if (params.action === 'authenticate') {
140
+ return this.createAuthenticationChallenge(params, metadata);
141
+ }
142
+ throw new Error(`Unsupported passkey action: ${String(params.action)}`);
143
+ }
144
+ async verifyResponse(params) {
145
+ await this.adapter.cleanupChallenges?.(new Date());
146
+ const record = await this.adapter.consumeChallenge(params.expectedChallenge);
147
+ if (!record) {
148
+ return { verified: false };
149
+ }
150
+ if (record.expiresAt.getTime() <= Date.now()) {
151
+ return { verified: false };
152
+ }
153
+ try {
154
+ if (record.action === 'register') {
155
+ return this.verifyRegistration(params, record);
156
+ }
157
+ if (record.action === 'authenticate') {
158
+ return this.verifyAuthentication(params, record);
159
+ }
160
+ }
161
+ catch (error) {
162
+ this.logger.error?.('Passkey verification failed', error);
163
+ }
164
+ return { verified: false };
165
+ }
166
+ async createRegistrationChallenge(params, metadata) {
167
+ const user = await this.requireUser({ userId: params.userId, login: params.login });
168
+ const existing = await this.adapter.listUserCredentials(user.id);
169
+ const excludeCredentials = existing.map((credential) => {
170
+ const transports = credential.transports;
171
+ return transports && transports.length > 0
172
+ ? { id: toBase64Url(credential.credentialId), transports }
173
+ : { id: toBase64Url(credential.credentialId) };
174
+ });
175
+ const options = await (0, server_1.generateRegistrationOptions)({
176
+ rpName: this.config.rpName,
177
+ rpID: this.config.rpId,
178
+ userID: Buffer.from(String(user.id)),
179
+ userName: user.login,
180
+ userDisplayName: user.displayName,
181
+ excludeCredentials
182
+ });
183
+ const expiresAt = this.createExpiry();
184
+ await this.adapter.saveChallenge({
185
+ challenge: options.challenge,
186
+ action: 'register',
187
+ userId: user.id,
188
+ login: user.login,
189
+ expiresAt,
190
+ metadata
191
+ });
192
+ return {
193
+ challenge: options.challenge,
194
+ expiresAt: expiresAt.toISOString(),
195
+ userId: user.id,
196
+ publicKey: options
197
+ };
198
+ }
199
+ async createAuthenticationChallenge(params, metadata) {
200
+ const user = await this.requireUser({ userId: params.userId, login: params.login });
201
+ const credentials = await this.adapter.listUserCredentials(user.id);
202
+ const allowCredentials = credentials.map((credential) => {
203
+ const transports = sanitizeTransports(credential.transports);
204
+ return transports && transports.length > 0
205
+ ? { type: 'public-key', id: toBase64Url(credential.credentialId), transports }
206
+ : { type: 'public-key', id: toBase64Url(credential.credentialId) };
207
+ });
208
+ const options = await (0, server_1.generateAuthenticationOptions)({
209
+ allowCredentials,
210
+ userVerification: this.config.userVerification,
211
+ rpID: this.config.rpId
212
+ });
213
+ const expiresAt = this.createExpiry();
214
+ await this.adapter.saveChallenge({
215
+ challenge: options.challenge,
216
+ action: 'authenticate',
217
+ userId: user.id,
218
+ login: user.login,
219
+ expiresAt,
220
+ metadata
221
+ });
222
+ return {
223
+ challenge: options.challenge,
224
+ expiresAt: expiresAt.toISOString(),
225
+ userId: user.id,
226
+ publicKey: options
227
+ };
228
+ }
229
+ async verifyRegistration(params, record) {
230
+ const parsed = typeof params.response === 'object' && params.response ? { ...params.response } : {};
231
+ const response = {
232
+ ...parsed,
233
+ id: String(parsed.id ?? ''),
234
+ rawId: String(parsed.rawId ?? '')
235
+ };
236
+ const user = await this.requireUser({ userId: record.userId, login: record.login });
237
+ const result = await (0, server_1.verifyRegistrationResponse)({
238
+ response,
239
+ expectedChallenge: record.challenge,
240
+ expectedOrigin: this.config.origins,
241
+ expectedRPID: this.config.rpId,
242
+ requireUserVerification: true
243
+ });
244
+ if (!result.verified || !result.registrationInfo) {
245
+ if (!result.verified) {
246
+ const err = result.error ?? result;
247
+ this.logger.error?.('Passkey registration verification failed', err);
248
+ }
249
+ return { verified: false };
250
+ }
251
+ const registrationInfo = result.registrationInfo;
252
+ const attestationResponse = params.response?.response;
253
+ const credentialIdPrimary = toBufferOrNull(registrationInfo.credentialID);
254
+ const credentialIdFallback = toBufferOrNull(params.response?.id);
255
+ const credentialId = credentialIdPrimary && credentialIdPrimary.length > 0 ? credentialIdPrimary : credentialIdFallback;
256
+ const publicKeyPrimary = toBufferOrNull(registrationInfo.credentialPublicKey);
257
+ let publicKeyFallback = toBufferOrNull(attestationResponse?.publicKey);
258
+ if ((!publicKeyPrimary || publicKeyPrimary.length === 0) && attestationResponse?.attestationObject) {
259
+ try {
260
+ const attObj = (0, helpers_1.decodeAttestationObject)(helpers_1.isoBase64URL.toBuffer(attestationResponse.attestationObject));
261
+ const parsedAuth = (0, helpers_1.parseAuthenticatorData)(attObj.get('authData'));
262
+ publicKeyFallback = toBufferOrNull(parsedAuth.credentialPublicKey) ?? publicKeyFallback;
263
+ }
264
+ catch (error) {
265
+ this.logger.warn?.('Passkey registration: failed to parse attestationObject', error);
266
+ }
267
+ }
268
+ const publicKey = publicKeyPrimary && publicKeyPrimary.length > 0 ? publicKeyPrimary : publicKeyFallback;
269
+ if (this.logger?.warn) {
270
+ const pkPrimaryHex = publicKeyPrimary ? publicKeyPrimary.slice(0, 4).toString('hex') : 'null';
271
+ const pkFallbackHex = publicKeyFallback ? publicKeyFallback.slice(0, 4).toString('hex') : 'null';
272
+ this.logger.warn(`Passkey registration: pkPrimary len=${publicKeyPrimary?.length ?? 0} head=${pkPrimaryHex}, pkFallback len=${publicKeyFallback?.length ?? 0} head=${pkFallbackHex}`);
273
+ }
274
+ if (!credentialId || credentialId.length === 0) {
275
+ return { verified: false, message: 'Missing credential id in registration response' };
276
+ }
277
+ if (!publicKey || publicKey.length === 0) {
278
+ return { verified: false, message: 'Missing public key in registration response' };
279
+ }
280
+ let storedPublicKey = Buffer.isBuffer(publicKey) ? publicKey : toBuffer(publicKey);
281
+ // If fallback is an SPKI key (DER, starts with 0x30) convert to COSE so verification succeeds.
282
+ if (storedPublicKey[0] === 0x30) {
283
+ const converted = await spkiToCosePublicKey(storedPublicKey);
284
+ if (converted) {
285
+ storedPublicKey = converted;
286
+ }
287
+ else {
288
+ this.logger.warn?.('Passkey registration: failed to convert SPKI public key to COSE');
289
+ }
290
+ }
291
+ await this.adapter.saveCredential({
292
+ userId: user.id,
293
+ credentialId,
294
+ publicKey: storedPublicKey,
295
+ counter: registrationInfo.counter ?? 0,
296
+ transports: sanitizeTransports(params.response.transports),
297
+ backedUp: registrationInfo.credentialDeviceType === 'multiDevice',
298
+ deviceType: registrationInfo.credentialDeviceType
299
+ });
300
+ return { verified: true, userId: user.id, login: user.login };
301
+ }
302
+ async verifyAuthentication(params, record) {
303
+ const parsed = typeof params.response === 'object' && params.response ? { ...params.response } : {};
304
+ const response = {
305
+ ...parsed,
306
+ id: String(parsed.id ?? ''),
307
+ rawId: String(parsed.rawId ?? '')
308
+ };
309
+ const credential = await this.adapter.findCredentialById(fromBase64Url(response.id));
310
+ if (!credential) {
311
+ return { verified: false };
312
+ }
313
+ const user = await this.requireUser({ userId: credential.userId, login: record.login });
314
+ const storedAuthData = {
315
+ id: credential.credentialId,
316
+ publicKey: toBuffer(credential.publicKey),
317
+ credentialPublicKey: toBuffer(credential.publicKey),
318
+ counter: credential.counter,
319
+ transports: credential.transports ?? undefined,
320
+ credentialBackedUp: credential.backedUp,
321
+ credentialDeviceType: credential.deviceType
322
+ // simplewebauthn accepts either Uint8Array or Buffer; ensure Buffer
323
+ // see https://github.com/MasterKale/SimpleWebAuthn/blob/master/packages/server/src/authentication/verifyAuthenticationResponse.ts
324
+ };
325
+ const result = await (0, server_1.verifyAuthenticationResponse)({
326
+ response,
327
+ expectedChallenge: record.challenge,
328
+ expectedOrigin: this.config.origins,
329
+ expectedRPID: this.config.rpId,
330
+ credential: storedAuthData,
331
+ requireUserVerification: true
332
+ });
333
+ if (!result.verified) {
334
+ const err = result.error ?? result;
335
+ this.logger.error?.('Passkey authentication verification failed', err);
336
+ return { verified: false };
337
+ }
338
+ await this.adapter.updateCredentialCounter(credential.credentialId, result.authenticationInfo.newCounter);
339
+ return {
340
+ verified: true,
341
+ userId: user.id,
342
+ login: user.login
343
+ };
344
+ }
345
+ async requireUser(params) {
346
+ const user = await this.adapter.resolveUser(params);
347
+ if (!user) {
348
+ throw new Error('User not found');
349
+ }
350
+ return user;
351
+ }
352
+ createExpiry() {
353
+ return new Date(Date.now() + this.config.timeoutMs);
354
+ }
355
+ }
356
+ exports.PasskeyService = PasskeyService;
@@ -0,0 +1,78 @@
1
+ import type { AuthIdentifier } from '../auth-api/types.js';
2
+ import type { Token, TokenPair } from '../token/types.js';
3
+ import type { AuthenticatorTransportFuture } from '@simplewebauthn/server';
4
+ export type CredentialDeviceType = 'singleDevice' | 'multiDevice';
5
+ export interface PasskeyServiceConfig {
6
+ rpId: string;
7
+ rpName: string;
8
+ origins: string[];
9
+ timeoutMs: number;
10
+ userVerification?: 'preferred' | 'required' | 'discouraged';
11
+ }
12
+ export interface PasskeyChallengeMetadata {
13
+ domain?: string;
14
+ fingerprint?: string;
15
+ label?: string;
16
+ userAgent?: string;
17
+ }
18
+ export interface PasskeyChallengeRecord {
19
+ challenge: string;
20
+ action: 'register' | 'authenticate';
21
+ userId?: AuthIdentifier;
22
+ login?: string;
23
+ expiresAt: Date;
24
+ metadata: PasskeyChallengeMetadata;
25
+ }
26
+ export interface PasskeyUserDescriptor {
27
+ id: AuthIdentifier;
28
+ login: string;
29
+ displayName: string;
30
+ }
31
+ export interface StoredPasskeyCredential {
32
+ userId: AuthIdentifier;
33
+ credentialId: Buffer;
34
+ publicKey: Buffer;
35
+ counter: number;
36
+ transports?: AuthenticatorTransportFuture[];
37
+ backedUp: boolean;
38
+ deviceType: CredentialDeviceType;
39
+ createdAt?: Date;
40
+ updatedAt?: Date;
41
+ }
42
+ export interface PasskeyStorageAdapter {
43
+ resolveUser(params: {
44
+ userId?: AuthIdentifier;
45
+ login?: string;
46
+ }): Promise<PasskeyUserDescriptor | null>;
47
+ listUserCredentials(userId: AuthIdentifier): Promise<StoredPasskeyCredential[]>;
48
+ deleteCredential(credentialId: Buffer | string): Promise<boolean>;
49
+ findCredentialById(credentialId: Buffer): Promise<StoredPasskeyCredential | null>;
50
+ saveCredential(record: StoredPasskeyCredential): Promise<void>;
51
+ updateCredentialCounter(credentialId: Buffer, counter: number): Promise<void>;
52
+ saveChallenge(record: PasskeyChallengeRecord): Promise<void>;
53
+ consumeChallenge(challenge: string): Promise<PasskeyChallengeRecord | null>;
54
+ cleanupChallenges?(now: Date): Promise<void>;
55
+ }
56
+ export interface PasskeyChallengeParams extends Partial<Omit<Token, 'userId'>> {
57
+ action: 'register' | 'authenticate';
58
+ login?: string;
59
+ userAgent?: string;
60
+ userId?: AuthIdentifier;
61
+ }
62
+ export interface PasskeyChallenge extends Record<string, unknown> {
63
+ challenge: string;
64
+ expiresAt?: string | number | Date;
65
+ userId?: AuthIdentifier;
66
+ }
67
+ export interface PasskeyVerificationParams extends Partial<Omit<Token, 'userId'>> {
68
+ expectedChallenge: string;
69
+ login?: string;
70
+ response: Record<string, unknown>;
71
+ userId?: AuthIdentifier;
72
+ }
73
+ export interface PasskeyVerificationResult extends Record<string, unknown> {
74
+ login?: string;
75
+ tokens?: TokenPair;
76
+ userId?: AuthIdentifier;
77
+ verified: boolean;
78
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });