@celljs/alipay 0.0.0-stage → 4.4.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.
Files changed (84) hide show
  1. package/README.md +109 -2
  2. package/cell.schema.json +58 -0
  3. package/cell.yml +10 -0
  4. package/esm/node/alipay-client.d.ts +58 -0
  5. package/esm/node/alipay-client.js +234 -0
  6. package/esm/node/alipay-client.js.map +1 -0
  7. package/esm/node/alipay-error.d.ts +28 -0
  8. package/esm/node/alipay-error.js +20 -0
  9. package/esm/node/alipay-error.js.map +1 -0
  10. package/esm/node/alipay-notification-middleware.d.ts +23 -0
  11. package/esm/node/alipay-notification-middleware.js +102 -0
  12. package/esm/node/alipay-notification-middleware.js.map +1 -0
  13. package/esm/node/alipay-protocol.d.ts +200 -0
  14. package/esm/node/alipay-protocol.js +15 -0
  15. package/esm/node/alipay-protocol.js.map +1 -0
  16. package/esm/node/alipay-util.d.ts +35 -0
  17. package/esm/node/alipay-util.js +191 -0
  18. package/esm/node/alipay-util.js.map +1 -0
  19. package/esm/node/index.d.ts +5 -0
  20. package/esm/node/index.js +6 -0
  21. package/esm/node/index.js.map +1 -0
  22. package/esm/node/module.d.ts +3 -0
  23. package/esm/node/module.js +4 -0
  24. package/esm/node/module.js.map +1 -0
  25. package/esm/node/test/fixtures.d.ts +10 -0
  26. package/esm/node/test/fixtures.js +266 -0
  27. package/esm/node/test/fixtures.js.map +1 -0
  28. package/esm/package.json +3 -0
  29. package/lib/node/alipay-client.d.ts +59 -0
  30. package/lib/node/alipay-client.d.ts.map +1 -0
  31. package/lib/node/alipay-client.js +237 -0
  32. package/lib/node/alipay-client.js.map +1 -0
  33. package/lib/node/alipay-error.d.ts +29 -0
  34. package/lib/node/alipay-error.d.ts.map +1 -0
  35. package/lib/node/alipay-error.js +24 -0
  36. package/lib/node/alipay-error.js.map +1 -0
  37. package/lib/node/alipay-notification-middleware.d.ts +24 -0
  38. package/lib/node/alipay-notification-middleware.d.ts.map +1 -0
  39. package/lib/node/alipay-notification-middleware.js +105 -0
  40. package/lib/node/alipay-notification-middleware.js.map +1 -0
  41. package/lib/node/alipay-protocol.d.ts +201 -0
  42. package/lib/node/alipay-protocol.d.ts.map +1 -0
  43. package/lib/node/alipay-protocol.js +19 -0
  44. package/lib/node/alipay-protocol.js.map +1 -0
  45. package/lib/node/alipay-util.d.ts +36 -0
  46. package/lib/node/alipay-util.d.ts.map +1 -0
  47. package/lib/node/alipay-util.js +194 -0
  48. package/lib/node/alipay-util.js.map +1 -0
  49. package/lib/node/alipay-util.spec.d.ts +2 -0
  50. package/lib/node/alipay-util.spec.d.ts.map +1 -0
  51. package/lib/node/alipay-util.spec.js +49 -0
  52. package/lib/node/alipay-util.spec.js.map +1 -0
  53. package/lib/node/alipay.spec.d.ts +8 -0
  54. package/lib/node/alipay.spec.d.ts.map +1 -0
  55. package/lib/node/alipay.spec.js +314 -0
  56. package/lib/node/alipay.spec.js.map +1 -0
  57. package/lib/node/index.d.ts +6 -0
  58. package/lib/node/index.d.ts.map +1 -0
  59. package/lib/node/index.js +22 -0
  60. package/lib/node/index.js.map +1 -0
  61. package/lib/node/module.d.ts +4 -0
  62. package/lib/node/module.d.ts.map +1 -0
  63. package/lib/node/module.js +6 -0
  64. package/lib/node/module.js.map +1 -0
  65. package/lib/node/test/fixtures.d.ts +11 -0
  66. package/lib/node/test/fixtures.d.ts.map +1 -0
  67. package/lib/node/test/fixtures.js +269 -0
  68. package/lib/node/test/fixtures.js.map +1 -0
  69. package/lib/package.spec.d.ts +2 -0
  70. package/lib/package.spec.d.ts.map +1 -0
  71. package/lib/package.spec.js +7 -0
  72. package/lib/package.spec.js.map +1 -0
  73. package/package.json +70 -4
  74. package/src/node/alipay-client.ts +266 -0
  75. package/src/node/alipay-error.ts +31 -0
  76. package/src/node/alipay-notification-middleware.ts +90 -0
  77. package/src/node/alipay-protocol.ts +210 -0
  78. package/src/node/alipay-util.spec.ts +56 -0
  79. package/src/node/alipay-util.ts +183 -0
  80. package/src/node/alipay.spec.ts +331 -0
  81. package/src/node/index.ts +5 -0
  82. package/src/node/module.ts +4 -0
  83. package/src/node/test/fixtures.ts +272 -0
  84. package/src/package.spec.ts +5 -0
@@ -0,0 +1,183 @@
1
+ import { createHash, createPrivateKey, createPublicKey, type KeyObject, sign, verify, X509Certificate } from 'node:crypto';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { Component, type ComponentId, type ComponentOption, getTargetClass, parseComponentOption } from '@celljs/core';
4
+
5
+ const EVENT_TYPES = 'cell:alipay:event-types';
6
+ const CERTIFICATE = /-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g;
7
+ /** Signature algorithms of RSA (sha1WithRSAEncryption, sha256WithRSAEncryption...): the root certificates Alipay counts. */
8
+ const RSA_SIGNATURE = '1.2.840.113549.1.1.';
9
+
10
+ /** The signatures (RSA2: SHA256 with RSA) and certificate serial numbers of the Alipay OpenAPI gateway, on Node's crypto. */
11
+ export namespace AlipayUtil {
12
+ /** The content of a key or certificate setting: PEM or base64 as it is, otherwise the file it names. */
13
+ export function content(value: string): string {
14
+ return !value.includes('-----BEGIN') && value.length < 1024 && existsSync(value) ? readFileSync(value, 'utf8') : value;
15
+ }
16
+
17
+ /** A private key in PEM, or in base64 as Alipay's key tool gives it (PKCS#8 or PKCS#1). */
18
+ export function privateKey(value: string | KeyObject): KeyObject {
19
+ if (typeof value !== 'string') {
20
+ return value;
21
+ }
22
+ const text = content(value);
23
+ if (text.includes('-----BEGIN')) {
24
+ return createPrivateKey(text);
25
+ }
26
+ const der = Buffer.from(text.replace(/\s+/g, ''), 'base64');
27
+ try {
28
+ return createPrivateKey({ key: der, format: 'der', type: 'pkcs8' });
29
+ } catch {
30
+ return createPrivateKey({ key: der, format: 'der', type: 'pkcs1' });
31
+ }
32
+ }
33
+
34
+ /** A public key in PEM (a key or a certificate), or in base64 as Alipay shows it. */
35
+ export function publicKey(value: string | KeyObject): KeyObject {
36
+ if (typeof value !== 'string') {
37
+ return value;
38
+ }
39
+ const text = content(value);
40
+ if (text.includes('-----BEGIN')) {
41
+ return createPublicKey(text);
42
+ }
43
+ return createPublicKey({ key: Buffer.from(text.replace(/\s+/g, ''), 'base64'), format: 'der', type: 'spki' });
44
+ }
45
+
46
+ /** `yyyy-MM-dd HH:mm:ss` in Beijing time, as the gateway wants it. */
47
+ export function timestamp(date = new Date()): string {
48
+ return new Date(date.getTime() + 8 * 3600_000).toISOString().slice(0, 19).replace('T', ' ');
49
+ }
50
+
51
+ /** `a=1&b=2`: the parameters sorted by name, without `sign`, `exclude` and empty values, not encoded. */
52
+ export function signContent(params: Record<string, string | undefined>, exclude: string[] = []): string {
53
+ return Object.keys(params)
54
+ .filter(key => key !== 'sign' && !exclude.includes(key) && params[key] !== undefined && params[key] !== '')
55
+ .sort()
56
+ .map(key => `${key}=${params[key]}`)
57
+ .join('&');
58
+ }
59
+
60
+ /** RSA2 (SHA256 with RSA), base64. */
61
+ export function signText(text: string, key: string | KeyObject): string {
62
+ return sign('sha256', Buffer.from(text), privateKey(key)).toString('base64');
63
+ }
64
+
65
+ export function verifyText(text: string, signature: string, key: string | KeyObject): boolean {
66
+ try {
67
+ return verify('sha256', Buffer.from(text), publicKey(key), Buffer.from(signature, 'base64'));
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
72
+
73
+ /**
74
+ * The serial number Alipay gives a certificate (`app_cert_sn`, `alipay_cert_sn`): MD5 of the issuer, its attributes in
75
+ * reverse order joined with commas, followed by the decimal serial number.
76
+ */
77
+ export function certSn(pem: string | X509Certificate): string {
78
+ const certificate = typeof pem === 'string' ? new X509Certificate(content(pem)) : pem;
79
+ const issuer = certificate.issuer.split('\n').reverse().join(',');
80
+ return createHash('md5')
81
+ .update(issuer + BigInt(`0x${certificate.serialNumber}`).toString(10))
82
+ .digest('hex');
83
+ }
84
+
85
+ /** `alipay_root_cert_sn`: the serial numbers of the RSA certificates of the root certificate file, joined with `_`. */
86
+ export function rootCertSn(pem: string): string {
87
+ return (content(pem).match(CERTIFICATE) ?? [])
88
+ .map(text => new X509Certificate(text))
89
+ .filter(certificate => signatureOid(certificate.raw).startsWith(RSA_SIGNATURE))
90
+ .map(certificate => certSn(certificate))
91
+ .join('_');
92
+ }
93
+
94
+ /** The OID of the signature algorithm of a DER certificate: its second element (after tbsCertificate). */
95
+ export function signatureOid(der: Uint8Array): string {
96
+ const certificate = readTlv(der, 0);
97
+ const tbs = readTlv(der, certificate.start);
98
+ const algorithm = readTlv(der, tbs.end);
99
+ const oid = readTlv(der, algorithm.start);
100
+ const bytes = der.subarray(oid.start, oid.end);
101
+ const arcs = [Math.floor(bytes[0] / 40), bytes[0] % 40];
102
+ let value = 0;
103
+ for (const byte of bytes.subarray(1)) {
104
+ value = value * 128 + (byte & 0x7f);
105
+ if (!(byte & 0x80)) {
106
+ arcs.push(value);
107
+ value = 0;
108
+ }
109
+ }
110
+ return arcs.join('.');
111
+ }
112
+
113
+ /**
114
+ * The JSON text of `key` in a gateway answer, exactly as sent: what its signature covers. Undefined when it is absent.
115
+ */
116
+ export function rawJson(text: string, key: string): string | undefined {
117
+ const name = text.indexOf(`"${key}"`);
118
+ if (name < 0) {
119
+ return undefined;
120
+ }
121
+ let start = text.indexOf(':', name + key.length + 2) + 1;
122
+ while (/\s/.test(text[start])) {
123
+ start++;
124
+ }
125
+ if (text[start] !== '{') {
126
+ return undefined;
127
+ }
128
+ let depth = 0;
129
+ let string = false;
130
+ for (let i = start; i < text.length; i++) {
131
+ const char = text[i];
132
+ if (string) {
133
+ if (char === '\\') {
134
+ i++;
135
+ } else if (char === '"') {
136
+ string = false;
137
+ }
138
+ } else if (char === '"') {
139
+ string = true;
140
+ } else if (char === '{') {
141
+ depth++;
142
+ } else if (char === '}' && --depth === 0) {
143
+ return text.slice(start, i + 1);
144
+ }
145
+ }
146
+ return undefined;
147
+ }
148
+
149
+ /** Registers the class as a component also bound to `id`, recording the event types it handles (`[]`: all). */
150
+ export function applyHandlerDecorator(target: any, id: ComponentId, eventTypes: string | string[] | undefined, option?: ComponentOption): void {
151
+ const parsed = parseComponentOption(target, option);
152
+ (parsed.id as ComponentId[]).push(id);
153
+ Reflect.defineMetadata(EVENT_TYPES, eventTypes === undefined ? [] : Array.isArray(eventTypes) ? eventTypes : [eventTypes], target);
154
+ Component(parsed)(target);
155
+ }
156
+
157
+ /** The handlers by event type; `'*'` holds those of all types. */
158
+ export function indexHandlers<H extends object>(handlers: H[]): Map<string, H[]> {
159
+ const result = new Map<string, H[]>();
160
+ for (const handler of handlers) {
161
+ const types: string[] = Reflect.getOwnMetadata(EVENT_TYPES, getTargetClass(handler)) || [];
162
+ for (const type of types.length ? types : ['*']) {
163
+ result.set(type, [...(result.get(type) ?? []), handler]);
164
+ }
165
+ }
166
+ return result;
167
+ }
168
+ }
169
+
170
+ /** Where the content of the DER element at `offset` starts and ends. */
171
+ function readTlv(der: Uint8Array, offset: number): { start: number; end: number } {
172
+ let length = der[offset + 1];
173
+ let start = offset + 2;
174
+ if (length & 0x80) {
175
+ const bytes = length & 0x7f;
176
+ length = 0;
177
+ for (let i = 0; i < bytes; i++) {
178
+ length = length * 256 + der[start + i];
179
+ }
180
+ start += bytes;
181
+ }
182
+ return { start, end: start + length };
183
+ }
@@ -0,0 +1,331 @@
1
+ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
2
+ import { generateKeyPairSync, type KeyObject, X509Certificate } from 'node:crypto';
3
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
4
+ import type { AddressInfo } from 'node:net';
5
+ import { Application } from '@celljs/core/lib/common/application/application-protocol';
6
+ import { autoBind } from '@celljs/core/lib/common/container/auto-bind';
7
+ import { Container } from '@celljs/core/lib/common/container/container';
8
+ import { ContainerProvider } from '@celljs/core/lib/common/container/container-provider';
9
+ import coreCommonStatic from '@celljs/core/lib/common/static-module';
10
+ import { currentThis } from '@celljs/core/lib/common/utils';
11
+ import coreNodeStatic from '@celljs/core/lib/node/static-module';
12
+ import webCommonModule from '@celljs/web/lib/common/module';
13
+ import { HttpServerUtil } from '@celljs/web/lib/node';
14
+ import webNodeModule from '@celljs/web/lib/node/module';
15
+ import { AlipayClientImpl } from './alipay-client';
16
+ import { AlipayError } from './alipay-error';
17
+ import { AlipayClient, type AlipayNotification, AlipayNotificationHandler } from './alipay-protocol';
18
+ import { AlipayUtil } from './alipay-util';
19
+ import alipayModule from './module';
20
+ import { TEST_ALIPAY_CERT, TEST_ALIPAY_PRIVATE_KEY, TEST_APP_CERT, TEST_APP_PRIVATE_KEY, TEST_ROOT_CERT } from './test/fixtures';
21
+
22
+ const app = generateKeyPairSync('rsa', { modulusLength: 2048 });
23
+ const alipay = generateKeyPairSync('rsa', { modulusLength: 2048 });
24
+ const APP_ID = '2021000000000001';
25
+
26
+ const paid: AlipayNotification[] = [];
27
+ const all: string[] = [];
28
+
29
+ @AlipayNotificationHandler(['TRADE_SUCCESS', 'TRADE_FINISHED'])
30
+ export class PaidHandler implements AlipayNotificationHandler {
31
+ handle(notification: AlipayNotification): void {
32
+ if (notification.out_trade_no === 'boom') {
33
+ throw new Error('database down');
34
+ }
35
+ paid.push(notification);
36
+ }
37
+ }
38
+
39
+ @AlipayNotificationHandler()
40
+ export class AllHandler implements AlipayNotificationHandler {
41
+ handle(notification: AlipayNotification): void {
42
+ all.push(notification.trade_status ?? notification.notify_type);
43
+ }
44
+ }
45
+
46
+ interface Call {
47
+ params: Record<string, string>;
48
+ query: Record<string, string>;
49
+ }
50
+
51
+ /** An Alipay gateway: checks the application's signature and answers signed with `signer`, with the spacing of the real one. */
52
+ class FakeGateway {
53
+ readonly calls: Call[] = [];
54
+ server: Server;
55
+ url: string;
56
+ appKey: KeyObject | string = app.publicKey;
57
+ signer: KeyObject | string = alipay.privateKey;
58
+ certSn?: string;
59
+ tamper = false;
60
+
61
+ async start(): Promise<void> {
62
+ this.server = createServer((req, res) => this.serve(req, res));
63
+ await new Promise<void>(r => this.server.listen(0, '127.0.0.1', r));
64
+ this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}/gateway.do`;
65
+ }
66
+
67
+ stop(): Promise<void> {
68
+ return new Promise(r => this.server.close(() => r()));
69
+ }
70
+
71
+ protected async serve(req: IncomingMessage, res: ServerResponse): Promise<void> {
72
+ const chunks: Buffer[] = [];
73
+ for await (const chunk of req) {
74
+ chunks.push(chunk as Buffer);
75
+ }
76
+ const query = Object.fromEntries(new URL(String(req.url), 'http://x').searchParams);
77
+ const params = { ...query, ...Object.fromEntries(new URLSearchParams(Buffer.concat(chunks).toString())) };
78
+ this.calls.push({ params, query });
79
+ const name = `${params.method.replace(/\./g, '_')}_response`;
80
+ if (!AlipayUtil.verifyText(AlipayUtil.signContent(params), params.sign, this.appKey)) {
81
+ return this.answer(res, 'error_response', { code: '40002', msg: 'Invalid Arguments', sub_code: 'isv.invalid-signature', sub_msg: '验签出错' });
82
+ }
83
+ const biz = JSON.parse(params.biz_content ?? '{}');
84
+ if (params.method === 'alipay.trade.precreate') {
85
+ return this.answer(res, name, { code: '10000', msg: 'Success', out_trade_no: biz.out_trade_no, qr_code: 'https:\\/\\/qr.alipay.com\\/bax0000' });
86
+ }
87
+ if (params.method === 'alipay.trade.query' && biz.out_trade_no === 'missing') {
88
+ return this.answer(res, name, { code: '40004', msg: 'Business Failed', sub_code: 'ACQ.TRADE_NOT_EXIST', sub_msg: '交易不存在' });
89
+ }
90
+ if (params.method === 'alipay.trade.query') {
91
+ return this.answer(res, name, {
92
+ code: '10000',
93
+ msg: 'Success',
94
+ out_trade_no: biz.out_trade_no,
95
+ trade_no: '2026110922001',
96
+ trade_status: 'TRADE_SUCCESS',
97
+ total_amount: '88.88',
98
+ });
99
+ }
100
+ return this.answer(res, name, { code: '10000', msg: 'Success', ...biz });
101
+ }
102
+
103
+ /** Writes the JSON by hand: the signature covers the text of the node, escapes included. */
104
+ protected answer(res: ServerResponse, name: string, node: Record<string, string>): void {
105
+ const raw = `{${Object.entries(node)
106
+ .map(([k, v]) => `"${k}":"${v}"`)
107
+ .join(',')}}`;
108
+ const sign = AlipayUtil.signText(this.tamper ? `${raw} ` : raw, this.signer);
109
+ res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
110
+ res.end(`{"${name}":${raw},${this.certSn ? `"alipay_cert_sn":"${this.certSn}",` : ''}"sign":"${sign}"}`);
111
+ }
112
+ }
113
+
114
+ const gateway = new FakeGateway();
115
+
116
+ function config(): any {
117
+ return {
118
+ component: { proxy: false },
119
+ logger: { level: 'fatal' },
120
+ tenant: { enabled: false },
121
+ server: { path: '/', port: 3000 },
122
+ web: {
123
+ session: { autoCommit: true, maxAge: 86400000, sessionIdKey: 'cell:sessionId', sessionKey: 'cell:session' },
124
+ trace: { requestField: 'X-Cell-Trace-ID', responseField: 'X-Cell-Trace-ID' },
125
+ health: { url: '/health', method: 'GET' },
126
+ cookies: { keys: ['abcdef'] },
127
+ route: { cacheSize: 500 },
128
+ },
129
+ alipay: {
130
+ appId: APP_ID,
131
+ privateKey: app.privateKey.export({ type: 'pkcs1', format: 'der' }).toString('base64'),
132
+ alipayPublicKey: alipay.publicKey.export({ type: 'spki', format: 'der' }).toString('base64'),
133
+ gateway: gateway.url,
134
+ notifyUrl: 'https://shop.example.com/alipay/notify',
135
+ timeout: 5000,
136
+ notification: { enabled: true, url: '/alipay/notify' },
137
+ },
138
+ };
139
+ }
140
+
141
+ function clientWith(options: object): AlipayClientImpl {
142
+ const client = new AlipayClientImpl();
143
+ Object.defineProperty(client, 'options', { value: options });
144
+ return client;
145
+ }
146
+
147
+ describe('alipay', () => {
148
+ let server: Server;
149
+ let base: string;
150
+ let client: AlipayClient;
151
+
152
+ beforeAll(async () => {
153
+ await gateway.start();
154
+ currentThis.cellProps = config();
155
+ const container = new Container(coreCommonStatic, coreNodeStatic, webCommonModule, webNodeModule, alipayModule, autoBind());
156
+ ContainerProvider.set(container);
157
+ await container.get<Application>(Application).start();
158
+ client = container.get<AlipayClient>(AlipayClient);
159
+ server = HttpServerUtil.createHttpServer(HttpServerUtil.createHandler(container));
160
+ await new Promise<void>(r => server.listen(0, '127.0.0.1', r));
161
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
162
+ });
163
+
164
+ afterAll(async () => {
165
+ await new Promise<void>(r => server.close(() => r()));
166
+ await gateway.stop();
167
+ });
168
+
169
+ beforeEach(() => {
170
+ gateway.calls.length = 0;
171
+ gateway.appKey = app.publicKey;
172
+ gateway.signer = alipay.privateKey;
173
+ gateway.certSn = undefined;
174
+ gateway.tamper = false;
175
+ paid.length = 0;
176
+ all.length = 0;
177
+ });
178
+
179
+ describe('client', () => {
180
+ it('signs a precreate with the common parameters and verifies the answer as sent', async () => {
181
+ const result = await client.precreate({ out_trade_no: 'T1001', total_amount: '88.88', subject: 'Cell T-shirt' });
182
+ expect(result).toEqual({ code: '10000', msg: 'Success', out_trade_no: 'T1001', qr_code: 'https://qr.alipay.com/bax0000' });
183
+ const { params, query } = gateway.calls[0];
184
+ expect(params).toMatchObject({
185
+ app_id: APP_ID,
186
+ method: 'alipay.trade.precreate',
187
+ format: 'JSON',
188
+ charset: 'utf-8',
189
+ sign_type: 'RSA2',
190
+ version: '1.0',
191
+ notify_url: 'https://shop.example.com/alipay/notify',
192
+ });
193
+ expect(params.timestamp).toMatch(/^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/);
194
+ expect(JSON.parse(params.biz_content)).toEqual({ out_trade_no: 'T1001', total_amount: '88.88', subject: 'Cell T-shirt' });
195
+ expect(query.biz_content).toBeUndefined();
196
+ });
197
+
198
+ it("rejects a business failure with CELL_ALIPAY_API_ERROR and Alipay's sub_code", async () => {
199
+ const error = await client.query({ out_trade_no: 'missing' }).catch(e => e);
200
+ expect(AlipayError.is(error, 'CELL_ALIPAY_API_ERROR')).toBe(true);
201
+ expect(error.detail).toMatchObject({ code: '40004', sub_code: 'ACQ.TRADE_NOT_EXIST' });
202
+ });
203
+
204
+ it('rejects an answer whose signature does not match', async () => {
205
+ gateway.tamper = true;
206
+ const error = await client.query({ out_trade_no: 'T1' }).catch(e => e);
207
+ expect(AlipayError.is(error, 'CELL_ALIPAY_SIGNATURE_INVALID')).toBe(true);
208
+ });
209
+
210
+ it('gives the gateway the signature error of a wrong application key', async () => {
211
+ gateway.appKey = generateKeyPairSync('rsa', { modulusLength: 2048 }).publicKey;
212
+ const error = await client.refund({ out_trade_no: 'T1', refund_amount: '1.00' }).catch(e => e);
213
+ expect(error.detail?.sub_code).toBe('isv.invalid-signature');
214
+ });
215
+
216
+ it('builds a page payment URL and a self-submitting form that the gateway accepts', async () => {
217
+ const url = new URL(
218
+ client.pagePay({ out_trade_no: 'T2', total_amount: '0.01', subject: '测试 & <b>' }, { return_url: 'https://shop.example.com/done' }),
219
+ );
220
+ const params = Object.fromEntries(url.searchParams);
221
+ expect(`${url.origin}${url.pathname}`).toBe(gateway.url);
222
+ expect(params).toMatchObject({
223
+ method: 'alipay.trade.page.pay',
224
+ return_url: 'https://shop.example.com/done',
225
+ notify_url: 'https://shop.example.com/alipay/notify',
226
+ });
227
+ expect(JSON.parse(params.biz_content)).toMatchObject({ product_code: 'FAST_INSTANT_TRADE_PAY', subject: '测试 & <b>' });
228
+ expect(AlipayUtil.verifyText(AlipayUtil.signContent(params), params.sign, app.publicKey)).toBe(true);
229
+ const form = client.wapPay({ out_trade_no: 'T3', total_amount: '0.01', subject: 'x"y' }, { httpMethod: 'POST' });
230
+ expect(form).toStartWith(`<form id="alipay" action="${gateway.url}?charset=utf-8" method="post">`);
231
+ expect(form).toContain('&quot;product_code&quot;:&quot;QUICK_WAP_WAY&quot;');
232
+ expect(form).toContain('x\\&quot;y');
233
+ });
234
+
235
+ it('builds the signed order string of the App SDK', () => {
236
+ const params = Object.fromEntries(new URLSearchParams(client.appPay({ out_trade_no: 'T4', total_amount: '1.00', subject: 'a b' })));
237
+ expect(params.method).toBe('alipay.trade.app.pay');
238
+ expect(AlipayUtil.verifyText(AlipayUtil.signContent(params), params.sign, app.publicKey)).toBe(true);
239
+ });
240
+
241
+ it("sends the certificate serial numbers and checks Alipay's in certificate mode", async () => {
242
+ const certified = clientWith({
243
+ ...config().alipay,
244
+ alipayPublicKey: undefined,
245
+ privateKey: TEST_APP_PRIVATE_KEY,
246
+ appCert: TEST_APP_CERT,
247
+ alipayPublicCert: TEST_ALIPAY_CERT,
248
+ alipayRootCert: TEST_ROOT_CERT,
249
+ });
250
+ gateway.appKey = new X509Certificate(TEST_APP_CERT).publicKey;
251
+ gateway.signer = TEST_ALIPAY_PRIVATE_KEY;
252
+ gateway.certSn = AlipayUtil.certSn(TEST_ALIPAY_CERT);
253
+ expect(await certified.query({ out_trade_no: 'T5' })).toMatchObject({ trade_status: 'TRADE_SUCCESS' });
254
+ expect(gateway.calls[0].params).toMatchObject({
255
+ app_cert_sn: AlipayUtil.certSn(TEST_APP_CERT),
256
+ alipay_root_cert_sn: AlipayUtil.rootCertSn(TEST_ROOT_CERT),
257
+ });
258
+ gateway.certSn = 'rotated';
259
+ const error = await certified.query({ out_trade_no: 'T5' }).catch(e => e);
260
+ expect(AlipayError.is(error, 'CELL_ALIPAY_SIGNATURE_INVALID')).toBe(true);
261
+ });
262
+
263
+ it('says what is missing when the application is not configured', async () => {
264
+ const error = await clientWith({ appId: APP_ID, privateKey: 'x', appCert: TEST_APP_CERT })
265
+ .query({ out_trade_no: 'T1' })
266
+ .catch(e => e);
267
+ expect(AlipayError.is(error, 'CELL_ALIPAY_NOT_CONFIGURED')).toBe(true);
268
+ expect(error.message).toContain('all of appCert, alipayPublicCert and alipayRootCert');
269
+ });
270
+ });
271
+
272
+ describe('notification endpoint', () => {
273
+ function notify(fields: Record<string, string>, key: KeyObject = alipay.privateKey): Promise<Response> {
274
+ const params: Record<string, string> = {
275
+ notify_id: 'N1',
276
+ notify_type: 'trade_status_sync',
277
+ notify_time: '2026-11-09 10:00:00',
278
+ app_id: APP_ID,
279
+ charset: 'utf-8',
280
+ version: '1.0',
281
+ sign_type: 'RSA2',
282
+ ...fields,
283
+ };
284
+ params.sign = AlipayUtil.signText(AlipayUtil.signContent(params, ['sign_type']), key);
285
+ return fetch(`${base}/alipay/notify`, {
286
+ method: 'POST',
287
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
288
+ body: new URLSearchParams(params).toString(),
289
+ });
290
+ }
291
+
292
+ it('verifies the form and hands it to the handlers of its trade status, then answers success', async () => {
293
+ const response = await notify({
294
+ trade_status: 'TRADE_SUCCESS',
295
+ out_trade_no: 'T1001',
296
+ trade_no: '2026110922001',
297
+ total_amount: '88.88',
298
+ subject: '中文 & 空格',
299
+ });
300
+ expect(response.status).toBe(200);
301
+ expect(await response.text()).toBe('success');
302
+ expect(paid).toHaveLength(1);
303
+ expect(paid[0]).toMatchObject({ out_trade_no: 'T1001', total_amount: '88.88', subject: '中文 & 空格' });
304
+ expect(all).toEqual(['TRADE_SUCCESS']);
305
+ });
306
+
307
+ it('runs only the handlers of all notifications for another status', async () => {
308
+ expect(await (await notify({ trade_status: 'TRADE_CLOSED', out_trade_no: 'T1' })).text()).toBe('success');
309
+ expect(paid).toHaveLength(0);
310
+ expect(all).toEqual(['TRADE_CLOSED']);
311
+ });
312
+
313
+ it('answers fail to a forged signature and to another application', async () => {
314
+ const forged = await notify({ trade_status: 'TRADE_SUCCESS', out_trade_no: 'T1' }, generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey);
315
+ expect(forged.status).toBe(400);
316
+ expect(await forged.text()).toBe('fail');
317
+ expect((await notify({ trade_status: 'TRADE_SUCCESS', app_id: '2021000000000002' })).status).toBe(400);
318
+ expect(paid).toHaveLength(0);
319
+ });
320
+
321
+ it('answers fail when a handler throws, so Alipay retries', async () => {
322
+ const response = await notify({ trade_status: 'TRADE_SUCCESS', out_trade_no: 'boom' });
323
+ expect(response.status).toBe(500);
324
+ expect(await response.text()).toBe('fail');
325
+ });
326
+
327
+ it('leaves other requests to the application', async () => {
328
+ expect((await fetch(`${base}/health`)).status).toBe(200);
329
+ });
330
+ });
331
+ });
@@ -0,0 +1,5 @@
1
+ export * from './alipay-client';
2
+ export * from './alipay-error';
3
+ export * from './alipay-notification-middleware';
4
+ export * from './alipay-protocol';
5
+ export * from './alipay-util';
@@ -0,0 +1,4 @@
1
+ import { autoBind } from '@celljs/core';
2
+ import './index';
3
+
4
+ export default autoBind();