@hot-updater/cloudflare 1.0.0-rc.43 → 1.0.0-rc.44

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.
@@ -1,7 +1,5 @@
1
- import { createEngineDatabase, createSqlAdapter, createStorageAdapter, createStorageDownloadUrl, createStorageKeyBuilder, createStorageUri, parseStorageUri } from "@hot-updater/plugin-core";
2
- import { apiKeys } from "@hot-updater/server/plugins/api-keys";
3
- import { insights } from "@hot-updater/server/plugins/insights";
4
- import { remoteConfig } from "@hot-updater/server/plugins/remote-config";
1
+ import { createEngineDatabase, createSqlAdapter, createStorageAdapter, createStorageKeyBuilder, createStorageUri, parseStorageUri } from "@hot-updater/plugin-core";
2
+ import { apiKeys, insights, remoteConfig } from "@hot-updater/server/plugins";
5
3
  //#region src/d1Executor.ts
6
4
  var D1ExecutionError = class extends Error {
7
5
  name = "D1ExecutionError";
@@ -72,10 +70,70 @@ const plugins = [
72
70
  remoteConfig()
73
71
  ];
74
72
  //#endregion
73
+ //#region src/presignR2Url.ts
74
+ const encoder = new TextEncoder();
75
+ const hex = (bytes) => Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
76
+ const hmac = async (key, value) => crypto.subtle.sign("HMAC", await crypto.subtle.importKey("raw", key, {
77
+ hash: "SHA-256",
78
+ name: "HMAC"
79
+ }, false, ["sign"]), encoder.encode(value));
80
+ /** RFC 3986 encoding, which S3 signs keys and query values in. */
81
+ const encodeRfc3986 = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
82
+ /**
83
+ * A presigned GET URL for an object on R2's S3-compatible API: AWS Signature
84
+ * Version 4 on Web Crypto, in the form `getSignedUrl` from
85
+ * `@aws-sdk/s3-request-presigner` signs, so a Worker presigns without the
86
+ * AWS SDK.
87
+ */
88
+ const presignR2GetUrl = async ({ accountId, bucketName, credentials, expiresInSeconds, key, signingDate = /* @__PURE__ */ new Date() }) => {
89
+ const host = `${accountId}.r2.cloudflarestorage.com`;
90
+ const path = `/${bucketName}/${key.split("/").map(encodeRfc3986).join("/")}`;
91
+ const amzDate = signingDate.toISOString().replace(/[-:]|\.\d{3}/g, "");
92
+ const scope = `${amzDate.slice(0, 8)}/auto/s3/aws4_request`;
93
+ const query = [
94
+ ["X-Amz-Algorithm", "AWS4-HMAC-SHA256"],
95
+ ["X-Amz-Content-Sha256", "UNSIGNED-PAYLOAD"],
96
+ ["X-Amz-Credential", `${credentials.accessKeyId}/${scope}`],
97
+ ["X-Amz-Date", amzDate],
98
+ ["X-Amz-Expires", String(expiresInSeconds)],
99
+ ["X-Amz-SignedHeaders", "host"],
100
+ ["x-id", "GetObject"]
101
+ ];
102
+ const queryString = (entries) => entries.map(([name, value]) => `${encodeRfc3986(name)}=${encodeRfc3986(value)}`).join("&");
103
+ const canonicalRequest = [
104
+ "GET",
105
+ path,
106
+ queryString(query),
107
+ `host:${host}\n`,
108
+ "host",
109
+ "UNSIGNED-PAYLOAD"
110
+ ].join("\n");
111
+ const stringToSign = [
112
+ "AWS4-HMAC-SHA256",
113
+ amzDate,
114
+ scope,
115
+ hex(await crypto.subtle.digest("SHA-256", encoder.encode(canonicalRequest)))
116
+ ].join("\n");
117
+ let signingKey = encoder.encode(`AWS4${credentials.secretAccessKey}`).buffer;
118
+ for (const part of [
119
+ amzDate.slice(0, 8),
120
+ "auto",
121
+ "s3",
122
+ "aws4_request"
123
+ ]) signingKey = await hmac(signingKey, part);
124
+ const signature = hex(await hmac(signingKey, stringToSign));
125
+ return `https://${host}${path}?${queryString([
126
+ ...query.slice(0, 5),
127
+ ["X-Amz-Signature", signature],
128
+ ...query.slice(5)
129
+ ])}`;
130
+ };
131
+ //#endregion
75
132
  //#region src/r2WorkerStorage.ts
76
- const r2WorkerStorage = (config) => {
133
+ /** Devices download right after the update check that returns the URL. */
134
+ const PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
135
+ function r2WorkerStorage(config) {
77
136
  const getStorageKey = createStorageKeyBuilder(config.basePath);
78
- const getDownloadUrl = createStorageDownloadUrl(config.downloadUrlSigningKey);
79
137
  const parseAndValidate = (storageUri) => {
80
138
  const parsed = parseStorageUri(storageUri, "r2");
81
139
  if (parsed.bucket !== config.bucketName) throw new Error(`Bucket name mismatch: expected "${config.bucketName}", but found "${parsed.bucket}".`);
@@ -113,10 +171,16 @@ const r2WorkerStorage = (config) => {
113
171
  headers.set("content-length", String(object.size));
114
172
  return { response: new Response(object.body, { headers }) };
115
173
  },
116
- async getDownloadUrl({ storageUri }) {
117
- parseAndValidate(storageUri);
118
- return getDownloadUrl({ storageUri });
119
- },
174
+ ...config.credentials === void 0 ? {} : { async getDownloadUrl({ storageUri }) {
175
+ const { key } = parseAndValidate(storageUri);
176
+ return { url: await presignR2GetUrl({
177
+ accountId: config.accountId,
178
+ bucketName: config.bucketName,
179
+ credentials: config.credentials,
180
+ expiresInSeconds: PRESIGNED_URL_EXPIRES_IN_SECONDS,
181
+ key
182
+ }) };
183
+ } },
120
184
  async exists({ storageUri }) {
121
185
  const { key } = parseAndValidate(storageUri);
122
186
  return { exists: await config.bucket.head(key) !== null };
@@ -127,6 +191,6 @@ const r2WorkerStorage = (config) => {
127
191
  return { deleted: true };
128
192
  }
129
193
  });
130
- };
194
+ }
131
195
  //#endregion
132
196
  export { d1Database, plugins, r2WorkerStorage as r2Storage };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hot-updater/cloudflare",
3
3
  "type": "module",
4
- "version": "1.0.0-rc.43",
4
+ "version": "1.0.0-rc.44",
5
5
  "description": "React Native OTA solution for self-hosted",
6
6
  "main": "dist/index.cjs",
7
7
  "module": "dist/index.mjs",
@@ -53,13 +53,14 @@
53
53
  "dependencies": {
54
54
  "@aws-sdk/client-s3": "3.1066.0",
55
55
  "@aws-sdk/lib-storage": "3.1008.0",
56
+ "@aws-sdk/s3-request-presigner": "3.1066.0",
56
57
  "cloudflare": "4.2.0",
57
58
  "hono": "4.12.34",
58
59
  "uuidv7": "^1.0.2",
59
- "@hot-updater/cli-tools": "1.0.0-rc.43",
60
- "@hot-updater/protocol": "1.0.0-rc.43",
61
- "@hot-updater/plugin-core": "1.0.0-rc.43",
62
- "@hot-updater/server": "1.0.0-rc.43"
60
+ "@hot-updater/protocol": "1.0.0-rc.44",
61
+ "@hot-updater/cli-tools": "1.0.0-rc.44",
62
+ "@hot-updater/plugin-core": "1.0.0-rc.44",
63
+ "@hot-updater/server": "1.0.0-rc.44"
63
64
  },
64
65
  "devDependencies": {
65
66
  "@cloudflare/vitest-pool-workers": "0.13.0",
@@ -75,7 +76,7 @@
75
76
  "vitest": "4.1.4",
76
77
  "wrangler": "^4.69.0",
77
78
  "xdg-app-paths": "^8.3.0",
78
- "@hot-updater/test-utils": "1.0.0-rc.43"
79
+ "@hot-updater/test-utils": "1.0.0-rc.44"
79
80
  },
80
81
  "scripts": {
81
82
  "build": "tsdown && pnpm build:worker",
package/src/plugins.ts CHANGED
@@ -1,6 +1,4 @@
1
- import { apiKeys } from "@hot-updater/server/plugins/api-keys";
2
- import { insights } from "@hot-updater/server/plugins/insights";
3
- import { remoteConfig } from "@hot-updater/server/plugins/remote-config";
1
+ import { apiKeys, insights, remoteConfig } from "@hot-updater/server/plugins";
4
2
 
5
3
  /**
6
4
  * The plugins the managed Cloudflare server runs: Insights, API keys on every
@@ -0,0 +1,103 @@
1
+ const encoder = new TextEncoder();
2
+
3
+ const hex = (bytes: ArrayBuffer) =>
4
+ Array.from(new Uint8Array(bytes), (byte) =>
5
+ byte.toString(16).padStart(2, "0"),
6
+ ).join("");
7
+
8
+ const hmac = async (key: BufferSource, value: string) =>
9
+ crypto.subtle.sign(
10
+ "HMAC",
11
+ await crypto.subtle.importKey(
12
+ "raw",
13
+ key,
14
+ { hash: "SHA-256", name: "HMAC" },
15
+ false,
16
+ ["sign"],
17
+ ),
18
+ encoder.encode(value),
19
+ );
20
+
21
+ /** RFC 3986 encoding, which S3 signs keys and query values in. */
22
+ const encodeRfc3986 = (value: string) =>
23
+ encodeURIComponent(value).replace(
24
+ /[!'()*]/g,
25
+ (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
26
+ );
27
+
28
+ /** R2's S3-compatible credentials. */
29
+ export interface R2Credentials {
30
+ readonly accessKeyId: string;
31
+ readonly secretAccessKey: string;
32
+ }
33
+
34
+ /**
35
+ * A presigned GET URL for an object on R2's S3-compatible API: AWS Signature
36
+ * Version 4 on Web Crypto, in the form `getSignedUrl` from
37
+ * `@aws-sdk/s3-request-presigner` signs, so a Worker presigns without the
38
+ * AWS SDK.
39
+ */
40
+ export const presignR2GetUrl = async ({
41
+ accountId,
42
+ bucketName,
43
+ credentials,
44
+ expiresInSeconds,
45
+ key,
46
+ signingDate = new Date(),
47
+ }: {
48
+ readonly accountId: string;
49
+ readonly bucketName: string;
50
+ readonly credentials: R2Credentials;
51
+ readonly expiresInSeconds: number;
52
+ /** The object's key, unencoded. */
53
+ readonly key: string;
54
+ readonly signingDate?: Date;
55
+ }): Promise<string> => {
56
+ const host = `${accountId}.r2.cloudflarestorage.com`;
57
+ const path = `/${bucketName}/${key.split("/").map(encodeRfc3986).join("/")}`;
58
+ const amzDate = signingDate.toISOString().replace(/[-:]|\.\d{3}/g, "");
59
+ const scope = `${amzDate.slice(0, 8)}/auto/s3/aws4_request`;
60
+ // Sorted by name, as the canonical request orders them.
61
+ const query: [string, string][] = [
62
+ ["X-Amz-Algorithm", "AWS4-HMAC-SHA256"],
63
+ ["X-Amz-Content-Sha256", "UNSIGNED-PAYLOAD"],
64
+ ["X-Amz-Credential", `${credentials.accessKeyId}/${scope}`],
65
+ ["X-Amz-Date", amzDate],
66
+ ["X-Amz-Expires", String(expiresInSeconds)],
67
+ ["X-Amz-SignedHeaders", "host"],
68
+ ["x-id", "GetObject"],
69
+ ];
70
+ const queryString = (entries: [string, string][]) =>
71
+ entries
72
+ .map(([name, value]) => `${encodeRfc3986(name)}=${encodeRfc3986(value)}`)
73
+ .join("&");
74
+ const canonicalRequest = [
75
+ "GET",
76
+ path,
77
+ queryString(query),
78
+ `host:${host}\n`,
79
+ "host",
80
+ "UNSIGNED-PAYLOAD",
81
+ ].join("\n");
82
+ const stringToSign = [
83
+ "AWS4-HMAC-SHA256",
84
+ amzDate,
85
+ scope,
86
+ hex(
87
+ await crypto.subtle.digest("SHA-256", encoder.encode(canonicalRequest)),
88
+ ),
89
+ ].join("\n");
90
+ let signingKey: ArrayBuffer = encoder.encode(
91
+ `AWS4${credentials.secretAccessKey}`,
92
+ ).buffer as ArrayBuffer;
93
+ for (const part of [amzDate.slice(0, 8), "auto", "s3", "aws4_request"]) {
94
+ signingKey = await hmac(signingKey, part);
95
+ }
96
+ const signature = hex(await hmac(signingKey, stringToSign));
97
+ const signed: [string, string][] = [
98
+ ...query.slice(0, 5),
99
+ ["X-Amz-Signature", signature],
100
+ ...query.slice(5),
101
+ ];
102
+ return `https://${host}${path}?${queryString(signed)}`;
103
+ };
@@ -6,9 +6,9 @@ import {
6
6
  type S3ClientConfig,
7
7
  } from "@aws-sdk/client-s3";
8
8
  import { Upload } from "@aws-sdk/lib-storage";
9
+ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
9
10
  import {
10
11
  createStorageKeyBuilder,
11
- createStorageDownloadUrl,
12
12
  createStorageAdapter,
13
13
  createStorageUri,
14
14
  parseStorageUri,
@@ -21,10 +21,11 @@ export interface R2S3StorageConfig extends S3ClientConfig {
21
21
  credentials: NonNullable<S3ClientConfig["credentials"]>;
22
22
  /** Base path where bundles will be stored in the bucket. */
23
23
  basePath?: string;
24
- /** Required when this storage serves downloads through createHotUpdater. */
25
- downloadUrlSigningKey?: string;
26
24
  }
27
25
 
26
+ /** Devices download right after the update check that returns the URL. */
27
+ const PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
28
+
28
29
  const isObjectNotFoundError = (error: unknown) => {
29
30
  if (
30
31
  error instanceof Error &&
@@ -43,12 +44,13 @@ const isObjectNotFoundError = (error: unknown) => {
43
44
 
44
45
  export const createR2S3Storage = (
45
46
  config: R2S3StorageConfig,
46
- ): StorageAdapterWith<"put" | "get" | "exists" | "delete"> => {
47
+ ): StorageAdapterWith<
48
+ "put" | "get" | "getDownloadUrl" | "exists" | "delete"
49
+ > => {
47
50
  const {
48
51
  accountId,
49
52
  basePath,
50
53
  bucketName,
51
- downloadUrlSigningKey,
52
54
  endpoint,
53
55
  forcePathStyle,
54
56
  region,
@@ -61,9 +63,6 @@ export const createR2S3Storage = (
61
63
  region: region ?? "auto",
62
64
  });
63
65
  const getStorageKey = createStorageKeyBuilder(basePath);
64
- const getDownloadUrl = downloadUrlSigningKey
65
- ? createStorageDownloadUrl(downloadUrlSigningKey)
66
- : undefined;
67
66
 
68
67
  const parseAndValidate = (storageUri: string) => {
69
68
  const parsed = parseStorageUri(storageUri, "r2");
@@ -122,14 +121,16 @@ export const createR2S3Storage = (
122
121
  throw error;
123
122
  }
124
123
  },
125
- ...(getDownloadUrl
126
- ? {
127
- async getDownloadUrl({ storageUri }: { storageUri: string }) {
128
- parseAndValidate(storageUri);
129
- return getDownloadUrl({ storageUri });
130
- },
131
- }
132
- : {}),
124
+ async getDownloadUrl({ storageUri }) {
125
+ const { key } = parseAndValidate(storageUri);
126
+ return {
127
+ url: await getSignedUrl(
128
+ client,
129
+ new GetObjectCommand({ Bucket: bucketName, Key: key }),
130
+ { expiresIn: PRESIGNED_URL_EXPIRES_IN_SECONDS },
131
+ ),
132
+ };
133
+ },
133
134
  async exists({ storageUri }) {
134
135
  const { key } = parseAndValidate(storageUri);
135
136
  try {
package/src/r2Storage.ts CHANGED
@@ -7,10 +7,12 @@ export type { R2S3StorageConfig };
7
7
 
8
8
  export const r2Storage = (
9
9
  config: R2S3StorageConfig,
10
- ): StorageAdapterWith<"put" | "get" | "exists" | "delete"> => {
10
+ ): StorageAdapterWith<
11
+ "put" | "get" | "getDownloadUrl" | "exists" | "delete"
12
+ > => {
11
13
  if (!config.credentials) {
12
14
  throw new Error(
13
- "r2Storage requires S3-compatible credentials. The Wrangler fallback was removed.",
15
+ "r2Storage requires S3-compatible credentials: pass credentials with an R2 access key ID and secret access key.",
14
16
  );
15
17
  }
16
18
 
@@ -1,26 +1,52 @@
1
1
  import {
2
2
  createStorageKeyBuilder,
3
- createStorageDownloadUrl,
4
3
  createStorageAdapter,
5
4
  createStorageUri,
6
5
  parseStorageUri,
7
6
  type StorageAdapterWith,
8
7
  } from "@hot-updater/plugin-core";
9
8
 
10
- export interface CloudflareWorkerStorageConfig {
9
+ import { presignR2GetUrl, type R2Credentials } from "./presignR2Url";
10
+
11
+ export type CloudflareWorkerStorageConfig = {
11
12
  readonly bucket: R2Bucket;
12
13
  readonly bucketName: string;
13
14
  readonly basePath?: string;
14
- readonly downloadUrlSigningKey: string;
15
- }
15
+ } & (
16
+ | {
17
+ /** The account whose R2 endpoint download URLs name. */
18
+ readonly accountId: string;
19
+ /**
20
+ * R2's S3-compatible credentials, which presign download URLs, as
21
+ * `r2Storage` from `@hot-updater/cloudflare` does: what a server needs
22
+ * to serve downloads.
23
+ */
24
+ readonly credentials: R2Credentials;
25
+ }
26
+ | { readonly accountId?: undefined; readonly credentials?: undefined }
27
+ );
28
+
29
+ /** Devices download right after the update check that returns the URL. */
30
+ const PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
16
31
 
17
- export const r2WorkerStorage = (
32
+ /**
33
+ * Storage on the Worker's R2 binding. With R2's S3-compatible credentials,
34
+ * its download URLs are presigned and devices download from the bucket;
35
+ * without them, it has no `getDownloadUrl`, as a Console that only reads
36
+ * needs.
37
+ */
38
+ export function r2WorkerStorage(
39
+ config: CloudflareWorkerStorageConfig & {
40
+ readonly credentials: R2Credentials;
41
+ },
42
+ ): StorageAdapterWith<"put" | "get" | "getDownloadUrl" | "exists" | "delete">;
43
+ export function r2WorkerStorage(
18
44
  config: CloudflareWorkerStorageConfig,
19
- ): StorageAdapterWith<
20
- "put" | "get" | "getDownloadUrl" | "exists" | "delete"
21
- > => {
45
+ ): StorageAdapterWith<"put" | "get" | "exists" | "delete">;
46
+ export function r2WorkerStorage(
47
+ config: CloudflareWorkerStorageConfig,
48
+ ): StorageAdapterWith<"put" | "get" | "exists" | "delete"> {
22
49
  const getStorageKey = createStorageKeyBuilder(config.basePath);
23
- const getDownloadUrl = createStorageDownloadUrl(config.downloadUrlSigningKey);
24
50
 
25
51
  const parseAndValidate = (storageUri: string) => {
26
52
  const parsed = parseStorageUri(storageUri, "r2");
@@ -77,10 +103,22 @@ export const r2WorkerStorage = (
77
103
  headers.set("content-length", String(object.size));
78
104
  return { response: new Response(object.body, { headers }) };
79
105
  },
80
- async getDownloadUrl({ storageUri }) {
81
- parseAndValidate(storageUri);
82
- return getDownloadUrl({ storageUri });
83
- },
106
+ ...(config.credentials === undefined
107
+ ? {}
108
+ : {
109
+ async getDownloadUrl({ storageUri }: { storageUri: string }) {
110
+ const { key } = parseAndValidate(storageUri);
111
+ return {
112
+ url: await presignR2GetUrl({
113
+ accountId: config.accountId,
114
+ bucketName: config.bucketName,
115
+ credentials: config.credentials,
116
+ expiresInSeconds: PRESIGNED_URL_EXPIRES_IN_SECONDS,
117
+ key,
118
+ }),
119
+ };
120
+ },
121
+ }),
84
122
  async exists({ storageUri }) {
85
123
  const { key } = parseAndValidate(storageUri);
86
124
  return { exists: (await config.bucket.head(key)) !== null };
@@ -91,4 +129,4 @@ export const r2WorkerStorage = (
91
129
  return { deleted: true };
92
130
  },
93
131
  });
94
- };
132
+ }
@@ -1 +1 @@
1
- This folder contains the built output assets for the worker "hot-updater" generated at 2026-10-09T07:58:40.468Z.
1
+ This folder contains the built output assets for the worker "hot-updater" generated at 2026-10-10T01:11:34.985Z.