@astratra/wallet 0.1.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/LICENSE +21 -0
- package/README.md +126 -0
- package/package.json +44 -0
- package/src/apple.js +137 -0
- package/src/appleWebService.js +100 -0
- package/src/certificates/apple-wwdr-g4.pem +26 -0
- package/src/credentials.js +108 -0
- package/src/google.js +101 -0
- package/src/index.d.ts +139 -0
- package/src/index.js +17 -0
- package/src/registrations.js +98 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Astratra
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# @astratra/wallet
|
|
2
|
+
|
|
3
|
+
Des cartes de fidélité dans **Apple Wallet** et **Google Wallet**, qui se
|
|
4
|
+
mettent à jour toutes seules. Le client n'installe rien et ne crée aucun
|
|
5
|
+
compte : il touche « Ajouter », la carte vit dans son téléphone, et ton serveur
|
|
6
|
+
la tient à jour.
|
|
7
|
+
|
|
8
|
+
Ce package ne connaît ni tes clients, ni ta base, ni ta règle de fidélité (voir
|
|
9
|
+
`@astratra/loyalty` pour celle-ci). Il signe, publie et rafraîchit des cartes ;
|
|
10
|
+
le contenu vient de toi.
|
|
11
|
+
|
|
12
|
+
## Ce qu'il règle
|
|
13
|
+
|
|
14
|
+
- **La signature Apple** : `.pkpass` signé avec ton certificat Pass Type ID.
|
|
15
|
+
L'identifiant de carte et l'équipe sont **lus dans le certificat**, et le
|
|
16
|
+
certificat intermédiaire WWDR G4 d'Apple est fourni : deux champs à saisir au
|
|
17
|
+
lieu de cinq.
|
|
18
|
+
- **Les mises à jour Apple** : le service web du protocole Apple (inscription
|
|
19
|
+
des appareils, cartes changées, dernière version, désinscription) et la
|
|
20
|
+
notification push vide qui déclenche le rafraîchissement. Les jetons morts
|
|
21
|
+
(400, 410) sont oubliés.
|
|
22
|
+
- **Google** : classe et carte créées au premier envoi puis mises à jour, lien
|
|
23
|
+
« Ajouter à Google Wallet » signé (JWT RS256).
|
|
24
|
+
- **La saisie des clés** : contrôles avant enregistrement (clé qui correspond au
|
|
25
|
+
certificat, certificat non expiré, vrai compte de service Google), et un
|
|
26
|
+
transport hexadécimal pour qu'un PEM traverse un pare-feu applicatif qui
|
|
27
|
+
bloque `--` sans l'affaiblir.
|
|
28
|
+
|
|
29
|
+
## Apple Wallet
|
|
30
|
+
|
|
31
|
+
```js
|
|
32
|
+
const { createApplePasses, createAppleWebServiceRouter, createMongooseRegistrationStore,
|
|
33
|
+
notifyApplePass } = require('@astratra/wallet');
|
|
34
|
+
|
|
35
|
+
const passes = createApplePasses({
|
|
36
|
+
certificate, privateKey, // PEM, depuis tes clés chiffrées
|
|
37
|
+
webServiceURL: 'https://api.exemple.com/api/wallet/apple',
|
|
38
|
+
organizationName: 'Mon salon',
|
|
39
|
+
description: 'Carte de fidélité',
|
|
40
|
+
images: { 'icon.png': icon, 'icon@2x.png': icon2x, 'logo.png': logo, 'logo@2x.png': logo2x },
|
|
41
|
+
colors: { backgroundColor: 'rgb(11, 16, 32)', foregroundColor: 'rgb(242, 245, 251)', labelColor: 'rgb(111, 180, 255)' }
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const pkpass = passes.build({
|
|
45
|
+
serialNumber: 'C-000142',
|
|
46
|
+
authenticationToken: client.carteToken, // 16 caractères minimum
|
|
47
|
+
headerFields: [{ key: 'numero', label: 'CARTE N°', value: 'C-000142' }],
|
|
48
|
+
secondaryFields: [{ key: 'client', label: 'CLIENT', value: 'Karim' }],
|
|
49
|
+
barcode: { message: 'Carte C-000142 · 5 / 7', altText: 'C-000142' },
|
|
50
|
+
images: { 'strip.png': bandeDuMoment } // propre à cette carte
|
|
51
|
+
});
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Le service web, monté sous le `webServiceURL` :
|
|
55
|
+
|
|
56
|
+
```js
|
|
57
|
+
const registrations = createMongooseRegistrationStore(mongoose.connection);
|
|
58
|
+
|
|
59
|
+
app.use('/api/wallet/apple', createAppleWebServiceRouter({
|
|
60
|
+
resolveConfig: async () => (appleConfigure ? { passTypeIdentifier: passes.passTypeIdentifier } : null),
|
|
61
|
+
findPass: async (serial) => clients.parCarte(serial), // { authenticationToken, updatedAt }
|
|
62
|
+
buildPass: async (serial) => passes.build(await contenuDeLaCarte(serial)),
|
|
63
|
+
registrations
|
|
64
|
+
}));
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Après chaque changement (visite validée, récompense accordée…), mets à jour
|
|
68
|
+
`updatedAt` puis préviens les appareils :
|
|
69
|
+
|
|
70
|
+
```js
|
|
71
|
+
await notifyApplePass({ registrations, passTypeIdentifier, serialNumber, certificate, privateKey });
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Google Wallet
|
|
75
|
+
|
|
76
|
+
```js
|
|
77
|
+
const { createGoogleWallet } = require('@astratra/wallet');
|
|
78
|
+
|
|
79
|
+
const google = createGoogleWallet({ issuerId, credentials }); // credentials : JSON du compte de service
|
|
80
|
+
const classId = google.classId('fidelite');
|
|
81
|
+
|
|
82
|
+
await google.ensureClass({ id: classId, issuerName: 'Mon salon', programName: 'Fidélité',
|
|
83
|
+
programLogo: { sourceUri: { uri: 'https://…/logo.png' } }, hexBackgroundColor: '#0b1020' });
|
|
84
|
+
|
|
85
|
+
await google.upsertObject({
|
|
86
|
+
id: google.objectId('C-000142'), classId, state: 'ACTIVE',
|
|
87
|
+
accountId: 'C-000142', accountName: 'Karim',
|
|
88
|
+
loyaltyPoints: { label: 'Prestations', balance: { int: 5 } },
|
|
89
|
+
heroImage: { sourceUri: { uri: 'https://…/bande-5.png' } },
|
|
90
|
+
barcode: { type: 'QR_CODE', value: 'Carte C-000142 · 5 / 7' }
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const lien = google.saveLink([{ id: google.objectId('C-000142'), classId }]);
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Une image référencée par Google doit être **publique** : Google la télécharge
|
|
97
|
+
depuis ses serveurs. Change son URL quand son contenu change, c'est ce qui force
|
|
98
|
+
Google à la rafraîchir.
|
|
99
|
+
|
|
100
|
+
## Saisir les clés depuis l'interface
|
|
101
|
+
|
|
102
|
+
```js
|
|
103
|
+
const { checkAppleCredentials, checkGoogleCredentials, fromHexField } = require('@astratra/wallet');
|
|
104
|
+
|
|
105
|
+
const certificate = fromHexField(req.body.certificate); // l'interface envoie toHexField(pem)
|
|
106
|
+
const privateKey = fromHexField(req.body.privateKey);
|
|
107
|
+
const verdict = checkAppleCredentials({ certificate, privateKey });
|
|
108
|
+
if (!verdict.ok) return res.status(400).json({ message: verdict.reason });
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
À combiner avec `@astratra/credentials` pour stocker le certificat et la clé
|
|
112
|
+
chiffrés, et les relire à chaque usage : une clé changée prend effet sans
|
|
113
|
+
redémarrage.
|
|
114
|
+
|
|
115
|
+
## À savoir
|
|
116
|
+
|
|
117
|
+
- **Google démarre en mode démo** : seuls le propriétaire de la console et les
|
|
118
|
+
comptes testeurs voient les cartes. La publication demande un profil de
|
|
119
|
+
paiement Entreprise et une validation de Google (quelques jours).
|
|
120
|
+
- **Apple n'a pas de validation** : un certificat valide suffit.
|
|
121
|
+
- **Le certificat Pass Type ID expire au bout d'un an et un mois** : au-delà,
|
|
122
|
+
les cartes déjà ajoutées ne se mettent plus à jour. `readPassCertificate`
|
|
123
|
+
donne la date, affiche-la.
|
|
124
|
+
- **Badges** : dans un e-mail ou une page, utilise les badges officiels
|
|
125
|
+
(« Ajouter à l'app Cartes Apple », « Ajouter au Google Wallet »), téléchargés
|
|
126
|
+
depuis les kits de marque d'Apple et de Google.
|
package/package.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@astratra/wallet",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Apple Wallet and Google Wallet loyalty cards: signed passes, live updates, add-to-wallet links.",
|
|
5
|
+
"engines": {
|
|
6
|
+
"node": ">=20"
|
|
7
|
+
},
|
|
8
|
+
"main": "src/index.js",
|
|
9
|
+
"types": "src/index.d.ts",
|
|
10
|
+
"type": "commonjs",
|
|
11
|
+
"files": [
|
|
12
|
+
"src"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"test": "jest"
|
|
16
|
+
},
|
|
17
|
+
"jest": {
|
|
18
|
+
"testMatch": [
|
|
19
|
+
"**/__tests__/**/*.test.js"
|
|
20
|
+
]
|
|
21
|
+
},
|
|
22
|
+
"keywords": [
|
|
23
|
+
"astratra",
|
|
24
|
+
"wallet",
|
|
25
|
+
"apple-wallet",
|
|
26
|
+
"google-wallet",
|
|
27
|
+
"pkpass",
|
|
28
|
+
"loyalty"
|
|
29
|
+
],
|
|
30
|
+
"license": "MIT",
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@astratra/core": "^1.1.0",
|
|
36
|
+
"express": "^4.18.3",
|
|
37
|
+
"google-auth-library": "^11.1.0",
|
|
38
|
+
"passkit-generator": "^3.6.1"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"jest": "30.4.2",
|
|
42
|
+
"supertest": "^7.0.0"
|
|
43
|
+
}
|
|
44
|
+
}
|
package/src/apple.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
const http2 = require('node:http2');
|
|
2
|
+
const { PKPass } = require('passkit-generator');
|
|
3
|
+
const { APPLE_WWDR_G4, readPassCertificate } = require('./credentials');
|
|
4
|
+
|
|
5
|
+
const APNS_PRODUCTION = 'https://api.push.apple.com';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Fabrique de cartes Apple Wallet (storeCard par défaut), signées avec le
|
|
9
|
+
* certificat Pass Type ID de l'émetteur.
|
|
10
|
+
*
|
|
11
|
+
* L'identifiant de carte et l'équipe se lisent dans le certificat. Le style
|
|
12
|
+
* (couleurs, logo) est celui de l'émetteur ; le contenu (champs, bande, QR)
|
|
13
|
+
* change d'une carte à l'autre.
|
|
14
|
+
*
|
|
15
|
+
* @param {object} options
|
|
16
|
+
* @param {string} options.certificate certificat Pass Type ID (PEM).
|
|
17
|
+
* @param {string} options.privateKey clé privée associée (PEM).
|
|
18
|
+
* @param {string} [options.passphrase]
|
|
19
|
+
* @param {string} [options.wwdr] certificat intermédiaire ; WWDR G4 par défaut.
|
|
20
|
+
* @param {string} options.webServiceURL base du service web de mise à jour (…/v1 ajouté par Apple).
|
|
21
|
+
* @param {string} options.organizationName
|
|
22
|
+
* @param {string} options.description
|
|
23
|
+
* @param {Record<string, Buffer>} options.images images communes : icon.png, icon@2x.png, logo.png…
|
|
24
|
+
* @param {{foregroundColor?: string, backgroundColor?: string, labelColor?: string}} [options.colors]
|
|
25
|
+
* @param {'storeCard'|'generic'|'coupon'|'eventTicket'} [options.type='storeCard']
|
|
26
|
+
*/
|
|
27
|
+
function createApplePasses({
|
|
28
|
+
certificate, privateKey, passphrase, wwdr = APPLE_WWDR_G4, webServiceURL,
|
|
29
|
+
organizationName, description, images = {}, colors = {}, type = 'storeCard', logoText
|
|
30
|
+
}) {
|
|
31
|
+
const lu = readPassCertificate(certificate);
|
|
32
|
+
if (!lu?.passTypeIdentifier || !lu.teamIdentifier) {
|
|
33
|
+
throw new Error('Certificat Pass Type ID illisible ou incomplet.');
|
|
34
|
+
}
|
|
35
|
+
const { passTypeIdentifier, teamIdentifier } = lu;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param {object} card
|
|
39
|
+
* @param {string} card.serialNumber
|
|
40
|
+
* @param {string} card.authenticationToken au moins 16 caractères (exigence Apple).
|
|
41
|
+
* @param {Array<object>} [card.headerFields] … et primaryFields, secondaryFields, auxiliaryFields, backFields
|
|
42
|
+
* @param {{message: string, altText?: string, format?: string}} [card.barcode]
|
|
43
|
+
* @param {Record<string, Buffer>} [card.images] images propres à cette carte (strip.png…), prioritaires.
|
|
44
|
+
* @returns {Buffer} le .pkpass
|
|
45
|
+
*/
|
|
46
|
+
function build(card) {
|
|
47
|
+
const pass = new PKPass(
|
|
48
|
+
{ ...images, ...(card.images || {}) },
|
|
49
|
+
{ wwdr, signerCert: certificate, signerKey: privateKey, signerKeyPassphrase: passphrase },
|
|
50
|
+
{
|
|
51
|
+
formatVersion: 1,
|
|
52
|
+
passTypeIdentifier,
|
|
53
|
+
teamIdentifier,
|
|
54
|
+
serialNumber: card.serialNumber,
|
|
55
|
+
organizationName,
|
|
56
|
+
description,
|
|
57
|
+
...(logoText ? { logoText } : {}),
|
|
58
|
+
...colors,
|
|
59
|
+
webServiceURL,
|
|
60
|
+
authenticationToken: card.authenticationToken
|
|
61
|
+
}
|
|
62
|
+
);
|
|
63
|
+
pass.type = type;
|
|
64
|
+
for (const zone of ['headerFields', 'primaryFields', 'secondaryFields', 'auxiliaryFields', 'backFields']) {
|
|
65
|
+
for (const field of card[zone] || []) pass[zone].push(field);
|
|
66
|
+
}
|
|
67
|
+
if (card.barcode) {
|
|
68
|
+
pass.setBarcodes({
|
|
69
|
+
format: card.barcode.format || 'PKBarcodeFormatQR',
|
|
70
|
+
message: card.barcode.message,
|
|
71
|
+
messageEncoding: 'utf-8',
|
|
72
|
+
...(card.barcode.altText ? { altText: card.barcode.altText } : {})
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return pass.getAsBuffer();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return { passTypeIdentifier, teamIdentifier, expiresAt: lu.expiresAt, build };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Prévient un appareil qu'une carte a changé : Apple Wallet revient alors
|
|
83
|
+
* chercher la nouvelle version auprès du service web. La notification est
|
|
84
|
+
* vide par conception (Apple l'exige).
|
|
85
|
+
*
|
|
86
|
+
* Rejette avec `error.status` : 400 et 410 veulent dire que le jeton est mort
|
|
87
|
+
* et doit être oublié.
|
|
88
|
+
*/
|
|
89
|
+
function sendApplePassUpdate(pushToken, { certificate, privateKey, passphrase, passTypeIdentifier, connect = http2.connect, host = APNS_PRODUCTION }) {
|
|
90
|
+
return new Promise((resolve, reject) => {
|
|
91
|
+
const session = connect(host, { cert: certificate, key: privateKey, passphrase });
|
|
92
|
+
session.once('error', reject);
|
|
93
|
+
const requete = session.request({
|
|
94
|
+
':method': 'POST',
|
|
95
|
+
':path': `/3/device/${pushToken}`,
|
|
96
|
+
'apns-topic': passTypeIdentifier
|
|
97
|
+
});
|
|
98
|
+
let statut;
|
|
99
|
+
requete.on('response', (headers) => { statut = Number(headers[':status']); });
|
|
100
|
+
requete.on('error', reject);
|
|
101
|
+
requete.on('end', () => {
|
|
102
|
+
session.close();
|
|
103
|
+
if (statut >= 200 && statut < 300) resolve(statut);
|
|
104
|
+
else {
|
|
105
|
+
const error = new Error(`APNs a répondu ${statut || 'sans statut'}`);
|
|
106
|
+
error.status = statut;
|
|
107
|
+
reject(error);
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
requete.end('{}');
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Prévient tous les appareils qui portent une carte, et oublie les jetons que
|
|
116
|
+
* Apple déclare morts. Rejette si au moins un envoi a échoué pour une autre
|
|
117
|
+
* raison.
|
|
118
|
+
*/
|
|
119
|
+
async function notifyApplePass({ registrations, passTypeIdentifier, serialNumber, ...apns }) {
|
|
120
|
+
const inscrits = await registrations.listForPass(passTypeIdentifier, serialNumber);
|
|
121
|
+
const resultats = await Promise.allSettled(inscrits.map(async ({ pushToken }) => {
|
|
122
|
+
try {
|
|
123
|
+
await sendApplePassUpdate(pushToken, { ...apns, passTypeIdentifier });
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if ([400, 410].includes(error.status)) {
|
|
126
|
+
await registrations.forgetPushToken(pushToken);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
}));
|
|
132
|
+
const echec = resultats.find((resultat) => resultat.status === 'rejected');
|
|
133
|
+
if (echec) throw echec.reason;
|
|
134
|
+
return inscrits.length;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
module.exports = { createApplePasses, sendApplePassUpdate, notifyApplePass };
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
const express = require('express');
|
|
2
|
+
const { asyncHandler } = require('@astratra/core');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Le service web qu'Apple Wallet appelle pour tenir une carte à jour, selon le
|
|
6
|
+
* protocole d'Apple (monté sous le `webServiceURL` de la carte) :
|
|
7
|
+
*
|
|
8
|
+
* POST /v1/devices/:device/registrations/:passType/:serial inscrire un appareil
|
|
9
|
+
* GET /v1/devices/:device/registrations/:passType cartes changées depuis
|
|
10
|
+
* GET /v1/passes/:passType/:serial dernière version
|
|
11
|
+
* DELETE /v1/devices/:device/registrations/:passType/:serial désinscrire
|
|
12
|
+
* POST /v1/log erreurs remontées par l'appareil
|
|
13
|
+
*
|
|
14
|
+
* Tout ce qui touche à une carte précise exige l'en-tête
|
|
15
|
+
* `Authorization: ApplePass <authenticationToken>` de cette carte.
|
|
16
|
+
*
|
|
17
|
+
* @param {object} options
|
|
18
|
+
* @param {() => Promise<{passTypeIdentifier: string} | null>} options.resolveConfig
|
|
19
|
+
* null tant qu'Apple Wallet n'est pas configuré (503) — relu à chaque appel,
|
|
20
|
+
* pour que des clés changées prennent effet sans redémarrage.
|
|
21
|
+
* @param {(serialNumber: string) => Promise<{authenticationToken: string, updatedAt?: Date|string} | null>} options.findPass
|
|
22
|
+
* @param {(serialNumber: string) => Promise<Buffer>} options.buildPass
|
|
23
|
+
* @param {object} options.registrations voir registrations.js.
|
|
24
|
+
* @param {{warn: Function}} [options.logger=console]
|
|
25
|
+
*/
|
|
26
|
+
function createAppleWebServiceRouter({ resolveConfig, findPass, buildPass, registrations, logger = console }) {
|
|
27
|
+
const router = express.Router();
|
|
28
|
+
|
|
29
|
+
async function contexte(req, res, { authentifier = true } = {}) {
|
|
30
|
+
const config = await resolveConfig();
|
|
31
|
+
if (!config) {
|
|
32
|
+
res.sendStatus(503);
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
if (req.params.passTypeIdentifier !== config.passTypeIdentifier) {
|
|
36
|
+
res.sendStatus(404);
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
if (!req.params.serialNumber) return { config };
|
|
40
|
+
const pass = await findPass(req.params.serialNumber);
|
|
41
|
+
if (!pass) {
|
|
42
|
+
res.sendStatus(404);
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
if (authentifier && req.get('authorization') !== `ApplePass ${pass.authenticationToken}`) {
|
|
46
|
+
res.sendStatus(401);
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
return { config, pass };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
router.post('/v1/devices/:deviceLibraryIdentifier/registrations/:passTypeIdentifier/:serialNumber', asyncHandler(async (req, res) => {
|
|
53
|
+
if (!await contexte(req, res)) return undefined;
|
|
54
|
+
if (!req.body?.pushToken || typeof req.body.pushToken !== 'string') return res.sendStatus(400);
|
|
55
|
+
const { deviceLibraryIdentifier, passTypeIdentifier, serialNumber } = req.params;
|
|
56
|
+
const nouvelle = await registrations.register({ deviceLibraryIdentifier, passTypeIdentifier, serialNumber, pushToken: req.body.pushToken });
|
|
57
|
+
return res.sendStatus(nouvelle ? 201 : 200);
|
|
58
|
+
}));
|
|
59
|
+
|
|
60
|
+
router.get('/v1/devices/:deviceLibraryIdentifier/registrations/:passTypeIdentifier', asyncHandler(async (req, res) => {
|
|
61
|
+
if (!await contexte(req, res)) return undefined;
|
|
62
|
+
const { deviceLibraryIdentifier, passTypeIdentifier } = req.params;
|
|
63
|
+
const inscriptions = await registrations.listForDevice(deviceLibraryIdentifier, passTypeIdentifier);
|
|
64
|
+
const depuis = req.query.passesUpdatedSince ? new Date(req.query.passesUpdatedSince) : new Date(0);
|
|
65
|
+
const cartes = (await Promise.all(inscriptions.map(async ({ serialNumber }) => {
|
|
66
|
+
const pass = await findPass(serialNumber);
|
|
67
|
+
return pass ? { serialNumber, updatedAt: new Date(pass.updatedAt || 0) } : null;
|
|
68
|
+
}))).filter(Boolean);
|
|
69
|
+
const changees = cartes.filter(({ updatedAt }) => Number.isNaN(depuis.getTime()) || updatedAt > depuis);
|
|
70
|
+
if (!changees.length) return res.sendStatus(204);
|
|
71
|
+
return res.json({
|
|
72
|
+
serialNumbers: changees.map(({ serialNumber }) => serialNumber),
|
|
73
|
+
lastUpdated: new Date(Math.max(...changees.map(({ updatedAt }) => updatedAt.getTime()))).toISOString()
|
|
74
|
+
});
|
|
75
|
+
}));
|
|
76
|
+
|
|
77
|
+
router.get('/v1/passes/:passTypeIdentifier/:serialNumber', asyncHandler(async (req, res) => {
|
|
78
|
+
const ctx = await contexte(req, res);
|
|
79
|
+
if (!ctx) return undefined;
|
|
80
|
+
res.type('application/vnd.apple.pkpass');
|
|
81
|
+
res.set('Last-Modified', new Date(ctx.pass.updatedAt || Date.now()).toUTCString());
|
|
82
|
+
return res.send(await buildPass(req.params.serialNumber));
|
|
83
|
+
}));
|
|
84
|
+
|
|
85
|
+
router.delete('/v1/devices/:deviceLibraryIdentifier/registrations/:passTypeIdentifier/:serialNumber', asyncHandler(async (req, res) => {
|
|
86
|
+
if (!await contexte(req, res)) return undefined;
|
|
87
|
+
const { deviceLibraryIdentifier, passTypeIdentifier, serialNumber } = req.params;
|
|
88
|
+
await registrations.unregister({ deviceLibraryIdentifier, passTypeIdentifier, serialNumber });
|
|
89
|
+
return res.sendStatus(200);
|
|
90
|
+
}));
|
|
91
|
+
|
|
92
|
+
router.post('/v1/log', (req, res) => {
|
|
93
|
+
for (const message of req.body?.logs || []) logger.warn(`Apple Wallet: ${String(message)}`);
|
|
94
|
+
res.sendStatus(200);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
return router;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
module.exports = { createAppleWebServiceRouter };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
-----BEGIN CERTIFICATE-----
|
|
2
|
+
MIIEVTCCAz2gAwIBAgIUE9x3lVJx5T3GMujM/+Uh88zFztIwDQYJKoZIhvcNAQEL
|
|
3
|
+
BQAwYjELMAkGA1UEBhMCVVMxEzARBgNVBAoTCkFwcGxlIEluYy4xJjAkBgNVBAsT
|
|
4
|
+
HUFwcGxlIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRYwFAYDVQQDEw1BcHBsZSBS
|
|
5
|
+
b290IENBMB4XDTIwMTIxNjE5MzYwNFoXDTMwMTIxMDAwMDAwMFowdTFEMEIGA1UE
|
|
6
|
+
Aww7QXBwbGUgV29ybGR3aWRlIERldmVsb3BlciBSZWxhdGlvbnMgQ2VydGlmaWNh
|
|
7
|
+
dGlvbiBBdXRob3JpdHkxCzAJBgNVBAsMAkc0MRMwEQYDVQQKDApBcHBsZSBJbmMu
|
|
8
|
+
MQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAf
|
|
9
|
+
eKp6JzKwRl/nF3bYoJ0OKY6tPTKlxGs3yeRBkWq3eXFdDDQEYHX3rkOPR8SGHgjo
|
|
10
|
+
v9Y5Ui8eZ/xx8YJtPH4GUnadLLzVQ+mxtLxAOnhRXVGhJeG+bJGdayFZGEHVD41t
|
|
11
|
+
QSo5SiHgkJ9OE0/QjJoyuNdqkh4laqQyziIZhQVg3AJK8lrrd3kCfcCXVGySjnYB
|
|
12
|
+
5kaP5eYq+6KwrRitbTOFOCOL6oqW7Z+uZk+jDEAnbZXQYojZQykn/e2kv1MukBVl
|
|
13
|
+
PNkuYmQzHWxq3Y4hqqRfFcYw7V/mjDaSlLfcOQIA+2SM1AyB8j/VNJeHdSbCb64D
|
|
14
|
+
YyEMe9QbsWLFApy9/a8CAwEAAaOB7zCB7DASBgNVHRMBAf8ECDAGAQH/AgEAMB8G
|
|
15
|
+
A1UdIwQYMBaAFCvQaUeUdgn+9GuNLkCm90dNfwheMEQGCCsGAQUFBwEBBDgwNjA0
|
|
16
|
+
BggrBgEFBQcwAYYoaHR0cDovL29jc3AuYXBwbGUuY29tL29jc3AwMy1hcHBsZXJv
|
|
17
|
+
b3RjYTAuBgNVHR8EJzAlMCOgIaAfhh1odHRwOi8vY3JsLmFwcGxlLmNvbS9yb290
|
|
18
|
+
LmNybDAdBgNVHQ4EFgQUW9n6HeeaGgujmXYiUIY+kchbd6gwDgYDVR0PAQH/BAQD
|
|
19
|
+
AgEGMBAGCiqGSIb3Y2QGAgEEAgUAMA0GCSqGSIb3DQEBCwUAA4IBAQA/Vj2e5bbD
|
|
20
|
+
eeZFIGi9v3OLLBKeAuOugCKMBB7DUshwgKj7zqew1UJEggOCTwb8O0kU+9h0UoWv
|
|
21
|
+
p50h5wESA5/NQFjQAde/MoMrU1goPO6cn1R2PWQnxn6NHThNLa6B5rmluJyJlPef
|
|
22
|
+
x4elUWY0GzlxOSTjh2fvpbFoe4zuPfeutnvi0v/fYcZqdUmVIkSoBPyUuAsuORFJ
|
|
23
|
+
EtHlgepZAE9bPFo22noicwkJac3AfOriJP6YRLj477JxPxpd1F1+M02cHSS+APCQ
|
|
24
|
+
A1iZQT0xWmJArzmoUUOSqwSonMJNsUvSq3xKX+udO7xPiEAGE/+QF4oIRynoYpgp
|
|
25
|
+
pU8RBWk6z/Kf
|
|
26
|
+
-----END CERTIFICATE-----
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
const crypto = require('node:crypto');
|
|
2
|
+
const fs = require('node:fs');
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
|
|
5
|
+
/* Certificat intermédiaire public d'Apple (WWDR G4, valable jusqu'en 2030) :
|
|
6
|
+
rien de secret, identique pour tous les émetteurs. Il voyage avec le package
|
|
7
|
+
plutôt que d'être recopié par chaque application. */
|
|
8
|
+
const APPLE_WWDR_G4 = fs.readFileSync(path.join(__dirname, 'certificates', 'apple-wwdr-g4.pem'), 'utf8');
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Lit un certificat Pass Type ID. Il porte lui-même son identifiant (UID) et
|
|
12
|
+
* l'équipe Apple (OU) : les en extraire évite deux champs à recopier, et deux
|
|
13
|
+
* occasions de se tromper.
|
|
14
|
+
* @returns {{passTypeIdentifier: string|null, teamIdentifier: string|null, expiresAt: string, x509: crypto.X509Certificate} | null}
|
|
15
|
+
*/
|
|
16
|
+
function readPassCertificate(pem) {
|
|
17
|
+
try {
|
|
18
|
+
const x509 = new crypto.X509Certificate(pem);
|
|
19
|
+
const champ = (nom) => (x509.subject.split('\n').find((ligne) => ligne.startsWith(`${nom}=`)) || '').slice(nom.length + 1);
|
|
20
|
+
return {
|
|
21
|
+
x509,
|
|
22
|
+
passTypeIdentifier: champ('UID') || null,
|
|
23
|
+
teamIdentifier: champ('OU') || null,
|
|
24
|
+
expiresAt: new Date(x509.validTo).toISOString()
|
|
25
|
+
};
|
|
26
|
+
} catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Contrôle un certificat Apple et sa clé avant de les enregistrer : un couple
|
|
33
|
+
* incohérent ne se verrait sinon qu'au premier client qui ajoute sa carte.
|
|
34
|
+
* @returns {{ok: true} | {ok: false, reason: string}}
|
|
35
|
+
*/
|
|
36
|
+
function checkAppleCredentials({ certificate, privateKey }, now = Date.now()) {
|
|
37
|
+
if (!certificate || !privateKey) {
|
|
38
|
+
return { ok: false, reason: 'Colle le certificat et la clé privée Apple Wallet.' };
|
|
39
|
+
}
|
|
40
|
+
const lu = readPassCertificate(certificate);
|
|
41
|
+
if (!lu) return { ok: false, reason: 'Le certificat n’est pas lisible : colle le bloc complet, de BEGIN CERTIFICATE à END CERTIFICATE.' };
|
|
42
|
+
if (!lu.passTypeIdentifier?.startsWith('pass.') || !lu.teamIdentifier) {
|
|
43
|
+
return { ok: false, reason: 'Ce certificat n’est pas un certificat Pass Type ID Apple Wallet.' };
|
|
44
|
+
}
|
|
45
|
+
if (new Date(lu.expiresAt).getTime() <= now) return { ok: false, reason: 'Ce certificat Apple a expiré : génère-en un nouveau.' };
|
|
46
|
+
let cle;
|
|
47
|
+
try {
|
|
48
|
+
cle = crypto.createPrivateKey(privateKey);
|
|
49
|
+
} catch {
|
|
50
|
+
return { ok: false, reason: 'La clé privée n’est pas lisible : colle le bloc complet, de BEGIN à END PRIVATE KEY.' };
|
|
51
|
+
}
|
|
52
|
+
if (!lu.x509.checkPrivateKey(cle)) return { ok: false, reason: 'La clé privée ne correspond pas à ce certificat.' };
|
|
53
|
+
return { ok: true };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Le JSON d'un compte de service Google, ou null s'il n'en est pas un. */
|
|
57
|
+
function readGoogleServiceAccount(json) {
|
|
58
|
+
try {
|
|
59
|
+
const compte = typeof json === 'string' ? JSON.parse(json) : json;
|
|
60
|
+
return compte?.type === 'service_account' && compte.client_email && compte.private_key ? compte : null;
|
|
61
|
+
} catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Un champ absent veut dire « ne touche pas à celui-là » ; les deux absents
|
|
68
|
+
* sont refusés.
|
|
69
|
+
* @returns {{ok: true} | {ok: false, reason: string}}
|
|
70
|
+
*/
|
|
71
|
+
function checkGoogleCredentials({ issuerId, serviceAccount }) {
|
|
72
|
+
if (issuerId !== undefined && !/^\d{10,25}$/.test(String(issuerId).trim())) {
|
|
73
|
+
return { ok: false, reason: 'L’ID émetteur Google Wallet est un nombre (par exemple 3388000000000000000).' };
|
|
74
|
+
}
|
|
75
|
+
if (serviceAccount !== undefined && !readGoogleServiceAccount(serviceAccount)) {
|
|
76
|
+
return { ok: false, reason: 'Colle le contenu complet du fichier JSON du compte de service Google.' };
|
|
77
|
+
}
|
|
78
|
+
if (issuerId === undefined && serviceAccount === undefined) {
|
|
79
|
+
return { ok: false, reason: 'Renseigne l’ID émetteur et la clé du compte de service Google.' };
|
|
80
|
+
}
|
|
81
|
+
return { ok: true };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/* Un certificat PEM commence par « ----- », qu'un pare-feu applicatif prend,
|
|
85
|
+
à raison en général, pour un commentaire SQL. Encoder en hexadécimal côté
|
|
86
|
+
interface ([0-9a-f] seulement) fait traverser ces champs précis sans
|
|
87
|
+
affaiblir le pare-feu pour le reste. Le contenu décodé doit toujours passer
|
|
88
|
+
par checkAppleCredentials / checkGoogleCredentials avant d'être gardé. */
|
|
89
|
+
function toHexField(texte) {
|
|
90
|
+
return Buffer.from(String(texte ?? ''), 'utf8').toString('hex');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Décode un champ hexadécimal ; '' si ce n'est pas de l'hexadécimal, undefined s'il est absent. */
|
|
94
|
+
function fromHexField(valeur) {
|
|
95
|
+
if (valeur === undefined) return undefined;
|
|
96
|
+
const texte = String(valeur);
|
|
97
|
+
return /^(?:[0-9a-f]{2})+$/i.test(texte) ? Buffer.from(texte, 'hex').toString('utf8') : '';
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
module.exports = {
|
|
101
|
+
APPLE_WWDR_G4,
|
|
102
|
+
readPassCertificate,
|
|
103
|
+
checkAppleCredentials,
|
|
104
|
+
readGoogleServiceAccount,
|
|
105
|
+
checkGoogleCredentials,
|
|
106
|
+
toHexField,
|
|
107
|
+
fromHexField
|
|
108
|
+
};
|
package/src/google.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
const crypto = require('node:crypto');
|
|
2
|
+
const { GoogleAuth } = require('google-auth-library');
|
|
3
|
+
|
|
4
|
+
const API_BASE = 'https://walletobjects.googleapis.com/walletobjects/v1';
|
|
5
|
+
const SCOPE = 'https://www.googleapis.com/auth/wallet_object.issuer';
|
|
6
|
+
|
|
7
|
+
/* Chaque type de carte Google a sa ressource REST et sa clé dans le JWT
|
|
8
|
+
d'ajout. La fidélité est le cas courant ; les autres suivent le même
|
|
9
|
+
chemin. */
|
|
10
|
+
const KINDS = {
|
|
11
|
+
loyalty: { resource: 'loyalty', jwtKey: 'loyaltyObjects' },
|
|
12
|
+
generic: { resource: 'generic', jwtKey: 'genericObjects' },
|
|
13
|
+
offer: { resource: 'offer', jwtKey: 'offerObjects' },
|
|
14
|
+
giftCard: { resource: 'giftCard', jwtKey: 'giftCardObjects' }
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const base64urlJson = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Signe le JWT « Ajouter à Google Wallet » (RS256, clé du compte de service).
|
|
21
|
+
* @param {object} payload par exemple { loyaltyObjects: [{ id, classId }] }.
|
|
22
|
+
*/
|
|
23
|
+
function signSaveJwt(payload, credentials, { now = new Date(), origins } = {}) {
|
|
24
|
+
const header = { alg: 'RS256', typ: 'JWT' };
|
|
25
|
+
const corps = {
|
|
26
|
+
iss: credentials.client_email,
|
|
27
|
+
aud: 'google',
|
|
28
|
+
typ: 'savetowallet',
|
|
29
|
+
iat: Math.floor(now.getTime() / 1000),
|
|
30
|
+
...(origins ? { origins } : {}),
|
|
31
|
+
payload
|
|
32
|
+
};
|
|
33
|
+
const signe = `${base64urlJson(header)}.${base64urlJson(corps)}`;
|
|
34
|
+
const signature = crypto.createSign('RSA-SHA256').update(signe).sign(credentials.private_key, 'base64url');
|
|
35
|
+
return `${signe}.${signature}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {object} options
|
|
40
|
+
* @param {string} options.issuerId
|
|
41
|
+
* @param {object} options.credentials JSON du compte de service (client_email, private_key).
|
|
42
|
+
* @param {'loyalty'|'generic'|'offer'|'giftCard'} [options.kind='loyalty']
|
|
43
|
+
* @param {(options: object) => Promise<object>} [options.request] remplace le client HTTP (tests).
|
|
44
|
+
*/
|
|
45
|
+
function createGoogleWallet({ issuerId, credentials, kind = 'loyalty', request }) {
|
|
46
|
+
const type = KINDS[kind];
|
|
47
|
+
if (!type) throw new Error(`Type de carte Google inconnu : ${kind}`);
|
|
48
|
+
const auth = request ? null : new GoogleAuth({ credentials, scopes: [SCOPE] });
|
|
49
|
+
const classesPretes = new Map();
|
|
50
|
+
|
|
51
|
+
async function requete(options) {
|
|
52
|
+
if (request) return request(options);
|
|
53
|
+
const client = await auth.getClient();
|
|
54
|
+
return client.request(options);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const idOf = (suffix) => `${issuerId}.${String(suffix).replace(/[^\w.-]/g, '_')}`;
|
|
58
|
+
const url = (ressource, id) => `${API_BASE}/${type.resource}${ressource}${id ? `/${encodeURIComponent(id)}` : ''}`;
|
|
59
|
+
|
|
60
|
+
/* Crée la ressource si Google répond 404, sinon la met à jour : une seule
|
|
61
|
+
fonction pour le premier envoi et tous les suivants. */
|
|
62
|
+
async function upsert(ressource, data) {
|
|
63
|
+
try {
|
|
64
|
+
await requete({ method: 'PATCH', url: url(ressource, data.id), data });
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (error?.response?.status !== 404) throw error;
|
|
67
|
+
await requete({ method: 'POST', url: url(ressource), data });
|
|
68
|
+
}
|
|
69
|
+
return data.id;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* La classe (le modèle commun à toutes les cartes de l'émetteur), vérifiée
|
|
74
|
+
* une fois par processus et par définition.
|
|
75
|
+
* @param {object} definition la classe Google, `id` compris (voir classId).
|
|
76
|
+
*/
|
|
77
|
+
async function ensureClass(definition) {
|
|
78
|
+
const cle = JSON.stringify(definition);
|
|
79
|
+
if (!classesPretes.has(cle)) {
|
|
80
|
+
const promesse = upsert('Class', { reviewStatus: 'UNDER_REVIEW', ...definition })
|
|
81
|
+
.catch((error) => { classesPretes.delete(cle); throw error; });
|
|
82
|
+
classesPretes.set(cle, promesse);
|
|
83
|
+
}
|
|
84
|
+
return classesPretes.get(cle);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Crée ou met à jour la carte d'un client ; Google la pousse sur ses appareils. */
|
|
88
|
+
function upsertObject(object) {
|
|
89
|
+
return upsert('Object', object);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Le lien « Ajouter à Google Wallet » pour des cartes déjà créées. */
|
|
93
|
+
function saveLink(objects, options) {
|
|
94
|
+
const refs = objects.map(({ id, classId }) => ({ id, classId }));
|
|
95
|
+
return `https://pay.google.com/gp/v/save/${signSaveJwt({ [type.jwtKey]: refs }, credentials, options)}`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return { classId: idOf, objectId: idOf, ensureClass, upsertObject, saveLink };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
module.exports = { createGoogleWallet, signSaveJwt };
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/** An express Router — opaque here, mount it with `app.use(path, router)` (same convention as @astratra/credentials). */
|
|
2
|
+
export type Router = unknown;
|
|
3
|
+
|
|
4
|
+
export type CheckResult = { ok: true } | { ok: false; reason: string };
|
|
5
|
+
|
|
6
|
+
export const APPLE_WWDR_G4: string;
|
|
7
|
+
|
|
8
|
+
export interface PassCertificateInfo {
|
|
9
|
+
passTypeIdentifier: string | null;
|
|
10
|
+
teamIdentifier: string | null;
|
|
11
|
+
expiresAt: string;
|
|
12
|
+
x509: unknown;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function readPassCertificate(pem: string): PassCertificateInfo | null;
|
|
16
|
+
export function checkAppleCredentials(input: { certificate?: string; privateKey?: string }, now?: number): CheckResult;
|
|
17
|
+
|
|
18
|
+
export interface GoogleServiceAccount {
|
|
19
|
+
type: 'service_account';
|
|
20
|
+
client_email: string;
|
|
21
|
+
private_key: string;
|
|
22
|
+
[key: string]: unknown;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function readGoogleServiceAccount(json: string | object): GoogleServiceAccount | null;
|
|
26
|
+
export function checkGoogleCredentials(input: { issuerId?: string; serviceAccount?: string }): CheckResult;
|
|
27
|
+
export function toHexField(text: string): string;
|
|
28
|
+
export function fromHexField(value: string | undefined): string | undefined;
|
|
29
|
+
|
|
30
|
+
export interface PassField {
|
|
31
|
+
key: string;
|
|
32
|
+
label?: string;
|
|
33
|
+
value: string | number;
|
|
34
|
+
textAlignment?: string;
|
|
35
|
+
changeMessage?: string;
|
|
36
|
+
[key: string]: unknown;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface PassContent {
|
|
40
|
+
serialNumber: string;
|
|
41
|
+
/** At least 16 characters (Apple requirement). */
|
|
42
|
+
authenticationToken: string;
|
|
43
|
+
headerFields?: PassField[];
|
|
44
|
+
primaryFields?: PassField[];
|
|
45
|
+
secondaryFields?: PassField[];
|
|
46
|
+
auxiliaryFields?: PassField[];
|
|
47
|
+
backFields?: PassField[];
|
|
48
|
+
barcode?: { message: string; altText?: string; format?: string };
|
|
49
|
+
images?: Record<string, Buffer>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface ApplePassesOptions {
|
|
53
|
+
certificate: string;
|
|
54
|
+
privateKey: string;
|
|
55
|
+
passphrase?: string;
|
|
56
|
+
wwdr?: string;
|
|
57
|
+
webServiceURL: string;
|
|
58
|
+
organizationName: string;
|
|
59
|
+
description: string;
|
|
60
|
+
images?: Record<string, Buffer>;
|
|
61
|
+
colors?: { foregroundColor?: string; backgroundColor?: string; labelColor?: string };
|
|
62
|
+
type?: 'storeCard' | 'generic' | 'coupon' | 'eventTicket';
|
|
63
|
+
logoText?: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface ApplePasses {
|
|
67
|
+
passTypeIdentifier: string;
|
|
68
|
+
teamIdentifier: string;
|
|
69
|
+
expiresAt: string;
|
|
70
|
+
build(card: PassContent): Buffer;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function createApplePasses(options: ApplePassesOptions): ApplePasses;
|
|
74
|
+
|
|
75
|
+
export interface ApnsOptions {
|
|
76
|
+
certificate: string;
|
|
77
|
+
privateKey: string;
|
|
78
|
+
passphrase?: string;
|
|
79
|
+
passTypeIdentifier: string;
|
|
80
|
+
connect?: (...args: unknown[]) => unknown;
|
|
81
|
+
host?: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function sendApplePassUpdate(pushToken: string, options: ApnsOptions): Promise<number>;
|
|
85
|
+
|
|
86
|
+
export interface Registration {
|
|
87
|
+
deviceLibraryIdentifier: string;
|
|
88
|
+
passTypeIdentifier: string;
|
|
89
|
+
serialNumber: string;
|
|
90
|
+
pushToken: string;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface RegistrationStore {
|
|
94
|
+
register(registration: Registration): Promise<boolean>;
|
|
95
|
+
unregister(registration: Omit<Registration, 'pushToken'>): Promise<boolean>;
|
|
96
|
+
listForDevice(deviceLibraryIdentifier: string, passTypeIdentifier: string): Promise<Registration[]>;
|
|
97
|
+
listForPass(passTypeIdentifier: string, serialNumber: string): Promise<Registration[]>;
|
|
98
|
+
forgetPushToken(pushToken: string): Promise<void>;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function notifyApplePass(options: Omit<ApnsOptions, 'passTypeIdentifier'> & {
|
|
102
|
+
registrations: RegistrationStore;
|
|
103
|
+
passTypeIdentifier: string;
|
|
104
|
+
serialNumber: string;
|
|
105
|
+
}): Promise<number>;
|
|
106
|
+
|
|
107
|
+
export function createMemoryRegistrationStore(): RegistrationStore;
|
|
108
|
+
export function createMongooseRegistrationStore(connection: unknown, collection?: string): RegistrationStore;
|
|
109
|
+
|
|
110
|
+
export function createAppleWebServiceRouter(options: {
|
|
111
|
+
resolveConfig(): Promise<{ passTypeIdentifier: string } | null>;
|
|
112
|
+
findPass(serialNumber: string): Promise<{ authenticationToken: string; updatedAt?: Date | string } | null>;
|
|
113
|
+
buildPass(serialNumber: string): Promise<Buffer>;
|
|
114
|
+
registrations: RegistrationStore;
|
|
115
|
+
logger?: { warn(message: string): void };
|
|
116
|
+
}): Router;
|
|
117
|
+
|
|
118
|
+
export type GoogleKind = 'loyalty' | 'generic' | 'offer' | 'giftCard';
|
|
119
|
+
|
|
120
|
+
export interface GoogleWallet {
|
|
121
|
+
classId(suffix: string): string;
|
|
122
|
+
objectId(suffix: string): string;
|
|
123
|
+
ensureClass(definition: { id: string; [key: string]: unknown }): Promise<string>;
|
|
124
|
+
upsertObject(object: { id: string; classId: string; [key: string]: unknown }): Promise<string>;
|
|
125
|
+
saveLink(objects: Array<{ id: string; classId: string }>, options?: { now?: Date; origins?: string[] }): string;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function createGoogleWallet(options: {
|
|
129
|
+
issuerId: string;
|
|
130
|
+
credentials: { client_email: string; private_key: string };
|
|
131
|
+
kind?: GoogleKind;
|
|
132
|
+
request?: (options: Record<string, unknown>) => Promise<unknown>;
|
|
133
|
+
}): GoogleWallet;
|
|
134
|
+
|
|
135
|
+
export function signSaveJwt(
|
|
136
|
+
payload: Record<string, unknown>,
|
|
137
|
+
credentials: { client_email: string; private_key: string },
|
|
138
|
+
options?: { now?: Date; origins?: string[] }
|
|
139
|
+
): string;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
const credentials = require('./credentials');
|
|
2
|
+
const { createApplePasses, sendApplePassUpdate, notifyApplePass } = require('./apple');
|
|
3
|
+
const { createAppleWebServiceRouter } = require('./appleWebService');
|
|
4
|
+
const { createGoogleWallet, signSaveJwt } = require('./google');
|
|
5
|
+
const { createMemoryRegistrationStore, createMongooseRegistrationStore } = require('./registrations');
|
|
6
|
+
|
|
7
|
+
module.exports = {
|
|
8
|
+
...credentials,
|
|
9
|
+
createApplePasses,
|
|
10
|
+
sendApplePassUpdate,
|
|
11
|
+
notifyApplePass,
|
|
12
|
+
createAppleWebServiceRouter,
|
|
13
|
+
createGoogleWallet,
|
|
14
|
+
signSaveJwt,
|
|
15
|
+
createMemoryRegistrationStore,
|
|
16
|
+
createMongooseRegistrationStore
|
|
17
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Qui porte quelle carte : Apple Wallet inscrit chaque appareil auprès du
|
|
3
|
+
* service web, avec un jeton de notification. Le même contrat pour les deux
|
|
4
|
+
* implémentations :
|
|
5
|
+
*
|
|
6
|
+
* register({ deviceLibraryIdentifier, passTypeIdentifier, serialNumber, pushToken }) → true si nouvelle
|
|
7
|
+
* unregister({ deviceLibraryIdentifier, passTypeIdentifier, serialNumber }) → true si supprimée
|
|
8
|
+
* listForDevice(deviceLibraryIdentifier, passTypeIdentifier) → inscriptions
|
|
9
|
+
* listForPass(passTypeIdentifier, serialNumber) → inscriptions
|
|
10
|
+
* forgetPushToken(pushToken) → jeton mort, oublié partout
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const memeInscription = (a, b) => a.deviceLibraryIdentifier === b.deviceLibraryIdentifier
|
|
14
|
+
&& a.passTypeIdentifier === b.passTypeIdentifier
|
|
15
|
+
&& a.serialNumber === b.serialNumber;
|
|
16
|
+
|
|
17
|
+
/** En mémoire : tests et démonstrations. */
|
|
18
|
+
function createMemoryRegistrationStore() {
|
|
19
|
+
const rows = [];
|
|
20
|
+
return {
|
|
21
|
+
async register(inscription) {
|
|
22
|
+
const existante = rows.find((row) => memeInscription(row, inscription));
|
|
23
|
+
if (existante) {
|
|
24
|
+
Object.assign(existante, { pushToken: inscription.pushToken, updatedAt: new Date() });
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
rows.push({ ...inscription, createdAt: new Date(), updatedAt: new Date() });
|
|
28
|
+
return true;
|
|
29
|
+
},
|
|
30
|
+
async unregister(inscription) {
|
|
31
|
+
const index = rows.findIndex((row) => memeInscription(row, inscription));
|
|
32
|
+
if (index < 0) return false;
|
|
33
|
+
rows.splice(index, 1);
|
|
34
|
+
return true;
|
|
35
|
+
},
|
|
36
|
+
async listForDevice(deviceLibraryIdentifier, passTypeIdentifier) {
|
|
37
|
+
return rows.filter((row) => row.deviceLibraryIdentifier === deviceLibraryIdentifier && row.passTypeIdentifier === passTypeIdentifier);
|
|
38
|
+
},
|
|
39
|
+
async listForPass(passTypeIdentifier, serialNumber) {
|
|
40
|
+
return rows.filter((row) => row.passTypeIdentifier === passTypeIdentifier && row.serialNumber === serialNumber);
|
|
41
|
+
},
|
|
42
|
+
async forgetPushToken(pushToken) {
|
|
43
|
+
for (let index = rows.length - 1; index >= 0; index -= 1) {
|
|
44
|
+
if (rows[index].pushToken === pushToken) rows.splice(index, 1);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Sur une connexion Mongoose existante, sans dépendre de Mongoose : le schéma
|
|
52
|
+
* se construit avec la classe portée par la connexion.
|
|
53
|
+
* @param {object} connection connexion Mongoose.
|
|
54
|
+
* @param {string} [collection='apple_wallet_registrations']
|
|
55
|
+
*/
|
|
56
|
+
function createMongooseRegistrationStore(connection, collection = 'apple_wallet_registrations') {
|
|
57
|
+
const schema = new connection.base.Schema({
|
|
58
|
+
deviceLibraryIdentifier: { type: String, required: true },
|
|
59
|
+
passTypeIdentifier: { type: String, required: true },
|
|
60
|
+
serialNumber: { type: String, required: true },
|
|
61
|
+
pushToken: { type: String, required: true },
|
|
62
|
+
createdAt: { type: Date, default: Date.now },
|
|
63
|
+
updatedAt: { type: Date, default: Date.now }
|
|
64
|
+
});
|
|
65
|
+
schema.index({ deviceLibraryIdentifier: 1, passTypeIdentifier: 1, serialNumber: 1 }, { unique: true });
|
|
66
|
+
schema.index({ passTypeIdentifier: 1, serialNumber: 1 });
|
|
67
|
+
const Registration = connection.models.AstratraWalletRegistration
|
|
68
|
+
|| connection.model('AstratraWalletRegistration', schema, collection);
|
|
69
|
+
let initialisation;
|
|
70
|
+
const ready = () => { initialisation ||= Registration.init(); return initialisation; };
|
|
71
|
+
|
|
72
|
+
return {
|
|
73
|
+
async register({ deviceLibraryIdentifier, passTypeIdentifier, serialNumber, pushToken }) {
|
|
74
|
+
await ready();
|
|
75
|
+
const resultat = await Registration.updateOne(
|
|
76
|
+
{ deviceLibraryIdentifier, passTypeIdentifier, serialNumber },
|
|
77
|
+
{ $set: { pushToken, updatedAt: new Date() }, $setOnInsert: { createdAt: new Date() } },
|
|
78
|
+
{ upsert: true }
|
|
79
|
+
);
|
|
80
|
+
return resultat.upsertedCount > 0;
|
|
81
|
+
},
|
|
82
|
+
async unregister({ deviceLibraryIdentifier, passTypeIdentifier, serialNumber }) {
|
|
83
|
+
const resultat = await Registration.deleteOne({ deviceLibraryIdentifier, passTypeIdentifier, serialNumber });
|
|
84
|
+
return resultat.deletedCount > 0;
|
|
85
|
+
},
|
|
86
|
+
async listForDevice(deviceLibraryIdentifier, passTypeIdentifier) {
|
|
87
|
+
return Registration.find({ deviceLibraryIdentifier, passTypeIdentifier }).lean();
|
|
88
|
+
},
|
|
89
|
+
async listForPass(passTypeIdentifier, serialNumber) {
|
|
90
|
+
return Registration.find({ passTypeIdentifier, serialNumber }).lean();
|
|
91
|
+
},
|
|
92
|
+
async forgetPushToken(pushToken) {
|
|
93
|
+
await Registration.deleteMany({ pushToken });
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
module.exports = { createMemoryRegistrationStore, createMongooseRegistrationStore };
|