@astratra/security 1.12.1 → 1.13.0
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/README.md +83 -0
- package/package.json +1 -1
- package/src/deviceSignatures.js +229 -0
- package/src/index.d.ts +43 -0
- package/src/index.js +2 -1
package/README.md
CHANGED
|
@@ -864,6 +864,89 @@ Ce qui est garanti, et testé :
|
|
|
864
864
|
fournisseur OpenID Connect ; `fetch` et `now` s'injectent pour les tests (faux
|
|
865
865
|
JWKS signé localement, jamais le vrai réseau).
|
|
866
866
|
|
|
867
|
+
## Requêtes signées par la puce du téléphone (sans connexion)
|
|
868
|
+
|
|
869
|
+
Une app qui s'ouvre **sans écran de connexion**, mais ne répond qu'aux
|
|
870
|
+
téléphones qu'elle connaît. Le téléphone crée une paire de clés P-256 **dans sa
|
|
871
|
+
puce de sécurité** (Secure Enclave sur iPhone) : la clé privée n'en sort
|
|
872
|
+
jamais. Chaque requête porte une signature de ce qu'elle dit (méthode, chemin,
|
|
873
|
+
heure, nonce, empreinte du corps). Le serveur ne garde que la clé publique :
|
|
874
|
+
une copie de sa base ne signe rien.
|
|
875
|
+
|
|
876
|
+
Deux clés par appareil :
|
|
877
|
+
|
|
878
|
+
- la **clé d'appareil** signe chaque requête, sans rien demander ;
|
|
879
|
+
- la **clé Face ID** est créée par l'app avec un contrôle d'accès qui fait
|
|
880
|
+
refuser à la puce toute signature sans Face ID ou empreinte. Une route qui
|
|
881
|
+
l'exige reçoit une signature que la puce n'a produite qu'après la
|
|
882
|
+
vérification. Le serveur vérifie la clé, le téléphone garantit le contrôle.
|
|
883
|
+
|
|
884
|
+
```js
|
|
885
|
+
const { createDeviceSignatureVerifier, createMemoryDeviceStore } = require('@astratra/security');
|
|
886
|
+
|
|
887
|
+
const appareils = createDeviceSignatureVerifier({
|
|
888
|
+
store: monStoreEnBase, // getDevice, countDevices, addDevice, revokeDevice, spendNonce (atomique)
|
|
889
|
+
maxDevices: 1 // le premier téléphone devient le seul ; l'enregistrement se ferme
|
|
890
|
+
});
|
|
891
|
+
|
|
892
|
+
app.use(express.raw({ type: '*/*' })); // la signature porte sur le corps BRUT
|
|
893
|
+
app.post('/appareil', async (req, res) => {
|
|
894
|
+
const { id, publicKey, biometricPublicKey, biometricSignature } = JSON.parse(req.body);
|
|
895
|
+
try {
|
|
896
|
+
await appareils.enroll({ method: req.method, path: req.originalUrl, headers: req.headers, body: req.body },
|
|
897
|
+
{ id, publicKey, biometricPublicKey, biometricSignature });
|
|
898
|
+
res.status(201).json({ ok: true });
|
|
899
|
+
} catch { res.status(404).end(); }
|
|
900
|
+
});
|
|
901
|
+
app.get('/conversation', appareils.middleware({ rejectStatus: 404 }), lireConversation);
|
|
902
|
+
app.post('/arret-urgence', appareils.middleware({ requireBiometric: true, rejectStatus: 404 }), arreter);
|
|
903
|
+
```
|
|
904
|
+
|
|
905
|
+
Les en-têtes : `x-device-id`, `x-device-time` (millisecondes), `x-device-nonce`
|
|
906
|
+
(16 à 128 caractères), `x-device-signature` (base64, DER ou brut 64 octets),
|
|
907
|
+
`x-device-key` (`device` ou `biometric`). Le texte signé est
|
|
908
|
+
`MÉTHODE\nchemin\nheure\nnonce\nsha256(corps) en base64url` — donné par
|
|
909
|
+
`canonicalDeviceRequest`.
|
|
910
|
+
|
|
911
|
+
Côté iPhone (Swift), les deux clés et une signature :
|
|
912
|
+
|
|
913
|
+
```swift
|
|
914
|
+
import Security
|
|
915
|
+
import LocalAuthentication
|
|
916
|
+
|
|
917
|
+
func cleDansLaPuce(tag: String, faceID: Bool) throws -> SecKey {
|
|
918
|
+
var flags: SecAccessControlCreateFlags = [.privateKeyUsage]
|
|
919
|
+
if faceID { flags.insert(.biometryCurrentSet) }
|
|
920
|
+
let acces = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, flags, nil)!
|
|
921
|
+
let attributs: [String: Any] = [
|
|
922
|
+
kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
|
|
923
|
+
kSecAttrKeySizeInBits as String: 256,
|
|
924
|
+
kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave,
|
|
925
|
+
kSecPrivateKeyAttrs as String: [kSecAttrIsPermanent as String: true,
|
|
926
|
+
kSecAttrApplicationTag as String: Data(tag.utf8),
|
|
927
|
+
kSecAttrAccessControl as String: acces]
|
|
928
|
+
]
|
|
929
|
+
var erreur: Unmanaged<CFError>?
|
|
930
|
+
guard let cle = SecKeyCreateRandomKey(attributs as CFDictionary, &erreur) else { throw erreur!.takeRetainedValue() }
|
|
931
|
+
return cle
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
// Clé publique à envoyer à l'enregistrement : les 65 octets bruts, en base64.
|
|
935
|
+
let publique = SecKeyCopyExternalRepresentation(SecKeyCopyPublicKey(cle)!, nil)! as Data
|
|
936
|
+
|
|
937
|
+
// Signature d'une requête (DER, ce que le serveur attend).
|
|
938
|
+
let signature = SecKeyCreateSignature(cle, .ecdsaSignatureMessageX962SHA256, Data(texteSigne.utf8) as CFData, nil)! as Data
|
|
939
|
+
```
|
|
940
|
+
|
|
941
|
+
Les règles, chacune vérifiée par les tests : une signature de plus de
|
|
942
|
+
`maxSkewMs` (60 s) est refusée ; un nonce ne sert qu'une fois, même une seconde
|
|
943
|
+
après ; un octet changé dans le corps casse la signature ; l'enregistrement
|
|
944
|
+
prouve qu'on détient les clés ; une fausse signature ne grille pas le nonce du
|
|
945
|
+
vrai téléphone ; un appareil révoqué est refusé ; et chaque refus a la **même**
|
|
946
|
+
réponse, pour qu'un curieux n'apprenne rien. En production, `spendNonce` doit
|
|
947
|
+
être atomique (une insertion qui échoue sur un doublon), sinon deux serveurs
|
|
948
|
+
acceptent chacun le même rejeu.
|
|
949
|
+
|
|
867
950
|
## Tests
|
|
868
951
|
|
|
869
952
|
```bash
|
package/package.json
CHANGED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Requests signed by a phone's secure chip (Secure Enclave on iPhone, StrongBox
|
|
3
|
+
* on Android): an app that opens without any sign-in screen, yet answers only
|
|
4
|
+
* the devices it knows.
|
|
5
|
+
*
|
|
6
|
+
* The phone makes a P-256 key pair INSIDE its chip; the private key never
|
|
7
|
+
* leaves it. Every request carries a signature of what it says (method, path,
|
|
8
|
+
* time, a nonce, a fingerprint of the body). The server keeps only the public
|
|
9
|
+
* key, so a copy of its database signs nothing.
|
|
10
|
+
*
|
|
11
|
+
* Two keys per device:
|
|
12
|
+
* - the DEVICE key signs every request, silently;
|
|
13
|
+
* - the BIOMETRIC key is created by the app with an access control that makes
|
|
14
|
+
* the chip refuse to sign without Face ID / a fingerprint. A route that
|
|
15
|
+
* requires it gets a signature the chip produced only after a biometric
|
|
16
|
+
* check. The server verifies the key, the phone guarantees the check.
|
|
17
|
+
*
|
|
18
|
+
* The rules, each one enforced below:
|
|
19
|
+
* - a signature older (or further in the future) than `maxSkewMs` is refused;
|
|
20
|
+
* - a nonce is spent once (`store.spendNonce`, atomic): a captured request
|
|
21
|
+
* replayed even a second later is refused;
|
|
22
|
+
* - the body is part of what is signed: a changed byte breaks the signature;
|
|
23
|
+
* - enrolment can be capped (`maxDevices`): with 1, the first phone becomes
|
|
24
|
+
* the only one and enrolment closes for good — "the one device" pattern;
|
|
25
|
+
* - enrolment proves possession: the new keys must sign the enrolment itself;
|
|
26
|
+
* - every refusal is the SAME answer, so a prober learns nothing.
|
|
27
|
+
*/
|
|
28
|
+
const crypto = require('crypto');
|
|
29
|
+
|
|
30
|
+
const HEADER = {
|
|
31
|
+
device: 'x-device-id',
|
|
32
|
+
time: 'x-device-time',
|
|
33
|
+
nonce: 'x-device-nonce',
|
|
34
|
+
signature: 'x-device-signature',
|
|
35
|
+
key: 'x-device-key'
|
|
36
|
+
};
|
|
37
|
+
/* The DER header of a P-256 SubjectPublicKeyInfo: prepended to the 65-byte raw point iOS exports. */
|
|
38
|
+
const P256_SPKI_PREFIX = Buffer.from('3059301306072a8648ce3d020106082a8648ce3d030107034200', 'hex');
|
|
39
|
+
const NONCE = /^[A-Za-z0-9_-]{16,128}$/;
|
|
40
|
+
const DEVICE_ID = /^[A-Za-z0-9_-]{8,128}$/;
|
|
41
|
+
|
|
42
|
+
class DeviceSignatureError extends Error {
|
|
43
|
+
constructor(code) { super(code); this.code = code; this.name = 'DeviceSignatureError'; }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* A public key as a phone hands it over: the raw uncompressed point (65 bytes,
|
|
48
|
+
* what SecKeyCopyExternalRepresentation gives), an SPKI DER, or a PEM.
|
|
49
|
+
*/
|
|
50
|
+
function importPublicKey(value) {
|
|
51
|
+
if (typeof value !== 'string' || !value.trim()) throw new DeviceSignatureError('bad_key');
|
|
52
|
+
let key;
|
|
53
|
+
try {
|
|
54
|
+
if (value.includes('BEGIN PUBLIC KEY')) key = crypto.createPublicKey(value);
|
|
55
|
+
else {
|
|
56
|
+
const bytes = Buffer.from(value, 'base64');
|
|
57
|
+
const der = bytes.length === 65 && bytes[0] === 0x04 ? Buffer.concat([P256_SPKI_PREFIX, bytes]) : bytes;
|
|
58
|
+
key = crypto.createPublicKey({ key: der, format: 'der', type: 'spki' });
|
|
59
|
+
}
|
|
60
|
+
} catch {
|
|
61
|
+
throw new DeviceSignatureError('bad_key');
|
|
62
|
+
}
|
|
63
|
+
if (key.asymmetricKeyType !== 'ec' || key.asymmetricKeyDetails?.namedCurve !== 'prime256v1') throw new DeviceSignatureError('bad_key');
|
|
64
|
+
return key.export({ type: 'spki', format: 'pem' }).toString();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** What is signed, byte for byte the same on the phone and on the server. */
|
|
68
|
+
function canonicalRequest({ method, path, time, nonce, body }) {
|
|
69
|
+
const digest = crypto.createHash('sha256').update(body === undefined || body === null ? '' : body).digest('base64url');
|
|
70
|
+
return [String(method).toUpperCase(), path, String(time), nonce, digest].join('\n');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Accepts the chip's DER (X9.62) signature, or the 64-byte raw form. */
|
|
74
|
+
function verifySignature(publicKeyPem, data, signatureB64) {
|
|
75
|
+
let signature;
|
|
76
|
+
try { signature = Buffer.from(String(signatureB64), 'base64'); } catch { return false; }
|
|
77
|
+
if (!signature.length) return false;
|
|
78
|
+
const dsaEncoding = signature.length === 64 ? 'ieee-p1363' : 'der';
|
|
79
|
+
try {
|
|
80
|
+
return crypto.verify('sha256', Buffer.from(data), { key: publicKeyPem, dsaEncoding }, signature);
|
|
81
|
+
} catch {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* In-memory store: one process, for development and tests. In production give
|
|
88
|
+
* a store backed by your database — `spendNonce` MUST be atomic (an INSERT
|
|
89
|
+
* that fails on a duplicate), or two servers each accept the same replay.
|
|
90
|
+
*/
|
|
91
|
+
function createMemoryDeviceStore() {
|
|
92
|
+
const devices = new Map();
|
|
93
|
+
const nonces = new Map();
|
|
94
|
+
return {
|
|
95
|
+
async getDevice(id) { return devices.get(id) || null; },
|
|
96
|
+
async countDevices() { return [...devices.values()].filter((d) => !d.revokedAt).length; },
|
|
97
|
+
async addDevice(device) { if (devices.has(device.id)) return false; devices.set(device.id, { ...device }); return true; },
|
|
98
|
+
async revokeDevice(id, at) { const d = devices.get(id); if (d) d.revokedAt = at; return Boolean(d); },
|
|
99
|
+
async spendNonce(deviceId, nonce, expiresAt) {
|
|
100
|
+
const now = Date.now();
|
|
101
|
+
for (const [k, exp] of nonces) if (exp < now) nonces.delete(k);
|
|
102
|
+
const key = `${deviceId}:${nonce}`;
|
|
103
|
+
if (nonces.has(key)) return false;
|
|
104
|
+
nonces.set(key, expiresAt);
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* @param {object} options
|
|
112
|
+
* @param {object} options.store getDevice, countDevices, addDevice, revokeDevice, spendNonce (see createMemoryDeviceStore).
|
|
113
|
+
* @param {number} [options.maxSkewMs=60000] How far a signature's time may be from the server's.
|
|
114
|
+
* @param {number|null} [options.maxDevices=null] Cap on enrolled devices (1: the one-device pattern).
|
|
115
|
+
* @param {Function} [options.now]
|
|
116
|
+
*/
|
|
117
|
+
function createDeviceSignatureVerifier(options = {}) {
|
|
118
|
+
const store = options.store;
|
|
119
|
+
for (const method of ['getDevice', 'countDevices', 'addDevice', 'revokeDevice', 'spendNonce']) {
|
|
120
|
+
if (!store || typeof store[method] !== 'function') throw new Error(`createDeviceSignatureVerifier requires options.store.${method}.`);
|
|
121
|
+
}
|
|
122
|
+
const maxSkewMs = options.maxSkewMs ?? 60_000;
|
|
123
|
+
const maxDevices = options.maxDevices ?? null;
|
|
124
|
+
const now = options.now || Date.now;
|
|
125
|
+
|
|
126
|
+
function readHeaders(headers) {
|
|
127
|
+
const get = (name) => {
|
|
128
|
+
const v = headers?.[name] ?? headers?.[name.toLowerCase()];
|
|
129
|
+
return Array.isArray(v) ? v[0] : v;
|
|
130
|
+
};
|
|
131
|
+
return {
|
|
132
|
+
deviceId: get(HEADER.device), time: Number(get(HEADER.time)), nonce: get(HEADER.nonce),
|
|
133
|
+
signature: get(HEADER.signature), keyKind: get(HEADER.key) === 'biometric' ? 'biometric' : 'device'
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function checkFreshness(deviceId, time, nonce) {
|
|
138
|
+
if (!Number.isFinite(time) || Math.abs(now() - time) > maxSkewMs) throw new DeviceSignatureError('stale');
|
|
139
|
+
if (typeof nonce !== 'string' || !NONCE.test(nonce)) throw new DeviceSignatureError('bad_nonce');
|
|
140
|
+
if (!(await store.spendNonce(deviceId, nonce, now() + 2 * maxSkewMs))) throw new DeviceSignatureError('replay');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Verifies one request. Returns { device, biometric } or throws DeviceSignatureError
|
|
145
|
+
* (code: unknown_device, stale, bad_nonce, replay, bad_signature, biometric_required, revoked).
|
|
146
|
+
* @param {{ method: string, path: string, headers: object, body?: string|Buffer }} request body: the RAW bytes.
|
|
147
|
+
* @param {{ requireBiometric?: boolean }} [rules]
|
|
148
|
+
*/
|
|
149
|
+
async function verify(request, rules = {}) {
|
|
150
|
+
const h = readHeaders(request.headers);
|
|
151
|
+
if (typeof h.deviceId !== 'string' || !DEVICE_ID.test(h.deviceId)) throw new DeviceSignatureError('unknown_device');
|
|
152
|
+
const device = await store.getDevice(h.deviceId);
|
|
153
|
+
if (!device) throw new DeviceSignatureError('unknown_device');
|
|
154
|
+
if (device.revokedAt) throw new DeviceSignatureError('revoked');
|
|
155
|
+
if (rules.requireBiometric && h.keyKind !== 'biometric') throw new DeviceSignatureError('biometric_required');
|
|
156
|
+
const publicKey = h.keyKind === 'biometric' ? device.biometricPublicKey : device.publicKey;
|
|
157
|
+
if (!publicKey) throw new DeviceSignatureError('biometric_required');
|
|
158
|
+
const data = canonicalRequest({ method: request.method, path: request.path, time: h.time, nonce: h.nonce, body: request.body });
|
|
159
|
+
if (!verifySignature(publicKey, data, h.signature)) throw new DeviceSignatureError('bad_signature');
|
|
160
|
+
/* The nonce is spent only once the signature is good: a forger cannot burn a real phone's nonces. */
|
|
161
|
+
await checkFreshness(h.deviceId, h.time, h.nonce);
|
|
162
|
+
return { device: { id: device.id, label: device.label ?? null }, biometric: h.keyKind === 'biometric' };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Enrols a device. The enrolment request is itself signed by the new device key
|
|
167
|
+
* (and, when given, a second signature by the biometric key in `biometricSignature`):
|
|
168
|
+
* proof that the caller holds both private keys.
|
|
169
|
+
* @param {{ method: string, path: string, headers: object, body?: string|Buffer }} request
|
|
170
|
+
* @param {{ id: string, publicKey: string, biometricPublicKey?: string, label?: string, biometricSignature?: string }} enrolment
|
|
171
|
+
* @returns {Promise<{ id: string }>} or throws DeviceSignatureError (closed, exists, bad_key, bad_signature, stale, replay).
|
|
172
|
+
*/
|
|
173
|
+
async function enroll(request, enrolment) {
|
|
174
|
+
if (!enrolment || typeof enrolment.id !== 'string' || !DEVICE_ID.test(enrolment.id)) throw new DeviceSignatureError('bad_request');
|
|
175
|
+
if (maxDevices !== null && (await store.countDevices()) >= maxDevices) throw new DeviceSignatureError('closed');
|
|
176
|
+
const publicKey = importPublicKey(enrolment.publicKey);
|
|
177
|
+
const biometricPublicKey = enrolment.biometricPublicKey ? importPublicKey(enrolment.biometricPublicKey) : null;
|
|
178
|
+
const h = readHeaders(request.headers);
|
|
179
|
+
if (h.deviceId !== enrolment.id) throw new DeviceSignatureError('bad_request');
|
|
180
|
+
const data = canonicalRequest({ method: request.method, path: request.path, time: h.time, nonce: h.nonce, body: request.body });
|
|
181
|
+
if (!verifySignature(publicKey, data, h.signature)) throw new DeviceSignatureError('bad_signature');
|
|
182
|
+
if (biometricPublicKey && !verifySignature(biometricPublicKey, data, enrolment.biometricSignature)) throw new DeviceSignatureError('bad_signature');
|
|
183
|
+
await checkFreshness(enrolment.id, h.time, h.nonce);
|
|
184
|
+
const added = await store.addDevice({ id: enrolment.id, publicKey, biometricPublicKey, label: enrolment.label ?? null, enrolledAt: now(), revokedAt: null });
|
|
185
|
+
if (!added) throw new DeviceSignatureError('exists');
|
|
186
|
+
/* Two phones racing for the last place: the store let both in; the later one is undone. */
|
|
187
|
+
if (maxDevices !== null && (await store.countDevices()) > maxDevices) {
|
|
188
|
+
await store.revokeDevice(enrolment.id, now());
|
|
189
|
+
throw new DeviceSignatureError('closed');
|
|
190
|
+
}
|
|
191
|
+
return { id: enrolment.id };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Whether a new device could still enrol. */
|
|
195
|
+
async function enrollmentOpen() {
|
|
196
|
+
return maxDevices === null || (await store.countDevices()) < maxDevices;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Express middleware: sets req.device, or answers `rejectStatus` (default 401;
|
|
201
|
+
* 404 to look like a service that does not exist). Needs the RAW body: mount
|
|
202
|
+
* express.raw() (or keep req.rawBody) before it.
|
|
203
|
+
*/
|
|
204
|
+
function middleware({ requireBiometric = false, rejectStatus = 401 } = {}) {
|
|
205
|
+
return async (req, res, next) => {
|
|
206
|
+
try {
|
|
207
|
+
const body = Buffer.isBuffer(req.body) ? req.body : req.rawBody ?? (typeof req.body === 'string' ? req.body : '');
|
|
208
|
+
const result = await verify({ method: req.method, path: req.originalUrl || req.url, headers: req.headers, body }, { requireBiometric });
|
|
209
|
+
req.device = result.device;
|
|
210
|
+
req.deviceBiometric = result.biometric;
|
|
211
|
+
next();
|
|
212
|
+
} catch (error) {
|
|
213
|
+
if (!(error instanceof DeviceSignatureError)) return next(error);
|
|
214
|
+
res.status(rejectStatus).json({ message: rejectStatus === 404 ? 'Not found.' : 'Unauthorized.' });
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return { verify, enroll, enrollmentOpen, middleware, revoke: (id) => store.revokeDevice(id, now()) };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
module.exports = {
|
|
223
|
+
createDeviceSignatureVerifier,
|
|
224
|
+
createMemoryDeviceStore,
|
|
225
|
+
canonicalDeviceRequest: canonicalRequest,
|
|
226
|
+
importDevicePublicKey: importPublicKey,
|
|
227
|
+
DeviceSignatureError,
|
|
228
|
+
DEVICE_SIGNATURE_HEADERS: HEADER
|
|
229
|
+
};
|
package/src/index.d.ts
CHANGED
|
@@ -948,3 +948,46 @@ export const GOOGLE_JWKS_URL: string;
|
|
|
948
948
|
export const GOOGLE_ISSUERS: string[];
|
|
949
949
|
export const APPLE_JWKS_URL: string;
|
|
950
950
|
export const APPLE_ISSUERS: string[];
|
|
951
|
+
|
|
952
|
+
/** One enrolled phone: public keys only, never a private key. */
|
|
953
|
+
export interface EnrolledDevice {
|
|
954
|
+
id: string;
|
|
955
|
+
publicKey: string;
|
|
956
|
+
biometricPublicKey: string | null;
|
|
957
|
+
label: string | null;
|
|
958
|
+
enrolledAt: number;
|
|
959
|
+
revokedAt: number | null;
|
|
960
|
+
}
|
|
961
|
+
export interface DeviceStore {
|
|
962
|
+
getDevice(id: string): Promise<EnrolledDevice | null>;
|
|
963
|
+
/** Devices not revoked. */
|
|
964
|
+
countDevices(): Promise<number>;
|
|
965
|
+
/** false when the id already exists. */
|
|
966
|
+
addDevice(device: EnrolledDevice): Promise<boolean>;
|
|
967
|
+
revokeDevice(id: string, at: number): Promise<boolean>;
|
|
968
|
+
/** MUST be atomic: false when this nonce was already spent by this device. */
|
|
969
|
+
spendNonce(deviceId: string, nonce: string, expiresAt: number): Promise<boolean>;
|
|
970
|
+
}
|
|
971
|
+
export interface SignedDeviceRequest {
|
|
972
|
+
method: string;
|
|
973
|
+
path: string;
|
|
974
|
+
headers: Record<string, string | string[] | undefined>;
|
|
975
|
+
/** The RAW body bytes. */
|
|
976
|
+
body?: string | Buffer;
|
|
977
|
+
}
|
|
978
|
+
export type DeviceSignatureErrorCode = 'unknown_device' | 'revoked' | 'stale' | 'bad_nonce' | 'replay' | 'bad_signature' | 'biometric_required' | 'closed' | 'exists' | 'bad_key' | 'bad_request';
|
|
979
|
+
export class DeviceSignatureError extends Error { code: DeviceSignatureErrorCode; }
|
|
980
|
+
export interface DeviceSignatureVerifier {
|
|
981
|
+
verify(request: SignedDeviceRequest, rules?: { requireBiometric?: boolean }): Promise<{ device: { id: string; label: string | null }; biometric: boolean }>;
|
|
982
|
+
enroll(request: SignedDeviceRequest, enrolment: { id: string; publicKey: string; biometricPublicKey?: string; biometricSignature?: string; label?: string }): Promise<{ id: string }>;
|
|
983
|
+
enrollmentOpen(): Promise<boolean>;
|
|
984
|
+
/** Sets req.device and req.deviceBiometric; needs the raw body (express.raw or req.rawBody). */
|
|
985
|
+
middleware(options?: { requireBiometric?: boolean; rejectStatus?: number }): RequestHandler;
|
|
986
|
+
revoke(id: string): Promise<boolean>;
|
|
987
|
+
}
|
|
988
|
+
export function createDeviceSignatureVerifier(options: { store: DeviceStore; maxSkewMs?: number; maxDevices?: number | null; now?: () => number }): DeviceSignatureVerifier;
|
|
989
|
+
export function createMemoryDeviceStore(): DeviceStore;
|
|
990
|
+
export function canonicalDeviceRequest(parts: { method: string; path: string; time: number | string; nonce: string; body?: string | Buffer | null }): string;
|
|
991
|
+
/** Raw 65-byte point (base64), SPKI DER (base64) or PEM, P-256 only; returns the SPKI PEM. */
|
|
992
|
+
export function importDevicePublicKey(value: string): string;
|
|
993
|
+
export const DEVICE_SIGNATURE_HEADERS: { device: string; time: string; nonce: string; signature: string; key: string };
|