@technomoron/apicore-server 1.0.0-beta.1
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.
- package/LICENSE +21 -0
- package/dist/cjs/api-module.cjs +34 -0
- package/dist/cjs/api-module.d.ts +45 -0
- package/dist/cjs/apicore-server.cjs +1561 -0
- package/dist/cjs/apicore-server.d.ts +288 -0
- package/dist/cjs/auth-api/auth-module.cjs +1248 -0
- package/dist/cjs/auth-api/auth-module.d.ts +116 -0
- package/dist/cjs/auth-api/compat-auth-storage.cjs +128 -0
- package/dist/cjs/auth-api/compat-auth-storage.d.ts +57 -0
- package/dist/cjs/auth-api/mem-auth-store.cjs +121 -0
- package/dist/cjs/auth-api/mem-auth-store.d.ts +68 -0
- package/dist/cjs/auth-api/module.cjs +25 -0
- package/dist/cjs/auth-api/module.d.ts +20 -0
- package/dist/cjs/auth-api/schemas.cjs +171 -0
- package/dist/cjs/auth-api/schemas.d.ts +21 -0
- package/dist/cjs/auth-api/sql-auth-store.cjs +179 -0
- package/dist/cjs/auth-api/sql-auth-store.d.ts +87 -0
- package/dist/cjs/auth-api/storage.cjs +102 -0
- package/dist/cjs/auth-api/storage.d.ts +38 -0
- package/dist/cjs/auth-api/types.cjs +2 -0
- package/dist/cjs/auth-api/types.d.ts +34 -0
- package/dist/cjs/auth-api/user-id.cjs +47 -0
- package/dist/cjs/auth-api/user-id.d.ts +5 -0
- package/dist/cjs/auth-cookie-options.cjs +66 -0
- package/dist/cjs/auth-cookie-options.d.ts +13 -0
- package/dist/cjs/base/client-info.cjs +285 -0
- package/dist/cjs/base/client-info.d.ts +27 -0
- package/dist/cjs/base/error-utils.cjs +50 -0
- package/dist/cjs/base/error-utils.d.ts +16 -0
- package/dist/cjs/base/request-utils.cjs +27 -0
- package/dist/cjs/base/request-utils.d.ts +8 -0
- package/dist/cjs/index.cjs +51 -0
- package/dist/cjs/index.d.ts +34 -0
- package/dist/cjs/limiter/auth-rate-limiter.cjs +35 -0
- package/dist/cjs/limiter/auth-rate-limiter.d.ts +12 -0
- package/dist/cjs/limiter/fixed-window.cjs +41 -0
- package/dist/cjs/limiter/fixed-window.d.ts +11 -0
- package/dist/cjs/oauth/base.cjs +7 -0
- package/dist/cjs/oauth/base.d.ts +17 -0
- package/dist/cjs/oauth/memory.cjs +135 -0
- package/dist/cjs/oauth/memory.d.ts +22 -0
- package/dist/cjs/oauth/models.cjs +47 -0
- package/dist/cjs/oauth/models.d.ts +50 -0
- package/dist/cjs/oauth/sequelize.cjs +159 -0
- package/dist/cjs/oauth/sequelize.d.ts +30 -0
- package/dist/cjs/oauth/types.cjs +3 -0
- package/dist/cjs/oauth/types.d.ts +51 -0
- package/dist/cjs/passkey/base.cjs +7 -0
- package/dist/cjs/passkey/base.d.ts +28 -0
- package/dist/cjs/passkey/config.cjs +26 -0
- package/dist/cjs/passkey/config.d.ts +2 -0
- package/dist/cjs/passkey/memory.cjs +123 -0
- package/dist/cjs/passkey/memory.d.ts +34 -0
- package/dist/cjs/passkey/models.cjs +142 -0
- package/dist/cjs/passkey/models.d.ts +34 -0
- package/dist/cjs/passkey/sequelize.cjs +126 -0
- package/dist/cjs/passkey/sequelize.d.ts +42 -0
- package/dist/cjs/passkey/service.cjs +413 -0
- package/dist/cjs/passkey/service.d.ts +21 -0
- package/dist/cjs/passkey/types.cjs +2 -0
- package/dist/cjs/passkey/types.d.ts +84 -0
- package/dist/cjs/sequelize-utils.cjs +56 -0
- package/dist/cjs/sequelize-utils.d.ts +8 -0
- package/dist/cjs/token/base.cjs +120 -0
- package/dist/cjs/token/base.d.ts +46 -0
- package/dist/cjs/token/memory.cjs +234 -0
- package/dist/cjs/token/memory.d.ts +29 -0
- package/dist/cjs/token/sequelize.cjs +400 -0
- package/dist/cjs/token/sequelize.d.ts +58 -0
- package/dist/cjs/token/types.cjs +2 -0
- package/dist/cjs/token/types.d.ts +34 -0
- package/dist/cjs/upload/memory.cjs +92 -0
- package/dist/cjs/upload/memory.d.ts +17 -0
- package/dist/cjs/upload/tus-module.cjs +270 -0
- package/dist/cjs/upload/tus-module.d.ts +38 -0
- package/dist/cjs/upload/types.cjs +2 -0
- package/dist/cjs/upload/types.d.ts +28 -0
- package/dist/cjs/user/base.cjs +53 -0
- package/dist/cjs/user/base.d.ts +36 -0
- package/dist/cjs/user/memory.cjs +194 -0
- package/dist/cjs/user/memory.d.ts +37 -0
- package/dist/cjs/user/sequelize.cjs +194 -0
- package/dist/cjs/user/sequelize.d.ts +46 -0
- package/dist/cjs/user/types.cjs +2 -0
- package/dist/cjs/user/types.d.ts +11 -0
- package/dist/esm/api-module.d.ts +45 -0
- package/dist/esm/api-module.js +30 -0
- package/dist/esm/apicore-server.d.ts +288 -0
- package/dist/esm/apicore-server.js +1552 -0
- package/dist/esm/auth-api/auth-module.d.ts +116 -0
- package/dist/esm/auth-api/auth-module.js +1246 -0
- package/dist/esm/auth-api/compat-auth-storage.d.ts +57 -0
- package/dist/esm/auth-api/compat-auth-storage.js +124 -0
- package/dist/esm/auth-api/mem-auth-store.d.ts +68 -0
- package/dist/esm/auth-api/mem-auth-store.js +117 -0
- package/dist/esm/auth-api/module.d.ts +20 -0
- package/dist/esm/auth-api/module.js +21 -0
- package/dist/esm/auth-api/schemas.d.ts +21 -0
- package/dist/esm/auth-api/schemas.js +168 -0
- package/dist/esm/auth-api/sql-auth-store.d.ts +87 -0
- package/dist/esm/auth-api/sql-auth-store.js +175 -0
- package/dist/esm/auth-api/storage.d.ts +38 -0
- package/dist/esm/auth-api/storage.js +98 -0
- package/dist/esm/auth-api/types.d.ts +34 -0
- package/dist/esm/auth-api/types.js +1 -0
- package/dist/esm/auth-api/user-id.d.ts +5 -0
- package/dist/esm/auth-api/user-id.js +41 -0
- package/dist/esm/auth-cookie-options.d.ts +13 -0
- package/dist/esm/auth-cookie-options.js +63 -0
- package/dist/esm/base/client-info.d.ts +27 -0
- package/dist/esm/base/client-info.js +282 -0
- package/dist/esm/base/error-utils.d.ts +16 -0
- package/dist/esm/base/error-utils.js +44 -0
- package/dist/esm/base/request-utils.d.ts +8 -0
- package/dist/esm/base/request-utils.js +23 -0
- package/dist/esm/index.d.ts +34 -0
- package/dist/esm/index.js +21 -0
- package/dist/esm/limiter/auth-rate-limiter.d.ts +12 -0
- package/dist/esm/limiter/auth-rate-limiter.js +32 -0
- package/dist/esm/limiter/fixed-window.d.ts +11 -0
- package/dist/esm/limiter/fixed-window.js +37 -0
- package/dist/esm/oauth/base.d.ts +17 -0
- package/dist/esm/oauth/base.js +3 -0
- package/dist/esm/oauth/memory.d.ts +22 -0
- package/dist/esm/oauth/memory.js +128 -0
- package/dist/esm/oauth/models.d.ts +50 -0
- package/dist/esm/oauth/models.js +38 -0
- package/dist/esm/oauth/sequelize.d.ts +30 -0
- package/dist/esm/oauth/sequelize.js +148 -0
- package/dist/esm/oauth/types.d.ts +51 -0
- package/dist/esm/oauth/types.js +2 -0
- package/dist/esm/passkey/base.d.ts +28 -0
- package/dist/esm/passkey/base.js +3 -0
- package/dist/esm/passkey/config.d.ts +2 -0
- package/dist/esm/passkey/config.js +23 -0
- package/dist/esm/passkey/memory.d.ts +34 -0
- package/dist/esm/passkey/memory.js +119 -0
- package/dist/esm/passkey/models.d.ts +34 -0
- package/dist/esm/passkey/models.js +135 -0
- package/dist/esm/passkey/sequelize.d.ts +42 -0
- package/dist/esm/passkey/sequelize.js +122 -0
- package/dist/esm/passkey/service.d.ts +21 -0
- package/dist/esm/passkey/service.js +376 -0
- package/dist/esm/passkey/types.d.ts +84 -0
- package/dist/esm/passkey/types.js +1 -0
- package/dist/esm/sequelize-utils.d.ts +8 -0
- package/dist/esm/sequelize-utils.js +47 -0
- package/dist/esm/token/base.d.ts +46 -0
- package/dist/esm/token/base.js +113 -0
- package/dist/esm/token/memory.d.ts +29 -0
- package/dist/esm/token/memory.js +230 -0
- package/dist/esm/token/sequelize.d.ts +58 -0
- package/dist/esm/token/sequelize.js +396 -0
- package/dist/esm/token/types.d.ts +34 -0
- package/dist/esm/token/types.js +1 -0
- package/dist/esm/upload/memory.d.ts +17 -0
- package/dist/esm/upload/memory.js +86 -0
- package/dist/esm/upload/tus-module.d.ts +38 -0
- package/dist/esm/upload/tus-module.js +266 -0
- package/dist/esm/upload/types.d.ts +28 -0
- package/dist/esm/upload/types.js +1 -0
- package/dist/esm/user/base.d.ts +36 -0
- package/dist/esm/user/base.js +46 -0
- package/dist/esm/user/memory.d.ts +37 -0
- package/dist/esm/user/memory.js +190 -0
- package/dist/esm/user/sequelize.d.ts +46 -0
- package/dist/esm/user/sequelize.js +188 -0
- package/dist/esm/user/types.d.ts +11 -0
- package/dist/esm/user/types.js +1 -0
- package/docs/swagger/openapi.json +2162 -0
- package/package.json +131 -0
|
@@ -0,0 +1,413 @@
|
|
|
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 toOptionalString(value) {
|
|
58
|
+
if (typeof value !== 'string') {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
const trimmed = value.trim();
|
|
62
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
63
|
+
}
|
|
64
|
+
function toBase64Url(buffer) {
|
|
65
|
+
return helpers_1.isoBase64URL.fromBuffer(new Uint8Array(buffer));
|
|
66
|
+
}
|
|
67
|
+
function fromBase64Url(value) {
|
|
68
|
+
return Buffer.from(helpers_1.isoBase64URL.toBuffer(value));
|
|
69
|
+
}
|
|
70
|
+
function toBuffer(value) {
|
|
71
|
+
if (Buffer.isBuffer(value)) {
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
const view = value instanceof Uint8Array ? value : new Uint8Array(value);
|
|
75
|
+
return Buffer.from(view);
|
|
76
|
+
}
|
|
77
|
+
function toBufferOrNull(value) {
|
|
78
|
+
if (!value) {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
if (Buffer.isBuffer(value)) {
|
|
82
|
+
return value;
|
|
83
|
+
}
|
|
84
|
+
if (value instanceof ArrayBuffer || value instanceof Uint8Array) {
|
|
85
|
+
return toBuffer(value);
|
|
86
|
+
}
|
|
87
|
+
if (typeof value === 'string') {
|
|
88
|
+
try {
|
|
89
|
+
return fromBase64Url(value);
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
async function spkiToCosePublicKey(spki) {
|
|
98
|
+
try {
|
|
99
|
+
const subtle = (globalThis.crypto?.subtle ??
|
|
100
|
+
(await Promise.resolve().then(() => __importStar(require('crypto')))).webcrypto?.subtle);
|
|
101
|
+
if (!subtle) {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
const spkiView = new Uint8Array(spki);
|
|
105
|
+
const ecCurves = [
|
|
106
|
+
{ namedCurve: 'P-256', crv: 1, alg: -7, rawLength: 65 },
|
|
107
|
+
{ namedCurve: 'P-384', crv: 2, alg: -35, rawLength: 97 },
|
|
108
|
+
{ namedCurve: 'P-521', crv: 3, alg: -36, rawLength: 133 }
|
|
109
|
+
];
|
|
110
|
+
for (const curve of ecCurves) {
|
|
111
|
+
try {
|
|
112
|
+
const key = await subtle.importKey('spki', spkiView, { name: 'ECDSA', namedCurve: curve.namedCurve }, true, ['verify']);
|
|
113
|
+
const raw = Buffer.from(await subtle.exportKey('raw', key));
|
|
114
|
+
if (raw.length !== curve.rawLength || raw[0] !== 0x04) {
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const coordLength = (raw.length - 1) / 2;
|
|
118
|
+
const x = raw.slice(1, 1 + coordLength);
|
|
119
|
+
const y = raw.slice(1 + coordLength);
|
|
120
|
+
const coseMap = new Map([
|
|
121
|
+
[1, 2], // kty: EC2
|
|
122
|
+
[3, curve.alg],
|
|
123
|
+
[-1, curve.crv],
|
|
124
|
+
[-2, x],
|
|
125
|
+
[-3, y]
|
|
126
|
+
]);
|
|
127
|
+
return Buffer.from(helpers_1.isoCBOR.encode(coseMap));
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
// try next algorithm
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
try {
|
|
134
|
+
const edKey = await subtle.importKey('spki', spkiView, { name: 'Ed25519' }, true, ['verify']);
|
|
135
|
+
const raw = Buffer.from(await subtle.exportKey('raw', edKey));
|
|
136
|
+
if (raw.length !== 32) {
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
const coseMap = new Map([
|
|
140
|
+
[1, 1], // kty: OKP
|
|
141
|
+
[3, -8], // alg: EdDSA
|
|
142
|
+
[-1, 6], // crv: Ed25519
|
|
143
|
+
[-2, raw]
|
|
144
|
+
]);
|
|
145
|
+
return Buffer.from(helpers_1.isoCBOR.encode(coseMap));
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
class PasskeyService {
|
|
156
|
+
constructor(config, adapter, logger = console) {
|
|
157
|
+
this.config = config;
|
|
158
|
+
this.adapter = adapter;
|
|
159
|
+
this.logger = logger;
|
|
160
|
+
}
|
|
161
|
+
async listUserCredentials(userId) {
|
|
162
|
+
return this.adapter.listUserCredentials(userId);
|
|
163
|
+
}
|
|
164
|
+
async deleteCredential(credentialId, userId) {
|
|
165
|
+
if (userId !== undefined) {
|
|
166
|
+
const credentials = await this.adapter.listUserCredentials(userId);
|
|
167
|
+
const target = Buffer.isBuffer(credentialId) ? credentialId : Buffer.from(String(credentialId), 'base64');
|
|
168
|
+
const owns = credentials.some((c) => {
|
|
169
|
+
const stored = Buffer.isBuffer(c.credentialId)
|
|
170
|
+
? c.credentialId
|
|
171
|
+
: Buffer.from(String(c.credentialId), 'base64');
|
|
172
|
+
return stored.equals(target);
|
|
173
|
+
});
|
|
174
|
+
if (!owns)
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
return this.adapter.deleteCredential(credentialId);
|
|
178
|
+
}
|
|
179
|
+
async createChallenge(params) {
|
|
180
|
+
await this.adapter.cleanupChallenges?.(new Date());
|
|
181
|
+
if (params.action === 'register') {
|
|
182
|
+
return this.createRegistrationChallenge(params);
|
|
183
|
+
}
|
|
184
|
+
if (params.action === 'authenticate') {
|
|
185
|
+
return this.createAuthenticationChallenge(params);
|
|
186
|
+
}
|
|
187
|
+
throw new Error(`Unsupported passkey action: ${String(params.action)}`);
|
|
188
|
+
}
|
|
189
|
+
async verifyResponse(params) {
|
|
190
|
+
await this.adapter.cleanupChallenges?.(new Date());
|
|
191
|
+
const existing = this.adapter.getChallenge ? await this.adapter.getChallenge(params.expectedChallenge) : null;
|
|
192
|
+
if (existing && existing.expiresAt.getTime() <= Date.now()) {
|
|
193
|
+
return { verified: false };
|
|
194
|
+
}
|
|
195
|
+
const record = await this.adapter.consumeChallenge(params.expectedChallenge);
|
|
196
|
+
if (!record) {
|
|
197
|
+
return { verified: false };
|
|
198
|
+
}
|
|
199
|
+
if (record.expiresAt.getTime() <= Date.now()) {
|
|
200
|
+
return { verified: false };
|
|
201
|
+
}
|
|
202
|
+
try {
|
|
203
|
+
if (record.action === 'register') {
|
|
204
|
+
return this.verifyRegistration(params, record);
|
|
205
|
+
}
|
|
206
|
+
if (record.action === 'authenticate') {
|
|
207
|
+
return this.verifyAuthentication(params, record);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
this.logger.error?.('Passkey verification failed', error);
|
|
212
|
+
}
|
|
213
|
+
return { verified: false };
|
|
214
|
+
}
|
|
215
|
+
async createRegistrationChallenge(params) {
|
|
216
|
+
const user = await this.requireUser({ userId: params.userId, login: params.login });
|
|
217
|
+
const existing = await this.adapter.listUserCredentials(user.id);
|
|
218
|
+
const excludeCredentials = existing.map((credential) => {
|
|
219
|
+
const transports = credential.transports;
|
|
220
|
+
return transports && transports.length > 0
|
|
221
|
+
? { id: toBase64Url(credential.credentialId), transports }
|
|
222
|
+
: { id: toBase64Url(credential.credentialId) };
|
|
223
|
+
});
|
|
224
|
+
const options = await (0, server_1.generateRegistrationOptions)({
|
|
225
|
+
rpName: this.config.rpName,
|
|
226
|
+
rpID: this.config.rpId,
|
|
227
|
+
userID: Buffer.from(String(user.id)),
|
|
228
|
+
userName: user.login,
|
|
229
|
+
userDisplayName: user.displayName,
|
|
230
|
+
excludeCredentials
|
|
231
|
+
});
|
|
232
|
+
const expiresAt = this.createExpiry();
|
|
233
|
+
await this.adapter.saveChallenge({
|
|
234
|
+
challenge: options.challenge,
|
|
235
|
+
action: 'register',
|
|
236
|
+
userId: user.id,
|
|
237
|
+
login: user.login,
|
|
238
|
+
expiresAt
|
|
239
|
+
});
|
|
240
|
+
return {
|
|
241
|
+
challenge: options.challenge,
|
|
242
|
+
expiresAt: expiresAt.toISOString(),
|
|
243
|
+
userId: user.id,
|
|
244
|
+
publicKey: options
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
async createAuthenticationChallenge(params) {
|
|
248
|
+
const user = await this.requireUser({ userId: params.userId, login: params.login });
|
|
249
|
+
const credentials = await this.adapter.listUserCredentials(user.id);
|
|
250
|
+
const allowCredentials = credentials.map((credential) => {
|
|
251
|
+
const transports = sanitizeTransports(credential.transports);
|
|
252
|
+
return transports && transports.length > 0
|
|
253
|
+
? { type: 'public-key', id: toBase64Url(credential.credentialId), transports }
|
|
254
|
+
: { type: 'public-key', id: toBase64Url(credential.credentialId) };
|
|
255
|
+
});
|
|
256
|
+
const options = await (0, server_1.generateAuthenticationOptions)({
|
|
257
|
+
allowCredentials,
|
|
258
|
+
userVerification: this.config.userVerification,
|
|
259
|
+
rpID: this.config.rpId
|
|
260
|
+
});
|
|
261
|
+
const expiresAt = this.createExpiry();
|
|
262
|
+
await this.adapter.saveChallenge({
|
|
263
|
+
challenge: options.challenge,
|
|
264
|
+
action: 'authenticate',
|
|
265
|
+
userId: user.id,
|
|
266
|
+
login: user.login,
|
|
267
|
+
expiresAt
|
|
268
|
+
});
|
|
269
|
+
return {
|
|
270
|
+
challenge: options.challenge,
|
|
271
|
+
expiresAt: expiresAt.toISOString(),
|
|
272
|
+
userId: user.id,
|
|
273
|
+
publicKey: options
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
async verifyRegistration(params, record) {
|
|
277
|
+
const parsed = typeof params.response === 'object' && params.response ? { ...params.response } : {};
|
|
278
|
+
const response = {
|
|
279
|
+
...parsed,
|
|
280
|
+
id: String(parsed.id ?? ''),
|
|
281
|
+
rawId: String(parsed.rawId ?? '')
|
|
282
|
+
};
|
|
283
|
+
const user = await this.requireUser({ userId: record.userId, login: record.login });
|
|
284
|
+
const result = await (0, server_1.verifyRegistrationResponse)({
|
|
285
|
+
response,
|
|
286
|
+
expectedChallenge: record.challenge,
|
|
287
|
+
expectedOrigin: this.config.origins,
|
|
288
|
+
expectedRPID: this.config.rpId,
|
|
289
|
+
requireUserVerification: this.requireUserVerification()
|
|
290
|
+
});
|
|
291
|
+
if (!result.verified || !result.registrationInfo) {
|
|
292
|
+
if (!result.verified) {
|
|
293
|
+
const err = result.error ?? result;
|
|
294
|
+
this.logger.error?.('Passkey registration verification failed', err);
|
|
295
|
+
}
|
|
296
|
+
return { verified: false };
|
|
297
|
+
}
|
|
298
|
+
const registrationInfo = result.registrationInfo;
|
|
299
|
+
const attestationResponse = params.response.response;
|
|
300
|
+
const credentialIdPrimary = toBufferOrNull(registrationInfo.credentialID);
|
|
301
|
+
const credentialIdFallback = toBufferOrNull(params.response.id);
|
|
302
|
+
const credentialId = credentialIdPrimary && credentialIdPrimary.length > 0
|
|
303
|
+
? credentialIdPrimary
|
|
304
|
+
: (credentialIdFallback ?? Buffer.alloc(0));
|
|
305
|
+
const publicKeyPrimary = toBufferOrNull(registrationInfo.credentialPublicKey);
|
|
306
|
+
let publicKeyFallback = toBufferOrNull(attestationResponse?.publicKey);
|
|
307
|
+
if ((!publicKeyPrimary || publicKeyPrimary.length === 0) && attestationResponse?.attestationObject) {
|
|
308
|
+
try {
|
|
309
|
+
const attestationObject = String(attestationResponse.attestationObject);
|
|
310
|
+
const attObj = (0, helpers_1.decodeAttestationObject)(helpers_1.isoBase64URL.toBuffer(attestationObject));
|
|
311
|
+
const parsedAuth = (0, helpers_1.parseAuthenticatorData)(attObj.get('authData'));
|
|
312
|
+
publicKeyFallback = toBufferOrNull(parsedAuth.credentialPublicKey) ?? publicKeyFallback;
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
this.logger.warn?.('Passkey registration: failed to parse attestationObject', error);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
const publicKey = publicKeyPrimary && publicKeyPrimary.length > 0 ? publicKeyPrimary : publicKeyFallback;
|
|
319
|
+
if (this.config.debug && this.logger?.warn) {
|
|
320
|
+
const pkPrimaryHex = publicKeyPrimary ? publicKeyPrimary.slice(0, 4).toString('hex') : 'null';
|
|
321
|
+
const pkFallbackHex = publicKeyFallback ? publicKeyFallback.slice(0, 4).toString('hex') : 'null';
|
|
322
|
+
this.logger.warn(`Passkey registration: pkPrimary len=${publicKeyPrimary?.length ?? 0} head=${pkPrimaryHex}, pkFallback len=${publicKeyFallback?.length ?? 0} head=${pkFallbackHex}`);
|
|
323
|
+
}
|
|
324
|
+
if (!credentialId || credentialId.length === 0) {
|
|
325
|
+
return { verified: false, message: 'Missing credential id in registration response' };
|
|
326
|
+
}
|
|
327
|
+
if (!publicKey || publicKey.length === 0) {
|
|
328
|
+
return { verified: false, message: 'Missing public key in registration response' };
|
|
329
|
+
}
|
|
330
|
+
let storedPublicKey = Buffer.isBuffer(publicKey) ? publicKey : toBuffer(publicKey);
|
|
331
|
+
// If fallback is an SPKI key (DER, starts with 0x30) convert to COSE so verification succeeds.
|
|
332
|
+
if (storedPublicKey[0] === 0x30) {
|
|
333
|
+
const converted = await spkiToCosePublicKey(storedPublicKey);
|
|
334
|
+
if (converted) {
|
|
335
|
+
storedPublicKey = converted;
|
|
336
|
+
}
|
|
337
|
+
else {
|
|
338
|
+
this.logger.warn?.('Passkey registration: failed to convert SPKI public key to COSE');
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
await this.adapter.saveCredential({
|
|
342
|
+
userId: user.id,
|
|
343
|
+
credentialId,
|
|
344
|
+
publicKey: storedPublicKey,
|
|
345
|
+
counter: registrationInfo.counter ?? 0,
|
|
346
|
+
transports: sanitizeTransports(params.response.transports),
|
|
347
|
+
backedUp: registrationInfo.credentialBackedUp ?? registrationInfo.credentialDeviceType === 'multiDevice',
|
|
348
|
+
deviceType: registrationInfo.credentialDeviceType,
|
|
349
|
+
label: toOptionalString(params.label),
|
|
350
|
+
createdDomain: toOptionalString(params.domain),
|
|
351
|
+
createdUserAgent: toOptionalString(params.userAgent),
|
|
352
|
+
createdBrowser: toOptionalString(params.browser),
|
|
353
|
+
createdOs: toOptionalString(params.os),
|
|
354
|
+
createdDevice: toOptionalString(params.device),
|
|
355
|
+
createdIp: toOptionalString(params.ip)
|
|
356
|
+
});
|
|
357
|
+
return { verified: true, userId: user.id, login: user.login };
|
|
358
|
+
}
|
|
359
|
+
async verifyAuthentication(params, record) {
|
|
360
|
+
const parsed = typeof params.response === 'object' && params.response ? { ...params.response } : {};
|
|
361
|
+
const response = {
|
|
362
|
+
...parsed,
|
|
363
|
+
id: String(parsed.id ?? ''),
|
|
364
|
+
rawId: String(parsed.rawId ?? '')
|
|
365
|
+
};
|
|
366
|
+
const credential = await this.adapter.findCredentialById(fromBase64Url(response.id));
|
|
367
|
+
if (!credential) {
|
|
368
|
+
return { verified: false };
|
|
369
|
+
}
|
|
370
|
+
const user = await this.requireUser({ userId: credential.userId, login: record.login });
|
|
371
|
+
const storedAuthData = {
|
|
372
|
+
id: toBase64Url(credential.credentialId),
|
|
373
|
+
publicKey: new Uint8Array(toBuffer(credential.publicKey)),
|
|
374
|
+
counter: credential.counter,
|
|
375
|
+
transports: credential.transports ?? undefined
|
|
376
|
+
// simplewebauthn accepts either Uint8Array or Buffer; ensure Buffer
|
|
377
|
+
// see https://github.com/MasterKale/SimpleWebAuthn/blob/master/packages/server/src/authentication/verifyAuthenticationResponse.ts
|
|
378
|
+
};
|
|
379
|
+
const result = await (0, server_1.verifyAuthenticationResponse)({
|
|
380
|
+
response,
|
|
381
|
+
expectedChallenge: record.challenge,
|
|
382
|
+
expectedOrigin: this.config.origins,
|
|
383
|
+
expectedRPID: this.config.rpId,
|
|
384
|
+
credential: storedAuthData,
|
|
385
|
+
requireUserVerification: this.requireUserVerification()
|
|
386
|
+
});
|
|
387
|
+
if (!result.verified) {
|
|
388
|
+
const err = result.error ?? result;
|
|
389
|
+
this.logger.error?.('Passkey authentication verification failed', err);
|
|
390
|
+
return { verified: false };
|
|
391
|
+
}
|
|
392
|
+
await this.adapter.updateCredentialCounter(credential.credentialId, result.authenticationInfo.newCounter);
|
|
393
|
+
return {
|
|
394
|
+
verified: true,
|
|
395
|
+
userId: user.id,
|
|
396
|
+
login: user.login
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
async requireUser(params) {
|
|
400
|
+
const user = await this.adapter.resolveUser(params);
|
|
401
|
+
if (!user) {
|
|
402
|
+
throw new Error('User not found');
|
|
403
|
+
}
|
|
404
|
+
return user;
|
|
405
|
+
}
|
|
406
|
+
createExpiry() {
|
|
407
|
+
return new Date(Date.now() + this.config.timeoutMs);
|
|
408
|
+
}
|
|
409
|
+
requireUserVerification() {
|
|
410
|
+
return this.config.userVerification !== 'discouraged';
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
exports.PasskeyService = PasskeyService;
|
|
@@ -0,0 +1,21 @@
|
|
|
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, 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, userId?: AuthIdentifier): 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
|
+
private requireUserVerification;
|
|
21
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
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
|
+
* When enabled, PasskeyService emits additional diagnostic logs during registration/authentication.
|
|
13
|
+
* Defaults to false.
|
|
14
|
+
*/
|
|
15
|
+
debug?: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface PasskeyChallengeRecord {
|
|
18
|
+
challenge: string;
|
|
19
|
+
action: 'register' | 'authenticate';
|
|
20
|
+
userId?: AuthIdentifier;
|
|
21
|
+
login?: string;
|
|
22
|
+
expiresAt: Date;
|
|
23
|
+
}
|
|
24
|
+
export interface PasskeyUserDescriptor {
|
|
25
|
+
id: AuthIdentifier;
|
|
26
|
+
login: string;
|
|
27
|
+
displayName: string;
|
|
28
|
+
}
|
|
29
|
+
export interface StoredPasskeyCredential {
|
|
30
|
+
userId: AuthIdentifier;
|
|
31
|
+
credentialId: Buffer;
|
|
32
|
+
publicKey: Buffer;
|
|
33
|
+
counter: number;
|
|
34
|
+
transports?: AuthenticatorTransportFuture[];
|
|
35
|
+
backedUp: boolean;
|
|
36
|
+
deviceType: CredentialDeviceType;
|
|
37
|
+
label?: string;
|
|
38
|
+
createdDomain?: string;
|
|
39
|
+
createdUserAgent?: string;
|
|
40
|
+
createdBrowser?: string;
|
|
41
|
+
createdOs?: string;
|
|
42
|
+
createdDevice?: string;
|
|
43
|
+
createdIp?: string;
|
|
44
|
+
createdAt?: Date;
|
|
45
|
+
updatedAt?: Date;
|
|
46
|
+
}
|
|
47
|
+
export interface PasskeyStorageAdapter {
|
|
48
|
+
resolveUser(params: {
|
|
49
|
+
userId?: AuthIdentifier;
|
|
50
|
+
login?: string;
|
|
51
|
+
}): Promise<PasskeyUserDescriptor | null>;
|
|
52
|
+
listUserCredentials(userId: AuthIdentifier): Promise<StoredPasskeyCredential[]>;
|
|
53
|
+
deleteCredential(credentialId: Buffer | string): Promise<boolean>;
|
|
54
|
+
findCredentialById(credentialId: Buffer): Promise<StoredPasskeyCredential | null>;
|
|
55
|
+
saveCredential(record: StoredPasskeyCredential): Promise<void>;
|
|
56
|
+
updateCredentialCounter(credentialId: Buffer, counter: number): Promise<void>;
|
|
57
|
+
saveChallenge(record: PasskeyChallengeRecord): Promise<void>;
|
|
58
|
+
getChallenge?(challenge: string): Promise<PasskeyChallengeRecord | null>;
|
|
59
|
+
consumeChallenge(challenge: string): Promise<PasskeyChallengeRecord | null>;
|
|
60
|
+
cleanupChallenges?(now: Date): Promise<void>;
|
|
61
|
+
}
|
|
62
|
+
export interface PasskeyChallengeParams {
|
|
63
|
+
action: 'register' | 'authenticate';
|
|
64
|
+
login?: string;
|
|
65
|
+
userId?: AuthIdentifier;
|
|
66
|
+
}
|
|
67
|
+
export interface PasskeyChallenge extends Record<string, unknown> {
|
|
68
|
+
challenge: string;
|
|
69
|
+
expiresAt?: string | number | Date;
|
|
70
|
+
userId?: AuthIdentifier;
|
|
71
|
+
}
|
|
72
|
+
export interface PasskeyVerificationParams extends Partial<Omit<Token, 'userId'>> {
|
|
73
|
+
expectedChallenge: string;
|
|
74
|
+
login?: string;
|
|
75
|
+
response: Record<string, unknown>;
|
|
76
|
+
userId?: AuthIdentifier;
|
|
77
|
+
userAgent?: string;
|
|
78
|
+
}
|
|
79
|
+
export interface PasskeyVerificationResult extends Record<string, unknown> {
|
|
80
|
+
login?: string;
|
|
81
|
+
tokens?: TokenPair;
|
|
82
|
+
userId?: AuthIdentifier;
|
|
83
|
+
verified: boolean;
|
|
84
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DIALECTS_SUPPORTING_UNSIGNED = void 0;
|
|
4
|
+
exports.integerIdType = integerIdType;
|
|
5
|
+
exports.tableOptions = tableOptions;
|
|
6
|
+
exports.normalizeTablePrefix = normalizeTablePrefix;
|
|
7
|
+
exports.applyTablePrefix = applyTablePrefix;
|
|
8
|
+
exports.encodeStringArray = encodeStringArray;
|
|
9
|
+
exports.decodeStringArray = decodeStringArray;
|
|
10
|
+
const sequelize_1 = require("sequelize");
|
|
11
|
+
exports.DIALECTS_SUPPORTING_UNSIGNED = new Set(['mysql', 'mariadb']);
|
|
12
|
+
function integerIdType(sequelize) {
|
|
13
|
+
return exports.DIALECTS_SUPPORTING_UNSIGNED.has(sequelize.getDialect()) ? sequelize_1.DataTypes.INTEGER.UNSIGNED : sequelize_1.DataTypes.INTEGER;
|
|
14
|
+
}
|
|
15
|
+
function tableOptions(sequelize, tableName, tablePrefix, extra) {
|
|
16
|
+
const opts = { sequelize, tableName: applyTablePrefix(tablePrefix, tableName) };
|
|
17
|
+
if (extra) {
|
|
18
|
+
Object.assign(opts, extra);
|
|
19
|
+
}
|
|
20
|
+
if (exports.DIALECTS_SUPPORTING_UNSIGNED.has(sequelize.getDialect())) {
|
|
21
|
+
opts.charset = 'utf8mb4';
|
|
22
|
+
opts.collate = 'utf8mb4_unicode_ci';
|
|
23
|
+
}
|
|
24
|
+
return opts;
|
|
25
|
+
}
|
|
26
|
+
function normalizeTablePrefix(prefix) {
|
|
27
|
+
if (!prefix) {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
const trimmed = prefix.trim();
|
|
31
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
32
|
+
}
|
|
33
|
+
function applyTablePrefix(prefix, tableName) {
|
|
34
|
+
const normalized = normalizeTablePrefix(prefix);
|
|
35
|
+
return normalized ? `${normalized}${tableName}` : tableName;
|
|
36
|
+
}
|
|
37
|
+
function encodeStringArray(values) {
|
|
38
|
+
return JSON.stringify(values ?? []);
|
|
39
|
+
}
|
|
40
|
+
function decodeStringArray(raw) {
|
|
41
|
+
if (!raw) {
|
|
42
|
+
return [];
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
const parsed = JSON.parse(raw);
|
|
46
|
+
if (Array.isArray(parsed)) {
|
|
47
|
+
return parsed.filter((entry) => typeof entry === 'string' && entry.length > 0);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
// Malformed JSON — return empty rather than guessing via whitespace split.
|
|
52
|
+
// A whitespace-split fallback could silently grant unintended permissions
|
|
53
|
+
// if a scope/role column contains a corrupted value like "admin user".
|
|
54
|
+
}
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { DataTypes, type InitOptions, type Model, type Sequelize } from 'sequelize';
|
|
2
|
+
export declare const DIALECTS_SUPPORTING_UNSIGNED: Set<string>;
|
|
3
|
+
export declare function integerIdType(sequelize: Sequelize): DataTypes.IntegerDataTypeConstructor;
|
|
4
|
+
export declare function tableOptions<ModelType extends Model>(sequelize: Sequelize, tableName: string, tablePrefix?: string, extra?: Partial<InitOptions<ModelType>>): InitOptions<ModelType>;
|
|
5
|
+
export declare function normalizeTablePrefix(prefix?: string): string | undefined;
|
|
6
|
+
export declare function applyTablePrefix(prefix: string | undefined, tableName: string): string;
|
|
7
|
+
export declare function encodeStringArray(values: string[] | undefined): string;
|
|
8
|
+
export declare function decodeStringArray(raw: string | null | undefined): string[];
|