@stacklift/sdk-js 0.0.0-stage → 0.1.3
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 +110 -0
- package/README.md +31 -2
- package/dist/client.d.ts +98 -0
- package/dist/client.js +155 -0
- package/dist/device.d.ts +10 -0
- package/dist/device.js +20 -0
- package/dist/encoding.d.ts +2 -0
- package/dist/encoding.js +27 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +16 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +24 -0
- package/dist/verify.d.ts +16 -0
- package/dist/verify.js +42 -0
- package/package.json +55 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# Functional Source License, Version 1.1, MIT Future License
|
|
2
|
+
|
|
3
|
+
## Abbreviation
|
|
4
|
+
|
|
5
|
+
FSL-1.1-MIT
|
|
6
|
+
|
|
7
|
+
## Notice
|
|
8
|
+
|
|
9
|
+
Copyright 2026 Stacklift
|
|
10
|
+
|
|
11
|
+
## Terms and Conditions
|
|
12
|
+
|
|
13
|
+
### Licensor ("We")
|
|
14
|
+
|
|
15
|
+
The party offering the Software under these Terms and Conditions.
|
|
16
|
+
|
|
17
|
+
### The Software
|
|
18
|
+
|
|
19
|
+
The "Software" is each version of the software that we make available under
|
|
20
|
+
these Terms and Conditions, as indicated by our inclusion of these Terms and
|
|
21
|
+
Conditions with the Software.
|
|
22
|
+
|
|
23
|
+
### License Grant
|
|
24
|
+
|
|
25
|
+
Subject to your compliance with this License Grant and the Patents,
|
|
26
|
+
Redistribution and Trademark clauses below, we hereby grant you the right to
|
|
27
|
+
use, copy, modify, create derivative works, publicly perform, publicly display
|
|
28
|
+
and redistribute the Software for any Permitted Purpose identified below.
|
|
29
|
+
|
|
30
|
+
### Permitted Purpose
|
|
31
|
+
|
|
32
|
+
A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
|
|
33
|
+
means making the Software available to others in a commercial product or
|
|
34
|
+
service that:
|
|
35
|
+
|
|
36
|
+
1. substitutes for the Software;
|
|
37
|
+
|
|
38
|
+
2. substitutes for any other product or service we offer using the Software
|
|
39
|
+
that exists as of the date we make the Software available; or
|
|
40
|
+
|
|
41
|
+
3. offers the same or substantially similar functionality as the Software.
|
|
42
|
+
|
|
43
|
+
Permitted Purposes specifically include using the Software:
|
|
44
|
+
|
|
45
|
+
1. for your internal use and access;
|
|
46
|
+
|
|
47
|
+
2. for non-commercial education;
|
|
48
|
+
|
|
49
|
+
3. for non-commercial research; and
|
|
50
|
+
|
|
51
|
+
4. in connection with professional services that you provide to a licensee
|
|
52
|
+
using the Software in accordance with these Terms and Conditions.
|
|
53
|
+
|
|
54
|
+
### Patents
|
|
55
|
+
|
|
56
|
+
To the extent your use for a Permitted Purpose would necessarily infringe our
|
|
57
|
+
patents, the license grant above includes a license under our patents. If you
|
|
58
|
+
make a claim against any party that the Software infringes or contributes to
|
|
59
|
+
the infringement of any patent, then your patent license to the Software ends
|
|
60
|
+
immediately.
|
|
61
|
+
|
|
62
|
+
### Redistribution
|
|
63
|
+
|
|
64
|
+
The Terms and Conditions apply to all copies, modifications and derivatives of
|
|
65
|
+
the Software.
|
|
66
|
+
|
|
67
|
+
If you redistribute any copies, modifications or derivatives of the Software,
|
|
68
|
+
you must include a copy of or a link to these Terms and Conditions and not
|
|
69
|
+
remove any copyright notices provided in or with the Software.
|
|
70
|
+
|
|
71
|
+
### Disclaimer
|
|
72
|
+
|
|
73
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
|
|
74
|
+
IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
|
|
75
|
+
PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
|
|
76
|
+
|
|
77
|
+
IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
|
|
78
|
+
SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
|
|
79
|
+
EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
|
|
80
|
+
|
|
81
|
+
### Trademarks
|
|
82
|
+
|
|
83
|
+
Except for displaying the License Details and identifying us as the origin of
|
|
84
|
+
the Software, you have no right under these Terms and Conditions to use our
|
|
85
|
+
trademarks, trade names, service marks or product names.
|
|
86
|
+
|
|
87
|
+
## Grant of Future License
|
|
88
|
+
|
|
89
|
+
We hereby irrevocably grant you an additional license to use the Software under
|
|
90
|
+
the MIT license that is effective on the second anniversary of the date we make
|
|
91
|
+
the Software available. On or after that date, you may use the Software under
|
|
92
|
+
the MIT license, in which case the following will apply:
|
|
93
|
+
|
|
94
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
95
|
+
this software and associated documentation files (the "Software"), to deal in
|
|
96
|
+
the Software without restriction, including without limitation the rights to
|
|
97
|
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
|
98
|
+
of the Software, and to permit persons to whom the Software is furnished to do
|
|
99
|
+
so, subject to the following conditions:
|
|
100
|
+
|
|
101
|
+
The above copyright notice and this permission notice shall be included in all
|
|
102
|
+
copies or substantial portions of the Software.
|
|
103
|
+
|
|
104
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
105
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
106
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
107
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
108
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
109
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
110
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,32 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @stacklift/sdk-js
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Stacklift client SDK for JavaScript and TypeScript. It checks for updates, downloads artifacts and verifies their Ed25519 signature and SHA-256 checksum before handing the bytes to you. No Node built-ins: it runs in Node, browsers, React Native and Capacitor wherever `fetch` exists.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @stacklift/sdk-js
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { StackliftClient, getOrCreateDeviceId } from '@stacklift/sdk-js';
|
|
11
|
+
|
|
12
|
+
const client = new StackliftClient({
|
|
13
|
+
baseUrl: 'https://delivery.example.com',
|
|
14
|
+
apiKey: 'slp_…', // the PUBLIC project key: it can only check for updates, so it is safe inside the app
|
|
15
|
+
pinnedPublicKey: PINNED_PEM, // the project's Ed25519 public key, shipped with the app
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
const deviceId = await getOrCreateDeviceId(storage); // any { getItem, setItem }
|
|
19
|
+
const manifest = await client.check({ channel: 'production', platform: 'ios', runtimeVersion: '2.3.0', currentVersion: '2.3.1', deviceId });
|
|
20
|
+
|
|
21
|
+
if (manifest.updateAvailable) {
|
|
22
|
+
const { bytes } = await client.downloadToMemory(manifest); // verifies signature and checksum; throws on any mismatch
|
|
23
|
+
// apply the bundle with your runtime, then:
|
|
24
|
+
await client.report({ type: 'INSTALL_SUCCESS', releaseId: manifest.release!.id, channel: 'production', platform: 'ios', deviceId });
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Pin the public key. Without it, the key arrives in the same response as the signature, so verification only protects against transport corruption, not a malicious server.
|
|
29
|
+
|
|
30
|
+
This package hands you verified bytes; it never installs or executes anything. For large files, pass an `ArtifactSink` so nothing is buffered in memory. On React Native, install `react-native-get-random-values` first.
|
|
31
|
+
|
|
32
|
+
Full guide: https://github.com/Joynul-Abedin/stacklift/blob/main/docs/sdk.md · License: MIT
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
export type Platform = 'android' | 'ios' | 'web' | 'linux' | 'macos' | 'windows' | 'server';
|
|
2
|
+
export interface CheckInput {
|
|
3
|
+
channel: string;
|
|
4
|
+
platform: Platform;
|
|
5
|
+
/** Compatibility line of the installed binary — only releases built for the same runtime are offered. */
|
|
6
|
+
runtimeVersion: string;
|
|
7
|
+
currentVersion?: string;
|
|
8
|
+
/** Stable per-install id (see getOrCreateDeviceId). 8–128 chars. */
|
|
9
|
+
deviceId: string;
|
|
10
|
+
environment?: string;
|
|
11
|
+
/** Ask for one kind of artifact (e.g. 'ui-layout'), for releases that carry several for the same platform. */
|
|
12
|
+
kind?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface ReleaseInfo {
|
|
15
|
+
id: string;
|
|
16
|
+
version: string;
|
|
17
|
+
runtimeVersion: string;
|
|
18
|
+
description: string | null;
|
|
19
|
+
kind: string;
|
|
20
|
+
platform: Platform;
|
|
21
|
+
/** `filename` is informational and NOT covered by the signature — sanitise it and allow-list extensions before using it. */
|
|
22
|
+
artifact: {
|
|
23
|
+
url: string;
|
|
24
|
+
filename?: string;
|
|
25
|
+
sha256: string;
|
|
26
|
+
size: number;
|
|
27
|
+
signature: string;
|
|
28
|
+
expiresAt: string;
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export interface UpdateManifest {
|
|
32
|
+
updateAvailable: boolean;
|
|
33
|
+
reason?: string;
|
|
34
|
+
release?: ReleaseInfo;
|
|
35
|
+
publicKey?: string;
|
|
36
|
+
}
|
|
37
|
+
export interface UpdateEvent {
|
|
38
|
+
type: 'DOWNLOAD' | 'INSTALL_SUCCESS' | 'INSTALL_FAILURE';
|
|
39
|
+
releaseId: string;
|
|
40
|
+
channel: string;
|
|
41
|
+
platform: Platform;
|
|
42
|
+
deviceId: string;
|
|
43
|
+
fromVersion?: string;
|
|
44
|
+
errorCode?: string;
|
|
45
|
+
errorMessage?: string;
|
|
46
|
+
}
|
|
47
|
+
/** Where verified bytes go. `close()` runs only after every check passed (e.g. rename temp → final); `abort()` on any failure (delete the temp file). */
|
|
48
|
+
export interface ArtifactSink {
|
|
49
|
+
write(chunk: Uint8Array): Promise<void> | void;
|
|
50
|
+
close(): Promise<void> | void;
|
|
51
|
+
abort(): Promise<void> | void;
|
|
52
|
+
}
|
|
53
|
+
export interface DownloadOptions {
|
|
54
|
+
onProgress?: (received: number, total: number) => void;
|
|
55
|
+
signal?: AbortSignal;
|
|
56
|
+
}
|
|
57
|
+
export interface ClientOptions {
|
|
58
|
+
/** Delivery plane base URL, e.g. https://delivery.example.com */
|
|
59
|
+
baseUrl: string;
|
|
60
|
+
/** PUBLIC project key (scopes: updates:check, updates:report). Safe to embed in an app. */
|
|
61
|
+
apiKey: string;
|
|
62
|
+
/**
|
|
63
|
+
* The project's Ed25519 public key (PEM), shipped inside the app. STRONGLY recommended: without it the key arrives in the same
|
|
64
|
+
* response as the signature, so verification only proves integrity against transport corruption, not against a malicious server.
|
|
65
|
+
*/
|
|
66
|
+
pinnedPublicKey?: string;
|
|
67
|
+
fetch?: typeof fetch;
|
|
68
|
+
}
|
|
69
|
+
/** Sent as `x-stacklift-sdk` with every request so the server can tell official SDKs from changed copies. */
|
|
70
|
+
export declare const SDK_IDENTITY = "js/0.1.3 mark=e8875baf";
|
|
71
|
+
export declare class StackliftClient {
|
|
72
|
+
private readonly opts;
|
|
73
|
+
private readonly f;
|
|
74
|
+
constructor(opts: ClientOptions);
|
|
75
|
+
private url;
|
|
76
|
+
private post;
|
|
77
|
+
check(input: CheckInput, signal?: AbortSignal): Promise<UpdateManifest>;
|
|
78
|
+
report(event: UpdateEvent, signal?: AbortSignal): Promise<void>;
|
|
79
|
+
/**
|
|
80
|
+
* Verify the manifest's signature against the pinned (or manifest) key. Throws a typed StackliftError; returns the release only when
|
|
81
|
+
* the signature covers exactly the metadata the manifest claims. Call this BEFORE trusting `release.version`, `kind`, etc.
|
|
82
|
+
*/
|
|
83
|
+
verifyManifest(manifest: UpdateManifest): ReleaseInfo;
|
|
84
|
+
/**
|
|
85
|
+
* Download into `sink`, verifying signature (before any byte is fetched), exact size (aborting as soon as the server sends too much)
|
|
86
|
+
* and SHA-256 (incrementally). `sink.close()` is called only if everything verified; otherwise `sink.abort()` and a typed error.
|
|
87
|
+
*/
|
|
88
|
+
download(manifest: UpdateManifest, sink: ArtifactSink, opts?: DownloadOptions): Promise<{
|
|
89
|
+
sha256: string;
|
|
90
|
+
size: number;
|
|
91
|
+
}>;
|
|
92
|
+
/** Convenience for small artifacts (JS bundles, config). Large installers should stream into a file sink instead. */
|
|
93
|
+
downloadToMemory(manifest: UpdateManifest, opts?: DownloadOptions): Promise<{
|
|
94
|
+
bytes: Uint8Array;
|
|
95
|
+
sha256: string;
|
|
96
|
+
size: number;
|
|
97
|
+
}>;
|
|
98
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.StackliftClient = exports.SDK_IDENTITY = void 0;
|
|
4
|
+
const sha256_1 = require("@noble/hashes/sha256");
|
|
5
|
+
const utils_1 = require("@noble/hashes/utils");
|
|
6
|
+
const errors_1 = require("./errors");
|
|
7
|
+
const verify_1 = require("./verify");
|
|
8
|
+
/** Sent as `x-stacklift-sdk` with every request so the server can tell official SDKs from changed copies. */
|
|
9
|
+
exports.SDK_IDENTITY = 'js/0.1.3 mark=e8875baf';
|
|
10
|
+
class StackliftClient {
|
|
11
|
+
opts;
|
|
12
|
+
f;
|
|
13
|
+
constructor(opts) {
|
|
14
|
+
this.opts = opts;
|
|
15
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
16
|
+
if (!f)
|
|
17
|
+
throw new errors_1.StackliftError('unsupported', 'No fetch implementation available; pass one via options.fetch');
|
|
18
|
+
this.f = f.bind(globalThis);
|
|
19
|
+
}
|
|
20
|
+
url(path) {
|
|
21
|
+
return `${this.opts.baseUrl.replace(/\/+$/, '')}${path}`;
|
|
22
|
+
}
|
|
23
|
+
async post(path, body, signal) {
|
|
24
|
+
let res;
|
|
25
|
+
try {
|
|
26
|
+
res = await this.f(this.url(path), { method: 'POST', headers: { 'content-type': 'application/json', 'x-stacklift-key': this.opts.apiKey, 'x-stacklift-sdk': exports.SDK_IDENTITY }, body: JSON.stringify(body), signal });
|
|
27
|
+
}
|
|
28
|
+
catch (e) {
|
|
29
|
+
throw wrapNetwork(e);
|
|
30
|
+
}
|
|
31
|
+
const text = await res.text();
|
|
32
|
+
let json;
|
|
33
|
+
try {
|
|
34
|
+
json = text ? JSON.parse(text) : undefined;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
json = { message: text.slice(0, 200) };
|
|
38
|
+
}
|
|
39
|
+
if (!res.ok)
|
|
40
|
+
throw new errors_1.StackliftError('http_error', json?.message ?? res.statusText ?? `HTTP ${res.status}`, res.status, json);
|
|
41
|
+
return json;
|
|
42
|
+
}
|
|
43
|
+
async check(input, signal) {
|
|
44
|
+
const m = await this.post('/v1/updates/check', input, signal);
|
|
45
|
+
if (!m || typeof m.updateAvailable !== 'boolean' || (m.updateAvailable && !m.release?.artifact)) {
|
|
46
|
+
throw new errors_1.StackliftError('bad_response', 'Update check returned an unexpected response');
|
|
47
|
+
}
|
|
48
|
+
return m;
|
|
49
|
+
}
|
|
50
|
+
async report(event, signal) {
|
|
51
|
+
await this.post('/v1/updates/events', event, signal);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Verify the manifest's signature against the pinned (or manifest) key. Throws a typed StackliftError; returns the release only when
|
|
55
|
+
* the signature covers exactly the metadata the manifest claims. Call this BEFORE trusting `release.version`, `kind`, etc.
|
|
56
|
+
*/
|
|
57
|
+
verifyManifest(manifest) {
|
|
58
|
+
const rel = manifest.release;
|
|
59
|
+
if (!manifest.updateAvailable || !rel)
|
|
60
|
+
throw new errors_1.StackliftError('no_update', 'No update available');
|
|
61
|
+
const { pinnedPublicKey } = this.opts;
|
|
62
|
+
if (pinnedPublicKey && manifest.publicKey && !(0, verify_1.samePem)(manifest.publicKey, pinnedPublicKey)) {
|
|
63
|
+
throw new errors_1.StackliftError('key_mismatch', 'Manifest public key does not match the key pinned in this app');
|
|
64
|
+
}
|
|
65
|
+
const key = pinnedPublicKey ?? manifest.publicKey;
|
|
66
|
+
if (!key)
|
|
67
|
+
throw new errors_1.StackliftError('no_key', 'No public key available to verify the signature');
|
|
68
|
+
const payload = (0, verify_1.signingPayload)({ sha256: rel.artifact.sha256, size: rel.artifact.size, releaseId: rel.id, version: rel.version, platform: rel.platform, runtimeVersion: rel.runtimeVersion, kind: rel.kind });
|
|
69
|
+
if (!(0, verify_1.verifySignature)(key, payload, rel.artifact.signature)) {
|
|
70
|
+
throw new errors_1.StackliftError('signature_invalid', 'Artifact signature is invalid — refusing to download');
|
|
71
|
+
}
|
|
72
|
+
return rel;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Download into `sink`, verifying signature (before any byte is fetched), exact size (aborting as soon as the server sends too much)
|
|
76
|
+
* and SHA-256 (incrementally). `sink.close()` is called only if everything verified; otherwise `sink.abort()` and a typed error.
|
|
77
|
+
*/
|
|
78
|
+
async download(manifest, sink, opts = {}) {
|
|
79
|
+
const rel = this.verifyManifest(manifest);
|
|
80
|
+
const { size: expectedSize, sha256: expectedSha } = rel.artifact;
|
|
81
|
+
try {
|
|
82
|
+
let res;
|
|
83
|
+
try {
|
|
84
|
+
res = await this.f(rel.artifact.url, { signal: opts.signal });
|
|
85
|
+
}
|
|
86
|
+
catch (e) {
|
|
87
|
+
throw wrapNetwork(e);
|
|
88
|
+
}
|
|
89
|
+
if (!res.ok)
|
|
90
|
+
throw new errors_1.StackliftError('http_error', `Download failed (${res.status})`, res.status);
|
|
91
|
+
const hash = sha256_1.sha256.create();
|
|
92
|
+
let received = 0;
|
|
93
|
+
const push = async (chunk) => {
|
|
94
|
+
received += chunk.length;
|
|
95
|
+
if (received > expectedSize)
|
|
96
|
+
throw new errors_1.StackliftError('size_mismatch', `Server sent more than the signed size (${expectedSize} bytes)`);
|
|
97
|
+
hash.update(chunk);
|
|
98
|
+
await sink.write(chunk);
|
|
99
|
+
opts.onProgress?.(received, expectedSize);
|
|
100
|
+
};
|
|
101
|
+
if (res.body && typeof res.body.getReader === 'function') {
|
|
102
|
+
const reader = res.body.getReader();
|
|
103
|
+
try {
|
|
104
|
+
for (;;) {
|
|
105
|
+
const { done, value } = await reader.read();
|
|
106
|
+
if (done)
|
|
107
|
+
break;
|
|
108
|
+
if (value?.length)
|
|
109
|
+
await push(value);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
catch (e) {
|
|
113
|
+
await reader.cancel().catch(() => undefined);
|
|
114
|
+
throw e instanceof errors_1.StackliftError ? e : wrapNetwork(e);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
// Runtimes without streaming bodies (React Native's default fetch): one buffered chunk.
|
|
119
|
+
await push(new Uint8Array(await res.arrayBuffer()));
|
|
120
|
+
}
|
|
121
|
+
if (received !== expectedSize)
|
|
122
|
+
throw new errors_1.StackliftError('size_mismatch', `Size mismatch: expected ${expectedSize}, got ${received}`);
|
|
123
|
+
const actual = (0, utils_1.bytesToHex)(hash.digest());
|
|
124
|
+
if (actual !== expectedSha)
|
|
125
|
+
throw new errors_1.StackliftError('checksum_mismatch', 'Checksum mismatch — artifact corrupted or tampered');
|
|
126
|
+
await sink.close();
|
|
127
|
+
return { sha256: actual, size: received };
|
|
128
|
+
}
|
|
129
|
+
catch (e) {
|
|
130
|
+
await Promise.resolve(sink.abort()).catch(() => undefined);
|
|
131
|
+
throw e;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/** Convenience for small artifacts (JS bundles, config). Large installers should stream into a file sink instead. */
|
|
135
|
+
async downloadToMemory(manifest, opts) {
|
|
136
|
+
const chunks = [];
|
|
137
|
+
const meta = await this.download(manifest, { write: (c) => void chunks.push(c.slice()), close: () => undefined, abort: () => void (chunks.length = 0) }, opts);
|
|
138
|
+
const bytes = new Uint8Array(meta.size);
|
|
139
|
+
let o = 0;
|
|
140
|
+
for (const c of chunks) {
|
|
141
|
+
bytes.set(c, o);
|
|
142
|
+
o += c.length;
|
|
143
|
+
}
|
|
144
|
+
return { bytes, ...meta };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
exports.StackliftClient = StackliftClient;
|
|
148
|
+
function wrapNetwork(e) {
|
|
149
|
+
if (e instanceof errors_1.StackliftError)
|
|
150
|
+
return e;
|
|
151
|
+
const name = e?.name;
|
|
152
|
+
if (name === 'AbortError')
|
|
153
|
+
return new errors_1.StackliftError('aborted', 'Request aborted');
|
|
154
|
+
return new errors_1.StackliftError('network_error', e?.message ?? 'Network error');
|
|
155
|
+
}
|
package/dist/device.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Anything with async-or-sync get/set: AsyncStorage, localStorage, Capacitor Preferences, electron-store, ... */
|
|
2
|
+
export interface KeyValueStorage {
|
|
3
|
+
getItem(key: string): Promise<string | null | undefined> | string | null | undefined;
|
|
4
|
+
setItem(key: string, value: string): Promise<void> | void;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* A random, app-scoped install identifier. Deliberately NOT derived from hardware, advertising ids or the user:
|
|
8
|
+
* it only needs to be stable per install so rollout cohorts are stable. Reinstalling creates a new one.
|
|
9
|
+
*/
|
|
10
|
+
export declare function getOrCreateDeviceId(storage: KeyValueStorage, key?: string): Promise<string>;
|
package/dist/device.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getOrCreateDeviceId = getOrCreateDeviceId;
|
|
4
|
+
const utils_1 = require("@noble/hashes/utils");
|
|
5
|
+
const errors_1 = require("./errors");
|
|
6
|
+
/**
|
|
7
|
+
* A random, app-scoped install identifier. Deliberately NOT derived from hardware, advertising ids or the user:
|
|
8
|
+
* it only needs to be stable per install so rollout cohorts are stable. Reinstalling creates a new one.
|
|
9
|
+
*/
|
|
10
|
+
async function getOrCreateDeviceId(storage, key = 'stacklift.deviceId') {
|
|
11
|
+
const existing = await storage.getItem(key);
|
|
12
|
+
if (existing && existing.length >= 8)
|
|
13
|
+
return existing;
|
|
14
|
+
const c = globalThis.crypto;
|
|
15
|
+
if (!c?.getRandomValues)
|
|
16
|
+
throw new errors_1.StackliftError('unsupported', 'No secure random source (crypto.getRandomValues). On React Native install react-native-get-random-values.');
|
|
17
|
+
const id = `dev_${(0, utils_1.bytesToHex)(c.getRandomValues(new Uint8Array(16)))}`;
|
|
18
|
+
await storage.setItem(key, id);
|
|
19
|
+
return id;
|
|
20
|
+
}
|
package/dist/encoding.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.base64ToBytes = base64ToBytes;
|
|
4
|
+
// Portable base64 — `atob`/`Buffer` are not guaranteed in every JS runtime (older Hermes, some WebViews).
|
|
5
|
+
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
6
|
+
const LOOKUP = {};
|
|
7
|
+
for (let i = 0; i < ALPHABET.length; i++)
|
|
8
|
+
LOOKUP[ALPHABET[i]] = i;
|
|
9
|
+
/** Strict-ish base64 decode: returns undefined for anything that is not valid base64. */
|
|
10
|
+
function base64ToBytes(input) {
|
|
11
|
+
const s = input.replace(/\s+/g, '');
|
|
12
|
+
if (s.length === 0 || s.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(s))
|
|
13
|
+
return undefined;
|
|
14
|
+
const pad = s.endsWith('==') ? 2 : s.endsWith('=') ? 1 : 0;
|
|
15
|
+
const out = new Uint8Array((s.length / 4) * 3 - pad);
|
|
16
|
+
let o = 0;
|
|
17
|
+
for (let i = 0; i < s.length; i += 4) {
|
|
18
|
+
const n = (LOOKUP[s[i]] << 18) | (LOOKUP[s[i + 1]] << 12) | ((LOOKUP[s[i + 2]] ?? 0) << 6) | (LOOKUP[s[i + 3]] ?? 0);
|
|
19
|
+
if (o < out.length)
|
|
20
|
+
out[o++] = (n >> 16) & 255;
|
|
21
|
+
if (o < out.length)
|
|
22
|
+
out[o++] = (n >> 8) & 255;
|
|
23
|
+
if (o < out.length)
|
|
24
|
+
out[o++] = n & 255;
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export type StackliftErrorCode = 'signature_invalid' | 'key_mismatch' | 'checksum_mismatch' | 'size_mismatch' | 'no_key' | 'no_update' | 'http_error' | 'bad_response' | 'network_error' | 'aborted' | 'unsupported';
|
|
2
|
+
export declare class StackliftError extends Error {
|
|
3
|
+
readonly code: StackliftErrorCode;
|
|
4
|
+
readonly status?: number | undefined;
|
|
5
|
+
readonly body?: unknown | undefined;
|
|
6
|
+
constructor(code: StackliftErrorCode, message: string, status?: number | undefined, body?: unknown | undefined);
|
|
7
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.StackliftError = void 0;
|
|
4
|
+
class StackliftError extends Error {
|
|
5
|
+
code;
|
|
6
|
+
status;
|
|
7
|
+
body;
|
|
8
|
+
constructor(code, message, status, body) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.status = status;
|
|
12
|
+
this.body = body;
|
|
13
|
+
this.name = 'StackliftError';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
exports.StackliftError = StackliftError;
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.publicKeyFromPem = exports.verifySignature = exports.signingPayload = void 0;
|
|
18
|
+
__exportStar(require("./client"), exports);
|
|
19
|
+
__exportStar(require("./device"), exports);
|
|
20
|
+
__exportStar(require("./errors"), exports);
|
|
21
|
+
var verify_1 = require("./verify");
|
|
22
|
+
Object.defineProperty(exports, "signingPayload", { enumerable: true, get: function () { return verify_1.signingPayload; } });
|
|
23
|
+
Object.defineProperty(exports, "verifySignature", { enumerable: true, get: function () { return verify_1.verifySignature; } });
|
|
24
|
+
Object.defineProperty(exports, "publicKeyFromPem", { enumerable: true, get: function () { return verify_1.publicKeyFromPem; } });
|
package/dist/verify.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** The exact text Stacklift signs. Binding every field stops a valid artifact being replayed as another release, platform or kind. */
|
|
2
|
+
export interface SigningFields {
|
|
3
|
+
sha256: string;
|
|
4
|
+
size: number;
|
|
5
|
+
releaseId: string;
|
|
6
|
+
version: string;
|
|
7
|
+
platform: string;
|
|
8
|
+
runtimeVersion: string;
|
|
9
|
+
kind: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function signingPayload(p: SigningFields): string;
|
|
12
|
+
/** Extract the raw 32-byte key from a PEM `PUBLIC KEY` (SPKI). Returns undefined if it is not an Ed25519 public key. */
|
|
13
|
+
export declare function publicKeyFromPem(pem: string): Uint8Array | undefined;
|
|
14
|
+
/** True only for a valid Ed25519 signature over `payload`. Never throws. */
|
|
15
|
+
export declare function verifySignature(publicKeyPem: string, payload: string, signatureB64: string): boolean;
|
|
16
|
+
export declare const samePem: (a: string, b: string) => boolean;
|
package/dist/verify.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.samePem = void 0;
|
|
4
|
+
exports.signingPayload = signingPayload;
|
|
5
|
+
exports.publicKeyFromPem = publicKeyFromPem;
|
|
6
|
+
exports.verifySignature = verifySignature;
|
|
7
|
+
const ed25519_1 = require("@noble/curves/ed25519");
|
|
8
|
+
const utils_1 = require("@noble/hashes/utils");
|
|
9
|
+
const encoding_1 = require("./encoding");
|
|
10
|
+
function signingPayload(p) {
|
|
11
|
+
return ['stacklift-artifact-v1', `sha256:${p.sha256}`, `size:${p.size}`, `release:${p.releaseId}`, `version:${p.version}`, `platform:${p.platform}`, `runtime:${p.runtimeVersion}`, `kind:${p.kind}`].join('\n');
|
|
12
|
+
}
|
|
13
|
+
// DER prefix of an Ed25519 SubjectPublicKeyInfo: SEQUENCE { SEQUENCE { OID 1.3.101.112 } BIT STRING (33 bytes, 0 unused bits) }
|
|
14
|
+
const SPKI_PREFIX = [0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00];
|
|
15
|
+
/** Extract the raw 32-byte key from a PEM `PUBLIC KEY` (SPKI). Returns undefined if it is not an Ed25519 public key. */
|
|
16
|
+
function publicKeyFromPem(pem) {
|
|
17
|
+
const m = /-----BEGIN PUBLIC KEY-----([\s\S]+?)-----END PUBLIC KEY-----/.exec(pem);
|
|
18
|
+
if (!m)
|
|
19
|
+
return undefined;
|
|
20
|
+
const der = (0, encoding_1.base64ToBytes)(m[1]);
|
|
21
|
+
if (!der || der.length !== SPKI_PREFIX.length + 32)
|
|
22
|
+
return undefined;
|
|
23
|
+
for (let i = 0; i < SPKI_PREFIX.length; i++)
|
|
24
|
+
if (der[i] !== SPKI_PREFIX[i])
|
|
25
|
+
return undefined;
|
|
26
|
+
return der.slice(SPKI_PREFIX.length);
|
|
27
|
+
}
|
|
28
|
+
/** True only for a valid Ed25519 signature over `payload`. Never throws. */
|
|
29
|
+
function verifySignature(publicKeyPem, payload, signatureB64) {
|
|
30
|
+
try {
|
|
31
|
+
const key = publicKeyFromPem(publicKeyPem);
|
|
32
|
+
const sig = (0, encoding_1.base64ToBytes)(signatureB64);
|
|
33
|
+
if (!key || !sig || sig.length !== 64)
|
|
34
|
+
return false;
|
|
35
|
+
return ed25519_1.ed25519.verify(sig, (0, utils_1.utf8ToBytes)(payload), key);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const samePem = (a, b) => a.replace(/\s+/g, '') === b.replace(/\s+/g, '');
|
|
42
|
+
exports.samePem = samePem;
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacklift/sdk-js",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.3",
|
|
4
|
+
"description": "Stacklift client SDK for JavaScript and TypeScript: check for updates, download and verify Ed25519-signed artifacts. Works in Node, browsers, React Native and Capacitor.",
|
|
5
|
+
"license": "FSL-1.1-MIT",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"stacklift",
|
|
8
|
+
"ota",
|
|
9
|
+
"updates",
|
|
10
|
+
"ed25519",
|
|
11
|
+
"sdk"
|
|
12
|
+
],
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/Joynul-Abedin/stacklift.git",
|
|
16
|
+
"directory": "packages/sdk-js"
|
|
17
|
+
},
|
|
18
|
+
"bugs": {
|
|
19
|
+
"url": "https://github.com/Joynul-Abedin/stacklift/issues"
|
|
20
|
+
},
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=18"
|
|
23
|
+
},
|
|
24
|
+
"main": "dist/index.js",
|
|
25
|
+
"types": "dist/index.d.ts",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"default": "./dist/index.js"
|
|
30
|
+
},
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
33
|
+
"sideEffects": false,
|
|
34
|
+
"files": [
|
|
35
|
+
"dist/**/*.js",
|
|
36
|
+
"dist/**/*.d.ts",
|
|
37
|
+
"README.md",
|
|
38
|
+
"LICENSE"
|
|
39
|
+
],
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"@noble/curves": "^1.9.0",
|
|
45
|
+
"@noble/hashes": "^1.8.0"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"typescript": "~5.9.3",
|
|
49
|
+
"vitest": "^3.2.0",
|
|
50
|
+
"@types/node": "^22.10.0"
|
|
51
|
+
},
|
|
52
|
+
"scripts": {
|
|
53
|
+
"build": "tsc -p tsconfig.json",
|
|
54
|
+
"dev": "tsc -p tsconfig.json --watch --preserveWatchOutput",
|
|
55
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
56
|
+
"test": "vitest run"
|
|
57
|
+
}
|
|
6
58
|
}
|