@astratra/native 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +93 -1
- package/package.json +5 -3
- package/src/index.d.ts +121 -0
- package/src/index.js +2 -1
- package/src/pictureSource.js +696 -0
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
La plomberie mobile, sans le moteur mobile : **session sécurisée, verrou
|
|
4
4
|
biométrique, notifications natives, retour de paiement, état du réseau, mises à
|
|
5
|
-
jour à distance, cache de médias**.
|
|
5
|
+
jour à distance, cache de médias, sources d'images**.
|
|
6
6
|
|
|
7
7
|
Le package ne charge ni `expo-secure-store`, ni `expo-local-authentication`,
|
|
8
8
|
ni `expo-web-browser`, ni NetInfo, ni `expo-updates`, ni `expo-file-system`. Il les **reçoit**. Même règle que `@astratra/notify`
|
|
@@ -359,3 +359,95 @@ extensions déclarées est traité comme un temporaire abandonné.
|
|
|
359
359
|
L'API historique d'Expo ne sait pas toucher la date d'un fichier sans le
|
|
360
360
|
réécrire : l'éviction suit donc l'ordre de téléchargement, pas celui de
|
|
361
361
|
lecture. Un fichier très relu finit par partir, puis revient au prochain appui.
|
|
362
|
+
|
|
363
|
+
# Images
|
|
364
|
+
|
|
365
|
+
```js
|
|
366
|
+
import * as FileSystem from 'expo-file-system/legacy';
|
|
367
|
+
import * as Sharing from 'expo-sharing';
|
|
368
|
+
import { createPictureSources, createPictureFiles, pictureUti } from '@astratra/native';
|
|
369
|
+
|
|
370
|
+
const pictures = createPictureSources({
|
|
371
|
+
appUrl: API_BASE_URL, // 'https://api.example.com' ou '…/api'
|
|
372
|
+
getToken: () => session.getAccessToken()
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
// Pour <Image> (React Native ou expo-image) : le jeton seulement chez soi.
|
|
376
|
+
const source = await pictures.resolve('/images/abc');
|
|
377
|
+
// { uri: 'https://api.example.com/images/abc', headers: { Authorization: 'Bearer …' } }
|
|
378
|
+
await pictures.resolve('https://cdn.example.org/fig.jpg'); // { uri } — jamais d'en-tête
|
|
379
|
+
await pictures.resolve('https://api.example.com@evil.com/x'); // null — refusée
|
|
380
|
+
|
|
381
|
+
// L'original en fichier, pour Photos ou la feuille de partage.
|
|
382
|
+
const files = createPictureFiles({
|
|
383
|
+
sources: pictures,
|
|
384
|
+
fs: FileSystem,
|
|
385
|
+
directory: `${FileSystem.cacheDirectory}pictures/`
|
|
386
|
+
});
|
|
387
|
+
const uri = await files.named('/images/abc', title, { fallback: t('picture'), query: { original: 1 } });
|
|
388
|
+
await Sharing.shareAsync(uri, { dialogTitle: title, UTI: pictureUti(uri) ?? undefined });
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
Une application montre trois sortes d'images : **les siennes**, servies par son
|
|
392
|
+
API derrière le jeton de la personne (`/images/abc`, ou la même adresse écrite
|
|
393
|
+
en entier) ; celles **du dehors** (une publication, un CDN), chargées telles
|
|
394
|
+
quelles ; celles **intégrées** (`data:image/…`) dans un document.
|
|
395
|
+
|
|
396
|
+
**Le jeton ne part que vers l'origine de l'application.** La première version
|
|
397
|
+
de cette règle était un test de préfixe (`https://` = dehors) et collait le
|
|
398
|
+
chemin après l'URL de base de l'API. Deux adresses qu'on n'a pas écrites
|
|
399
|
+
soi-même suffisaient à envoyer le jeton ailleurs :
|
|
400
|
+
|
|
401
|
+
| Adresse reçue | Collée après `https://api.example.com` | Part vers |
|
|
402
|
+
| --- | --- | --- |
|
|
403
|
+
| `.evil.com/x` | `https://api.example.com.evil.com/x` | evil.com, **avec le jeton** |
|
|
404
|
+
| `@evil.com/x` | `https://api.example.com@evil.com/x` | evil.com, **avec le jeton** |
|
|
405
|
+
|
|
406
|
+
Ici l'adresse est **analysée**, son origine comparée **en entier** (schéma, hôte,
|
|
407
|
+
port — jamais une sous-chaîne ni un préfixe), et ce qui ne s'analyse pas
|
|
408
|
+
proprement est **refusé** au lieu d'être deviné : identifiants dans l'autorité
|
|
409
|
+
(`app.example.com@evil.com`), barre oblique inverse, caractère de contrôle ou
|
|
410
|
+
espace (l'analyseur WHATWG supprime tabulations et retours à la ligne en
|
|
411
|
+
silence), hôte encodé en `%` ou non ASCII, port hors plage, `//hôte` relatif au
|
|
412
|
+
schéma, chemin sans `/` initial. `app.example.com.evil.com`,
|
|
413
|
+
`evil.com/?u=app.example.com`, `cdn.app.example.com`, un autre port ou `http`
|
|
414
|
+
au lieu de `https` sont **d'autres origines** : chargées sans jeton. L'en-tête
|
|
415
|
+
est décidé au dernier moment, sur l'adresse finale (`headersFor`).
|
|
416
|
+
|
|
417
|
+
Pourquoi pas `new URL()` : le polyfill de React Native n'implémente pas
|
|
418
|
+
`hostname` sur toutes les versions, et l'analyseur WHATWG est tolérant
|
|
419
|
+
exactement là où un attaquant s'en sert. Un analyseur strict qui refuse vaut
|
|
420
|
+
mieux qu'un analyseur tolérant qui répare.
|
|
421
|
+
|
|
422
|
+
**Le dehors en `https` seulement** (`allowHttpOutside` pour l'autoriser) : iOS
|
|
423
|
+
bloque `http` de toute façon, et une page qui en charge trahit ce qu'on lit.
|
|
424
|
+
L'origine de l'application elle-même peut être en `http` (développement local).
|
|
425
|
+
|
|
426
|
+
**Les images intégrées** sont jugées sur leur **longueur** avant tout balayage
|
|
427
|
+
(10 Mo décodés par défaut, `maxDataBytes`) : une adresse de 200 Mo est refusée en
|
|
428
|
+
temps constant. Seul l'en-tête est examiné pour sa forme (256 premiers
|
|
429
|
+
caractères). SVG n'est pas accepté par défaut (c'est un document, pas une
|
|
430
|
+
image) ; `dataTypes` pour l'ajouter.
|
|
431
|
+
|
|
432
|
+
**La clé de cache** (`cacheKey`) : l'adresse normalisée — un chemin et la même
|
|
433
|
+
adresse écrite en entier la partagent — **jamais le jeton** ; 106 bits
|
|
434
|
+
(`contentKey`), là où l'ancienne empreinte de 32 bits pouvait faire partager un
|
|
435
|
+
fichier à deux images. `variant` et `version` séparent deux rendus et retirent
|
|
436
|
+
une ancienne règle.
|
|
437
|
+
|
|
438
|
+
**Les fichiers** (`createPictureFiles`) : l'original est téléchargé sous un nom
|
|
439
|
+
temporaire puis déplacé **une fois complet et reconnu**. L'ancienne version
|
|
440
|
+
servait n'importe quel fichier trouvé dans le dossier — un téléchargement coupé
|
|
441
|
+
à mi-chemin devenait l'image, pour toujours. Le type vient des **octets**
|
|
442
|
+
(`sniffPictureType` : PNG, JPEG, GIF, WebP, HEIC, AVIF, BMP), jamais du nom : une
|
|
443
|
+
page d'erreur HTML servie en 200 est refusée (`not_a_picture`) au lieu d'être
|
|
444
|
+
enregistrée dans Photos comme JPEG. Un statut hors 2xx est une erreur `http`.
|
|
445
|
+
Deux appels simultanés partagent un seul téléchargement. Le dossier est borné
|
|
446
|
+
par `createMediaCache`. `named()` en fait une copie au titre de l'image
|
|
447
|
+
(`pictureFileName` : caractères réservés retirés, pas de fichier caché, coupé en
|
|
448
|
+
caractères et non en octets) ; seule la dernière copie nommée est gardée.
|
|
449
|
+
|
|
450
|
+
Les erreurs sont des **codes** (`PictureSourceError`: `refused` + raison,
|
|
451
|
+
`http` + statut, `not_a_picture`), jamais des phrases. La permission de Photos
|
|
452
|
+
(`expo-media-library`) reste à l'application.
|
|
453
|
+
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/native",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Mobile plumbing without the mobile runtime: secure token session with an injected keystore, a biometric gate, native push registration and foreground watching, a checkout round-trip that survives a missing native module, network state that only calls a missing interface offline, over-the-air updates applied when nobody is looking,
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Mobile plumbing without the mobile runtime: secure token session with an injected keystore, a biometric gate, native push registration and foreground watching, a checkout round-trip that survives a missing native module, network state that only calls a missing interface offline, over-the-air updates applied when nobody is looking, a bounded on-disk media cache, and picture sources that send the token to the app's own origin only, with originals kept as files. Adapters injected, so it tests in plain Node.",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=20"
|
|
7
7
|
},
|
|
@@ -30,7 +30,9 @@
|
|
|
30
30
|
"netinfo",
|
|
31
31
|
"offline",
|
|
32
32
|
"expo-updates",
|
|
33
|
-
"cache"
|
|
33
|
+
"cache",
|
|
34
|
+
"image",
|
|
35
|
+
"pictures"
|
|
34
36
|
],
|
|
35
37
|
"license": "MIT",
|
|
36
38
|
"publishConfig": {
|
package/src/index.d.ts
CHANGED
|
@@ -466,3 +466,124 @@ export function createMediaCache(options: {
|
|
|
466
466
|
abandonedAfterMs?: number;
|
|
467
467
|
now?: () => number;
|
|
468
468
|
}): MediaCache;
|
|
469
|
+
|
|
470
|
+
/* ─────────────────────────────── Pictures ────────────────────────────── */
|
|
471
|
+
|
|
472
|
+
export const PICTURE_ADDRESS_MAX_LENGTH: number;
|
|
473
|
+
/** Largest inline picture accepted by default, decoded (10 MB). */
|
|
474
|
+
export const PICTURE_DATA_MAX_BYTES: number;
|
|
475
|
+
/** Inline types accepted by default (no SVG). */
|
|
476
|
+
export const PICTURE_DATA_TYPES: readonly string[];
|
|
477
|
+
export const PICTURE_EXTENSIONS: Readonly<Record<string, string>>;
|
|
478
|
+
export const PICTURE_FILE_EXTENSIONS: readonly string[];
|
|
479
|
+
|
|
480
|
+
export type PictureRefusal =
|
|
481
|
+
| 'empty'
|
|
482
|
+
| 'too_long'
|
|
483
|
+
| 'unsafe_characters'
|
|
484
|
+
| 'relative'
|
|
485
|
+
| 'scheme'
|
|
486
|
+
| 'userinfo'
|
|
487
|
+
| 'host'
|
|
488
|
+
| 'insecure'
|
|
489
|
+
| 'data_malformed'
|
|
490
|
+
| 'data_type'
|
|
491
|
+
| 'data_too_large';
|
|
492
|
+
|
|
493
|
+
export class PictureSourceError extends Error {
|
|
494
|
+
readonly code: 'refused' | 'http' | 'not_a_picture';
|
|
495
|
+
readonly reason: string | null;
|
|
496
|
+
readonly status: number | null;
|
|
497
|
+
constructor(code: 'refused' | 'http' | 'not_a_picture', reason?: string, status?: number);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
export interface HttpAddress {
|
|
501
|
+
scheme: 'http' | 'https';
|
|
502
|
+
host: string;
|
|
503
|
+
/** null for the scheme's default port. */
|
|
504
|
+
port: number | null;
|
|
505
|
+
origin: string;
|
|
506
|
+
/** Path, query and fragment; '' when none. */
|
|
507
|
+
path: string;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** Strict: no credentials, no backslash, no control character, ASCII host. */
|
|
511
|
+
export function parseHttpAddress(address: string): HttpAddress | null;
|
|
512
|
+
export function originOf(address: string): string | null;
|
|
513
|
+
/** Scheme, host and port compared whole — never a prefix or substring test. */
|
|
514
|
+
export function isSameOrigin(a: string, b: string): boolean;
|
|
515
|
+
|
|
516
|
+
export type DataAddressRead =
|
|
517
|
+
| { ok: true; mimeType: string; base64: boolean; payloadStart: number; bytes: number }
|
|
518
|
+
| { ok: false; reason: 'data_malformed' | 'data_type' | 'data_too_large' };
|
|
519
|
+
export function readDataAddress(address: string, options?: { types?: readonly string[]; maxBytes?: number }): DataAddressRead;
|
|
520
|
+
export function dataPayloadBase64(address: string, read: { base64: boolean; payloadStart: number }): string;
|
|
521
|
+
export function decodeBase64(text: string): Uint8Array;
|
|
522
|
+
export function encodeBase64(bytes: Uint8Array | ArrayLike<number>): string;
|
|
523
|
+
/** From the first bytes, never the name: PNG, JPEG, GIF, WebP, HEIC, AVIF, BMP. */
|
|
524
|
+
export function sniffPictureType(head: Uint8Array | ArrayLike<number>): { mimeType: string; extension: string } | null;
|
|
525
|
+
/** '' when neither the title nor the fallback leaves anything. */
|
|
526
|
+
export function pictureFileName(title: string, options?: { fallback?: string; maxLength?: number }): string;
|
|
527
|
+
/** expo-sharing's `UTI` for a picture file, from its extension; null when unknown. */
|
|
528
|
+
export function pictureUti(uri: string): string | null;
|
|
529
|
+
|
|
530
|
+
export type PictureKind =
|
|
531
|
+
| { kind: 'app'; url: string }
|
|
532
|
+
| { kind: 'outside'; url: string }
|
|
533
|
+
| { kind: 'data'; url: string; mimeType: string; bytes: number }
|
|
534
|
+
| { kind: 'refused'; reason: PictureRefusal };
|
|
535
|
+
|
|
536
|
+
/** What an image component takes: the token only on the app's own origin. */
|
|
537
|
+
export interface PictureSource {
|
|
538
|
+
uri: string;
|
|
539
|
+
headers?: Record<string, string>;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
export type PictureQuery = Record<string, string | number | boolean | null | undefined>;
|
|
543
|
+
|
|
544
|
+
export interface PictureSources {
|
|
545
|
+
readonly appOrigin: string;
|
|
546
|
+
classify(address: string): PictureKind;
|
|
547
|
+
/** null for a refused address. */
|
|
548
|
+
resolve(address: string, options?: { query?: PictureQuery }): Promise<PictureSource | null>;
|
|
549
|
+
headersFor(url: string): Promise<Record<string, string>>;
|
|
550
|
+
/** null for a refused address; never contains the token. */
|
|
551
|
+
cacheKey(address: string, options?: { variant?: string; version?: string | number }): string | null;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
export function createPictureSources(options: {
|
|
555
|
+
appUrl: string;
|
|
556
|
+
getToken?: () => string | null | undefined | Promise<string | null | undefined>;
|
|
557
|
+
authorize?: (token: string) => Record<string, string>;
|
|
558
|
+
allowHttpOutside?: boolean;
|
|
559
|
+
dataTypes?: readonly string[];
|
|
560
|
+
maxDataBytes?: number;
|
|
561
|
+
}): PictureSources;
|
|
562
|
+
|
|
563
|
+
/** expo-file-system/legacy's shape, as the picture files use it. */
|
|
564
|
+
export interface PictureFileSystemLike extends FileSystemLike {
|
|
565
|
+
copyAsync(options: { from: string; to: string }): Promise<void>;
|
|
566
|
+
downloadAsync(uri: string, fileUri: string, options?: { headers?: Record<string, string> }): Promise<{ status: number }>;
|
|
567
|
+
readAsStringAsync(uri: string, options: { encoding: 'base64'; position?: number; length?: number }): Promise<string>;
|
|
568
|
+
writeAsStringAsync(uri: string, contents: string, options: { encoding: 'base64' }): Promise<void>;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
export interface PictureFiles {
|
|
572
|
+
readonly directory: string;
|
|
573
|
+
original(address: string, options?: { query?: PictureQuery; version?: string | number }): Promise<string>;
|
|
574
|
+
named(
|
|
575
|
+
address: string,
|
|
576
|
+
title: string,
|
|
577
|
+
options?: { fallback?: string; query?: PictureQuery; version?: string | number }
|
|
578
|
+
): Promise<string>;
|
|
579
|
+
tidy(): Promise<string[]>;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
export function createPictureFiles(options: {
|
|
583
|
+
sources: PictureSources;
|
|
584
|
+
fs: PictureFileSystemLike;
|
|
585
|
+
directory: string;
|
|
586
|
+
maxFiles?: number;
|
|
587
|
+
maxBytes?: number;
|
|
588
|
+
now?: () => number;
|
|
589
|
+
}): PictureFiles;
|
package/src/index.js
CHANGED
|
@@ -0,0 +1,696 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a picture comes from, and who may learn the person's token on the way.
|
|
3
|
+
*
|
|
4
|
+
* An app shows three kinds of pictures:
|
|
5
|
+
* - its OWN, served by its API behind the person's token ('/images/abc', or
|
|
6
|
+
* the same address written in full);
|
|
7
|
+
* - OUTSIDE pictures — a publication, a web page, a CDN — loaded as they are;
|
|
8
|
+
* - INLINE pictures (`data:image/...`), carried inside a document.
|
|
9
|
+
*
|
|
10
|
+
* The one rule that matters: the token goes to the app's own origin and to
|
|
11
|
+
* nothing else. The first version of this rule was a prefix test
|
|
12
|
+
* (`/^https:\/\//` means "outside"), and the app's own addresses were built by
|
|
13
|
+
* gluing a path after the API's base URL. Both break on an address the app did
|
|
14
|
+
* not write itself:
|
|
15
|
+
*
|
|
16
|
+
* base 'https://api.example.com' + '.evil.com/x' -> https://api.example.com.evil.com/x
|
|
17
|
+
* base 'https://api.example.com' + '@evil.com/x' -> https://api.example.com@evil.com/x
|
|
18
|
+
*
|
|
19
|
+
* — two addresses that reach evil.com WITH the token. Here an address is
|
|
20
|
+
* parsed, its origin compared whole (scheme, host, port), and anything that
|
|
21
|
+
* does not parse cleanly is refused instead of guessed.
|
|
22
|
+
*
|
|
23
|
+
* WHY NOT `new URL()`: React Native's URL polyfill does not implement
|
|
24
|
+
* `hostname` / `host` on every version (it throws "not implemented"), and the
|
|
25
|
+
* WHATWG parser is lenient in exactly the ways an attacker uses — it strips
|
|
26
|
+
* tabs and newlines anywhere, and reads a backslash as a slash. A strict,
|
|
27
|
+
* small parser that refuses those inputs is safer than a lenient one that
|
|
28
|
+
* repairs them.
|
|
29
|
+
*
|
|
30
|
+
* Pure: no network, no file system, no platform. `createPictureSources` takes
|
|
31
|
+
* the token getter as an injected function; `createPictureFiles` below takes
|
|
32
|
+
* the file system.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
const { contentKey, createMediaCache } = require('./mediaCache');
|
|
36
|
+
|
|
37
|
+
/** Longest http(s) address accepted. Browsers cap far higher; a picture address is short. */
|
|
38
|
+
const PICTURE_ADDRESS_MAX_LENGTH = 8192;
|
|
39
|
+
|
|
40
|
+
/** Largest inline picture accepted, in decoded bytes. */
|
|
41
|
+
const PICTURE_DATA_MAX_BYTES = 10 * 1024 * 1024;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The inline types accepted by default. SVG is not among them: it is a
|
|
45
|
+
* document, not a picture — it can carry scripts and external references — and
|
|
46
|
+
* React Native's Image does not draw it anyway. An app that wants it lists it.
|
|
47
|
+
*/
|
|
48
|
+
const PICTURE_DATA_TYPES = Object.freeze([
|
|
49
|
+
'image/png',
|
|
50
|
+
'image/jpeg',
|
|
51
|
+
'image/jpg',
|
|
52
|
+
'image/gif',
|
|
53
|
+
'image/webp',
|
|
54
|
+
'image/heic',
|
|
55
|
+
'image/heif',
|
|
56
|
+
'image/avif',
|
|
57
|
+
'image/bmp'
|
|
58
|
+
]);
|
|
59
|
+
|
|
60
|
+
/** Where a picture's extension comes from, by declared type. */
|
|
61
|
+
const PICTURE_EXTENSIONS = Object.freeze({
|
|
62
|
+
'image/png': 'png',
|
|
63
|
+
'image/jpeg': 'jpg',
|
|
64
|
+
'image/jpg': 'jpg',
|
|
65
|
+
'image/gif': 'gif',
|
|
66
|
+
'image/webp': 'webp',
|
|
67
|
+
'image/heic': 'heic',
|
|
68
|
+
'image/heif': 'heic',
|
|
69
|
+
'image/avif': 'avif',
|
|
70
|
+
'image/bmp': 'bmp'
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const DEFAULT_PORTS = { http: 80, https: 443 };
|
|
74
|
+
|
|
75
|
+
/* How far into a data: address its header (type, parameters) may go. A
|
|
76
|
+
picture's header is a few dozen characters; looking further would mean
|
|
77
|
+
scanning megabytes of payload for a comma. */
|
|
78
|
+
const DATA_HEADER_MAX = 256;
|
|
79
|
+
|
|
80
|
+
class PictureSourceError extends Error {
|
|
81
|
+
/**
|
|
82
|
+
* @param {'refused'|'http'|'not_a_picture'} code A code, never a sentence:
|
|
83
|
+
* the app words it in its own language.
|
|
84
|
+
* @param {string} [reason] For 'refused': why the address was refused.
|
|
85
|
+
* @param {number} [status] For 'http': the status received.
|
|
86
|
+
*/
|
|
87
|
+
constructor(code, reason, status) {
|
|
88
|
+
super(reason ? `${code}:${reason}` : code);
|
|
89
|
+
this.name = 'PictureSourceError';
|
|
90
|
+
this.code = code;
|
|
91
|
+
this.reason = reason || null;
|
|
92
|
+
this.status = status === undefined ? null : status;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/* Any control character, space or DEL, anywhere. The WHATWG parser silently
|
|
97
|
+
REMOVES tabs and newlines ('https://app.example.com\t.evil.com' is not what
|
|
98
|
+
it looks like): an address carrying one is refused, never repaired. */
|
|
99
|
+
function hasUnsafeCharacter(text) {
|
|
100
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
101
|
+
const code = text.charCodeAt(i);
|
|
102
|
+
if (code <= 0x20 || code === 0x7f) return true;
|
|
103
|
+
}
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The origin of an http(s) address, parsed strictly; null when the address is
|
|
109
|
+
* not one, or not one this parser can vouch for.
|
|
110
|
+
*
|
|
111
|
+
* Refused: another scheme, a backslash anywhere, a control character or a
|
|
112
|
+
* space, credentials in the authority (`user@host`), a percent-encoded or
|
|
113
|
+
* non-ASCII host, an empty host, a port that is not a number in range.
|
|
114
|
+
* Scheme and host are lower-cased; the scheme's default port is dropped.
|
|
115
|
+
*
|
|
116
|
+
* @param {string} address
|
|
117
|
+
* @returns {{scheme: 'http'|'https', host: string, port: number|null, origin: string, path: string} | null}
|
|
118
|
+
* `path` is everything after the authority (path, query, fragment), '' when none.
|
|
119
|
+
*/
|
|
120
|
+
function parseHttpAddress(address) {
|
|
121
|
+
if (typeof address !== 'string' || address.length === 0 || address.length > PICTURE_ADDRESS_MAX_LENGTH) return null;
|
|
122
|
+
if (hasUnsafeCharacter(address) || address.includes('\\')) return null;
|
|
123
|
+
const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):\/\//.exec(address);
|
|
124
|
+
if (!match) return null;
|
|
125
|
+
const scheme = match[1].toLowerCase();
|
|
126
|
+
if (scheme !== 'http' && scheme !== 'https') return null;
|
|
127
|
+
const afterScheme = address.slice(match[0].length);
|
|
128
|
+
const end = afterScheme.search(/[/?#]/);
|
|
129
|
+
const authority = end === -1 ? afterScheme : afterScheme.slice(0, end);
|
|
130
|
+
const path = end === -1 ? '' : afterScheme.slice(end);
|
|
131
|
+
/* 'app.example.com@evil.com' is a request to evil.com. Credentials in a
|
|
132
|
+
picture address have no honest use: refused outright. */
|
|
133
|
+
if (!authority || authority.includes('@')) return null;
|
|
134
|
+
|
|
135
|
+
let host;
|
|
136
|
+
let portText = null;
|
|
137
|
+
if (authority.startsWith('[')) {
|
|
138
|
+
const close = authority.indexOf(']');
|
|
139
|
+
if (close === -1) return null;
|
|
140
|
+
host = authority.slice(0, close + 1).toLowerCase();
|
|
141
|
+
if (!/^\[[0-9a-f:.]+\]$/.test(host)) return null;
|
|
142
|
+
const rest = authority.slice(close + 1);
|
|
143
|
+
if (rest) {
|
|
144
|
+
if (!rest.startsWith(':')) return null;
|
|
145
|
+
portText = rest.slice(1);
|
|
146
|
+
}
|
|
147
|
+
} else {
|
|
148
|
+
const colon = authority.indexOf(':');
|
|
149
|
+
host = (colon === -1 ? authority : authority.slice(0, colon)).toLowerCase();
|
|
150
|
+
if (colon !== -1) portText = authority.slice(colon + 1);
|
|
151
|
+
/* ASCII letters, digits, dots and hyphens only: no '%' (an encoded host
|
|
152
|
+
decodes to something else), no Unicode look-alikes. */
|
|
153
|
+
if (!/^[a-z0-9.-]+$/.test(host) || host.startsWith('.') || host.includes('..')) return null;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
let port = null;
|
|
157
|
+
if (portText !== null) {
|
|
158
|
+
if (!/^\d{1,5}$/.test(portText)) return null;
|
|
159
|
+
port = Number(portText);
|
|
160
|
+
if (port > 65535) return null;
|
|
161
|
+
if (port === DEFAULT_PORTS[scheme]) port = null;
|
|
162
|
+
}
|
|
163
|
+
const origin = `${scheme}://${host}${port === null ? '' : `:${port}`}`;
|
|
164
|
+
return { scheme, host, port, origin, path };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The origin of an address ('https://host[:port]'), or null. */
|
|
168
|
+
function originOf(address) {
|
|
169
|
+
const parsed = parseHttpAddress(address);
|
|
170
|
+
return parsed ? parsed.origin : null;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Whether two addresses share an origin: scheme, host and port, compared
|
|
175
|
+
* whole. Never a substring or prefix test. Two addresses that do not parse
|
|
176
|
+
* share nothing.
|
|
177
|
+
*/
|
|
178
|
+
function isSameOrigin(a, b) {
|
|
179
|
+
const first = originOf(a);
|
|
180
|
+
return first !== null && first === originOf(b);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* An inline picture, read without decoding it.
|
|
185
|
+
*
|
|
186
|
+
* Only the header is examined for its shape (the first 256 characters); the
|
|
187
|
+
* size is judged from the payload's LENGTH before anything scans it, so a
|
|
188
|
+
* 200 MB address is refused in constant time.
|
|
189
|
+
*
|
|
190
|
+
* @param {string} address
|
|
191
|
+
* @param {object} [options]
|
|
192
|
+
* @param {readonly string[]} [options.types] Accepted types, lowercase.
|
|
193
|
+
* @param {number} [options.maxBytes] Decoded size limit.
|
|
194
|
+
* @returns {{ok: true, mimeType: string, base64: boolean, payloadStart: number, bytes: number}
|
|
195
|
+
* | {ok: false, reason: 'data_malformed'|'data_type'|'data_too_large'}}
|
|
196
|
+
* `bytes` is the decoded size (exact for base64 without whitespace, an
|
|
197
|
+
* upper bound otherwise).
|
|
198
|
+
*/
|
|
199
|
+
function readDataAddress(address, options = {}) {
|
|
200
|
+
const types = Array.isArray(options.types) ? options.types : PICTURE_DATA_TYPES;
|
|
201
|
+
const maxBytes = Number.isFinite(options.maxBytes) ? options.maxBytes : PICTURE_DATA_MAX_BYTES;
|
|
202
|
+
if (typeof address !== 'string' || address.slice(0, 5).toLowerCase() !== 'data:') return { ok: false, reason: 'data_malformed' };
|
|
203
|
+
const comma = address.slice(0, DATA_HEADER_MAX).indexOf(',');
|
|
204
|
+
if (comma === -1) return { ok: false, reason: 'data_malformed' };
|
|
205
|
+
const header = address.slice(5, comma);
|
|
206
|
+
if (hasUnsafeCharacter(header)) return { ok: false, reason: 'data_malformed' };
|
|
207
|
+
const parts = header.split(';');
|
|
208
|
+
const mimeType = parts[0].trim().toLowerCase();
|
|
209
|
+
const base64 = parts.length > 1 && parts[parts.length - 1].trim().toLowerCase() === 'base64';
|
|
210
|
+
if (!/^[a-z]+\/[a-z0-9.+-]+$/.test(mimeType)) return { ok: false, reason: 'data_malformed' };
|
|
211
|
+
if (!types.includes(mimeType)) return { ok: false, reason: 'data_type' };
|
|
212
|
+
const payloadStart = comma + 1;
|
|
213
|
+
const length = address.length - payloadStart;
|
|
214
|
+
if (length === 0) return { ok: false, reason: 'data_malformed' };
|
|
215
|
+
let bytes;
|
|
216
|
+
if (base64) {
|
|
217
|
+
bytes = Math.floor((length * 3) / 4);
|
|
218
|
+
if (bytes > maxBytes) return { ok: false, reason: 'data_too_large' };
|
|
219
|
+
/* Linear scan, no backtracking: the character set, then the padding. */
|
|
220
|
+
let padding = 0;
|
|
221
|
+
for (let i = payloadStart; i < address.length; i += 1) {
|
|
222
|
+
const code = address.charCodeAt(i);
|
|
223
|
+
const isAlphabet =
|
|
224
|
+
(code >= 65 && code <= 90) || (code >= 97 && code <= 122) || (code >= 48 && code <= 57) || code === 43 || code === 47;
|
|
225
|
+
if (code === 61) padding += 1;
|
|
226
|
+
else if (!isAlphabet || padding > 0) return { ok: false, reason: 'data_malformed' };
|
|
227
|
+
}
|
|
228
|
+
if (padding > 2 || length % 4 !== 0) return { ok: false, reason: 'data_malformed' };
|
|
229
|
+
bytes -= padding;
|
|
230
|
+
} else {
|
|
231
|
+
bytes = length;
|
|
232
|
+
if (bytes > maxBytes) return { ok: false, reason: 'data_too_large' };
|
|
233
|
+
}
|
|
234
|
+
return { ok: true, mimeType, base64, payloadStart, bytes };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
238
|
+
const BASE64_INDEX = (() => {
|
|
239
|
+
const index = new Int16Array(128).fill(-1);
|
|
240
|
+
for (let i = 0; i < BASE64.length; i += 1) index[BASE64.charCodeAt(i)] = i;
|
|
241
|
+
return index;
|
|
242
|
+
})();
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Standard base64 to bytes, without `atob` (absent from older Hermes builds
|
|
246
|
+
* and from this package's lint globals). Characters outside the alphabet are
|
|
247
|
+
* skipped; padding ends the data.
|
|
248
|
+
* @param {string} text
|
|
249
|
+
* @returns {Uint8Array}
|
|
250
|
+
*/
|
|
251
|
+
function decodeBase64(text) {
|
|
252
|
+
const source = String(text || '');
|
|
253
|
+
const out = new Uint8Array(Math.floor((source.length * 3) / 4) + 3);
|
|
254
|
+
let buffer = 0;
|
|
255
|
+
let bits = 0;
|
|
256
|
+
let length = 0;
|
|
257
|
+
for (let i = 0; i < source.length; i += 1) {
|
|
258
|
+
const code = source.charCodeAt(i);
|
|
259
|
+
if (code === 61) break;
|
|
260
|
+
const value = code < 128 ? BASE64_INDEX[code] : -1;
|
|
261
|
+
if (value === -1) continue;
|
|
262
|
+
buffer = (buffer << 6) | value;
|
|
263
|
+
bits += 6;
|
|
264
|
+
if (bits >= 8) {
|
|
265
|
+
bits -= 8;
|
|
266
|
+
out[length] = (buffer >> bits) & 0xff;
|
|
267
|
+
length += 1;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return out.slice(0, length);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Bytes to standard base64, padded. */
|
|
274
|
+
function encodeBase64(bytes) {
|
|
275
|
+
const input = bytes instanceof Uint8Array ? bytes : Uint8Array.from(bytes || []);
|
|
276
|
+
let out = '';
|
|
277
|
+
for (let i = 0; i < input.length; i += 3) {
|
|
278
|
+
const a = input[i];
|
|
279
|
+
const b = i + 1 < input.length ? input[i + 1] : 0;
|
|
280
|
+
const c = i + 2 < input.length ? input[i + 2] : 0;
|
|
281
|
+
out += BASE64[a >> 2] + BASE64[((a & 3) << 4) | (b >> 4)];
|
|
282
|
+
out += i + 1 < input.length ? BASE64[((b & 15) << 2) | (c >> 6)] : '=';
|
|
283
|
+
out += i + 2 < input.length ? BASE64[c & 63] : '=';
|
|
284
|
+
}
|
|
285
|
+
return out;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* The bytes of an inline picture's payload, base64-encoded — what a file
|
|
290
|
+
* system writes with `{ encoding: 'base64' }`. A base64 payload is returned as
|
|
291
|
+
* it stands (no decode, no copy of megabytes through a byte array); a
|
|
292
|
+
* percent-encoded one is decoded to bytes, then encoded.
|
|
293
|
+
*
|
|
294
|
+
* @param {string} address Already accepted by readDataAddress.
|
|
295
|
+
* @param {{base64: boolean, payloadStart: number}} read Its result.
|
|
296
|
+
* @returns {string}
|
|
297
|
+
*/
|
|
298
|
+
function dataPayloadBase64(address, read) {
|
|
299
|
+
const payload = address.slice(read.payloadStart);
|
|
300
|
+
if (read.base64) return payload;
|
|
301
|
+
const bytes = [];
|
|
302
|
+
for (let i = 0; i < payload.length; i += 1) {
|
|
303
|
+
const code = payload.charCodeAt(i);
|
|
304
|
+
if (code === 37 && /^[0-9a-fA-F]{2}$/.test(payload.slice(i + 1, i + 3))) {
|
|
305
|
+
bytes.push(parseInt(payload.slice(i + 1, i + 3), 16));
|
|
306
|
+
i += 2;
|
|
307
|
+
} else {
|
|
308
|
+
bytes.push(code & 0xff);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return encodeBase64(bytes);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* What a picture file IS, from its first bytes — never from its name or a
|
|
316
|
+
* declared type. A server that answers an error page with a 200 must not have
|
|
317
|
+
* that HTML saved to Photos as a JPEG.
|
|
318
|
+
*
|
|
319
|
+
* @param {Uint8Array|number[]} head At least the first 12 bytes.
|
|
320
|
+
* @returns {{mimeType: string, extension: string} | null}
|
|
321
|
+
*/
|
|
322
|
+
function sniffPictureType(head) {
|
|
323
|
+
const b = head || [];
|
|
324
|
+
const at = (i) => (i < b.length ? b[i] : -1);
|
|
325
|
+
const ascii = (from, text) => [...text].every((char, i) => at(from + i) === char.charCodeAt(0));
|
|
326
|
+
if (at(0) === 0x89 && ascii(1, 'PNG') && at(4) === 0x0d && at(5) === 0x0a) return { mimeType: 'image/png', extension: 'png' };
|
|
327
|
+
if (at(0) === 0xff && at(1) === 0xd8 && at(2) === 0xff) return { mimeType: 'image/jpeg', extension: 'jpg' };
|
|
328
|
+
if (ascii(0, 'GIF87a') || ascii(0, 'GIF89a')) return { mimeType: 'image/gif', extension: 'gif' };
|
|
329
|
+
if (ascii(0, 'RIFF') && ascii(8, 'WEBP')) return { mimeType: 'image/webp', extension: 'webp' };
|
|
330
|
+
if (ascii(4, 'ftyp')) {
|
|
331
|
+
if (ascii(8, 'avif') || ascii(8, 'avis')) return { mimeType: 'image/avif', extension: 'avif' };
|
|
332
|
+
if (['heic', 'heix', 'hevc', 'hevx', 'mif1', 'msf1'].some((brand) => ascii(8, brand))) {
|
|
333
|
+
return { mimeType: 'image/heic', extension: 'heic' };
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (ascii(0, 'BM') && b.length >= 14) return { mimeType: 'image/bmp', extension: 'bmp' };
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/* The Uniform Type Identifier iOS's share sheet wants for each extension. */
|
|
341
|
+
const PICTURE_UTIS = Object.freeze({
|
|
342
|
+
png: 'public.png',
|
|
343
|
+
jpg: 'public.jpeg',
|
|
344
|
+
gif: 'com.compuserve.gif',
|
|
345
|
+
webp: 'org.webmproject.webp',
|
|
346
|
+
heic: 'public.heic',
|
|
347
|
+
avif: 'public.avif',
|
|
348
|
+
bmp: 'com.microsoft.bmp'
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* What to tell iOS's share sheet a picture file is (expo-sharing's `UTI`),
|
|
353
|
+
* from its name; null for anything else. The first version knew only PNG and
|
|
354
|
+
* called everything else a JPEG.
|
|
355
|
+
* @param {string} uri
|
|
356
|
+
*/
|
|
357
|
+
function pictureUti(uri) {
|
|
358
|
+
const match = /\.([a-z0-9]+)$/i.exec(String(uri || ''));
|
|
359
|
+
const extension = match ? match[1].toLowerCase() : '';
|
|
360
|
+
return Object.prototype.hasOwnProperty.call(PICTURE_UTIS, extension) ? PICTURE_UTIS[extension] : null;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* A file name for a picture handed to the person (Photos, the share sheet):
|
|
365
|
+
* its title, cleaned. Separators, reserved characters and control characters
|
|
366
|
+
* become spaces; a leading dot (a hidden file) is dropped; the length is
|
|
367
|
+
* counted in characters, never cutting an emoji or an accented letter in two.
|
|
368
|
+
*
|
|
369
|
+
* @param {string} title
|
|
370
|
+
* @param {object} [options]
|
|
371
|
+
* @param {string} [options.fallback] When nothing is left. The APP's word —
|
|
372
|
+
* there is no default name in a language.
|
|
373
|
+
* @param {number} [options.maxLength=60]
|
|
374
|
+
* @returns {string} Without extension; '' when neither title nor fallback
|
|
375
|
+
* leaves anything.
|
|
376
|
+
*/
|
|
377
|
+
function pictureFileName(title, options = {}) {
|
|
378
|
+
const maxLength = Number.isFinite(options.maxLength) && options.maxLength > 0 ? options.maxLength : 60;
|
|
379
|
+
const clean = (text) =>
|
|
380
|
+
Array.from(
|
|
381
|
+
String(text || '')
|
|
382
|
+
// eslint-disable-next-line no-control-regex
|
|
383
|
+
.replace(/[\\/:*?"<>|\u0000-\u001f\u007f]+/g, ' ')
|
|
384
|
+
.replace(/\s+/g, ' ')
|
|
385
|
+
.trim()
|
|
386
|
+
.replace(/^[.\s]+/, '')
|
|
387
|
+
)
|
|
388
|
+
.slice(0, maxLength)
|
|
389
|
+
.join('')
|
|
390
|
+
.trim();
|
|
391
|
+
return clean(title) || clean(options.fallback);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* The rule for one app: which addresses are its own, and what they carry.
|
|
396
|
+
*
|
|
397
|
+
* @param {object} options
|
|
398
|
+
* @param {string} options.appUrl The API's base URL, e.g.
|
|
399
|
+
* 'https://api.example.com' or 'https://api.example.com/api'. Its ORIGIN
|
|
400
|
+
* is the only one that ever receives the token; a relative address
|
|
401
|
+
* ('/images/abc') is joined to the whole base.
|
|
402
|
+
* @param {() => (string|null|Promise<string|null>)} [options.getToken]
|
|
403
|
+
* The person's token, read at each resolution (a token refreshed since the
|
|
404
|
+
* last picture is the one sent).
|
|
405
|
+
* @param {(token: string) => Record<string, string>} [options.authorize]
|
|
406
|
+
* The headers a token becomes. Default: `Authorization: Bearer <token>`.
|
|
407
|
+
* @param {boolean} [options.allowHttpOutside=false] Outside pictures over
|
|
408
|
+
* plain http. Refused by default: iOS blocks them anyway (App Transport
|
|
409
|
+
* Security), and a page loading one leaks what the person reads.
|
|
410
|
+
* @param {readonly string[]} [options.dataTypes] Inline types accepted.
|
|
411
|
+
* @param {number} [options.maxDataBytes]
|
|
412
|
+
*/
|
|
413
|
+
function createPictureSources(options = {}) {
|
|
414
|
+
const base = parseHttpAddress(options.appUrl);
|
|
415
|
+
if (!base) throw new Error('createPictureSources: options.appUrl must be an absolute http(s) URL without credentials.');
|
|
416
|
+
const appOrigin = base.origin;
|
|
417
|
+
/* The base's own path, without query or fragment or trailing slash:
|
|
418
|
+
'https://api.example.com/api/' -> '/api'. */
|
|
419
|
+
const basePath = base.path.split(/[?#]/)[0].replace(/\/+$/, '');
|
|
420
|
+
const getToken = typeof options.getToken === 'function' ? options.getToken : () => null;
|
|
421
|
+
const authorize =
|
|
422
|
+
typeof options.authorize === 'function' ? options.authorize : (token) => ({ Authorization: `Bearer ${token}` });
|
|
423
|
+
const allowHttpOutside = options.allowHttpOutside === true;
|
|
424
|
+
const dataOptions = { types: options.dataTypes, maxBytes: options.maxDataBytes };
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* What an address is, decided without touching the network.
|
|
428
|
+
*
|
|
429
|
+
* @param {string} address
|
|
430
|
+
* @returns {{kind: 'app', url: string}
|
|
431
|
+
* | {kind: 'outside', url: string}
|
|
432
|
+
* | {kind: 'data', url: string, mimeType: string, bytes: number}
|
|
433
|
+
* | {kind: 'refused', reason: string}}
|
|
434
|
+
*/
|
|
435
|
+
function classify(address) {
|
|
436
|
+
if (typeof address !== 'string' || address.trim() === '') return { kind: 'refused', reason: 'empty' };
|
|
437
|
+
if (address.slice(0, 5).toLowerCase() === 'data:') {
|
|
438
|
+
const read = readDataAddress(address, dataOptions);
|
|
439
|
+
return read.ok ? { kind: 'data', url: address, mimeType: read.mimeType, bytes: read.bytes } : { kind: 'refused', reason: read.reason };
|
|
440
|
+
}
|
|
441
|
+
if (address.length > PICTURE_ADDRESS_MAX_LENGTH) return { kind: 'refused', reason: 'too_long' };
|
|
442
|
+
if (hasUnsafeCharacter(address) || address.includes('\\')) return { kind: 'refused', reason: 'unsafe_characters' };
|
|
443
|
+
|
|
444
|
+
/* A path of the app: '/images/abc'. Not '//host/…' — that is an address
|
|
445
|
+
on ANOTHER host, whatever it looks like. */
|
|
446
|
+
if (address.startsWith('/')) {
|
|
447
|
+
if (address.startsWith('//')) return { kind: 'refused', reason: 'relative' };
|
|
448
|
+
const url = `${appOrigin}${basePath}${address}`;
|
|
449
|
+
/* Belt and braces: the joined address must parse back to the app's own
|
|
450
|
+
origin, or it is not the app's. */
|
|
451
|
+
return originOf(url) === appOrigin ? { kind: 'app', url } : { kind: 'refused', reason: 'relative' };
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const scheme = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(address);
|
|
455
|
+
if (!scheme) return { kind: 'refused', reason: 'relative' };
|
|
456
|
+
const name = scheme[1].toLowerCase();
|
|
457
|
+
if (name !== 'http' && name !== 'https') return { kind: 'refused', reason: 'scheme' };
|
|
458
|
+
if (!address.slice(scheme[0].length).startsWith('//')) return { kind: 'refused', reason: 'relative' };
|
|
459
|
+
const afterSlashes = address.slice(scheme[0].length + 2);
|
|
460
|
+
const authorityEnd = afterSlashes.search(/[/?#]/);
|
|
461
|
+
const authority = authorityEnd === -1 ? afterSlashes : afterSlashes.slice(0, authorityEnd);
|
|
462
|
+
if (authority.includes('@')) return { kind: 'refused', reason: 'userinfo' };
|
|
463
|
+
const parsed = parseHttpAddress(address);
|
|
464
|
+
if (!parsed) return { kind: 'refused', reason: 'host' };
|
|
465
|
+
/* The app's own origin, written in full: its token goes with it. */
|
|
466
|
+
if (parsed.origin === appOrigin) return { kind: 'app', url: `${parsed.origin}${parsed.path}` };
|
|
467
|
+
if (parsed.scheme === 'http' && !allowHttpOutside) return { kind: 'refused', reason: 'insecure' };
|
|
468
|
+
return { kind: 'outside', url: `${parsed.origin}${parsed.path}` };
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* The headers an address may carry: the token for the app's own origin,
|
|
473
|
+
* nothing for any other. Compared whole, at the last moment, on the final
|
|
474
|
+
* address — whatever built it.
|
|
475
|
+
* @param {string} url An absolute address.
|
|
476
|
+
* @returns {Promise<Record<string, string>>}
|
|
477
|
+
*/
|
|
478
|
+
async function headersFor(url) {
|
|
479
|
+
if (originOf(url) !== appOrigin) return {};
|
|
480
|
+
const token = await getToken();
|
|
481
|
+
return typeof token === 'string' && token ? { ...authorize(token) } : {};
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* A source for an image component (`{ uri, headers? }`), or null for a
|
|
486
|
+
* refused address.
|
|
487
|
+
*
|
|
488
|
+
* @param {string} address
|
|
489
|
+
* @param {object} [resolveOptions]
|
|
490
|
+
* @param {Record<string, string|number|boolean>} [resolveOptions.query]
|
|
491
|
+
* Added to the APP's addresses only ('?original=1'). An outside address
|
|
492
|
+
* is never rewritten: a signed CDN link would stop working.
|
|
493
|
+
*/
|
|
494
|
+
async function resolve(address, resolveOptions = {}) {
|
|
495
|
+
const found = classify(address);
|
|
496
|
+
if (found.kind === 'refused') return null;
|
|
497
|
+
if (found.kind !== 'app') return { uri: found.url };
|
|
498
|
+
const uri = withQuery(found.url, resolveOptions.query);
|
|
499
|
+
const headers = await headersFor(uri);
|
|
500
|
+
return Object.keys(headers).length ? { uri, headers } : { uri };
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* A stable file-safe name for a picture's cached copy: the address,
|
|
505
|
+
* normalised (a path and the same address written in full share it),
|
|
506
|
+
* NEVER the token. Null for a refused address.
|
|
507
|
+
*
|
|
508
|
+
* @param {string} address
|
|
509
|
+
* @param {object} [keyOptions]
|
|
510
|
+
* @param {string} [keyOptions.variant] 'original', 'preview'…: two
|
|
511
|
+
* renditions of one picture are two files.
|
|
512
|
+
* @param {string|number} [keyOptions.version] Bump it to retire every
|
|
513
|
+
* file kept under the previous rule.
|
|
514
|
+
*/
|
|
515
|
+
function cacheKey(address, keyOptions = {}) {
|
|
516
|
+
const found = classify(address);
|
|
517
|
+
if (found.kind === 'refused') return null;
|
|
518
|
+
const identity = found.url.split('#')[0];
|
|
519
|
+
return contentKey('picture', keyOptions.version, keyOptions.variant, found.kind === 'data' ? 'data' : 'http', identity);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
return { appOrigin, classify, resolve, headersFor, cacheKey };
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function withQuery(url, query) {
|
|
526
|
+
if (!query || typeof query !== 'object') return url;
|
|
527
|
+
const entries = Object.entries(query).filter(([, value]) => value !== undefined && value !== null);
|
|
528
|
+
if (entries.length === 0) return url;
|
|
529
|
+
const hash = url.indexOf('#');
|
|
530
|
+
const head = hash === -1 ? url : url.slice(0, hash);
|
|
531
|
+
const tail = hash === -1 ? '' : url.slice(hash);
|
|
532
|
+
const encoded = entries.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`).join('&');
|
|
533
|
+
return `${head}${head.includes('?') ? '&' : '?'}${encoded}${tail}`;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
const PICTURE_FILE_EXTENSIONS = Object.freeze(['png', 'jpg', 'gif', 'webp', 'heic', 'avif', 'bmp']);
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* Pictures as FILES on the phone — the original, to save to Photos or hand to
|
|
540
|
+
* the share sheet — downloaded once, kept in a bounded directory.
|
|
541
|
+
*
|
|
542
|
+
* What the first version got wrong, and this one does not:
|
|
543
|
+
* - it downloaded to a file named 'download' and, on the next call, served
|
|
544
|
+
* ANY file found in the folder: a download cut halfway was then served as
|
|
545
|
+
* the picture, forever. Here a download lands under a temporary name and is
|
|
546
|
+
* moved into place only once complete and recognised;
|
|
547
|
+
* - it named the file .png or .jpg from two bytes, and anything else — an
|
|
548
|
+
* HTML error page answered with a 200 — was saved as a JPEG. Here the bytes
|
|
549
|
+
* decide, and what is not a picture is refused;
|
|
550
|
+
* - outside pictures were keyed by a 32-bit hash: two addresses could share a
|
|
551
|
+
* file and show each other's picture. Here the key is 106 bits;
|
|
552
|
+
* - nothing ever cleaned the folder. Here it is bounded (createMediaCache).
|
|
553
|
+
*
|
|
554
|
+
* @param {object} options
|
|
555
|
+
* @param {ReturnType<typeof createPictureSources>} options.sources
|
|
556
|
+
* @param {object} options.fs expo-file-system/legacy's shape: getInfoAsync,
|
|
557
|
+
* makeDirectoryAsync, moveAsync, copyAsync, deleteAsync, readDirectoryAsync,
|
|
558
|
+
* downloadAsync, readAsStringAsync, writeAsStringAsync.
|
|
559
|
+
* @param {string} options.directory A directory of its own.
|
|
560
|
+
* @param {number} [options.maxFiles]
|
|
561
|
+
* @param {number} [options.maxBytes]
|
|
562
|
+
* @param {() => number} [options.now]
|
|
563
|
+
*/
|
|
564
|
+
function createPictureFiles(options = {}) {
|
|
565
|
+
const { sources, fs } = options;
|
|
566
|
+
if (!sources || typeof sources.classify !== 'function') throw new Error('createPictureFiles: options.sources is required.');
|
|
567
|
+
if (!fs) throw new Error('createPictureFiles: an fs adapter is required.');
|
|
568
|
+
const now = typeof options.now === 'function' ? options.now : () => Date.now();
|
|
569
|
+
const cache = createMediaCache({
|
|
570
|
+
fs,
|
|
571
|
+
directory: options.directory,
|
|
572
|
+
extensions: [...PICTURE_FILE_EXTENSIONS],
|
|
573
|
+
maxFiles: options.maxFiles,
|
|
574
|
+
maxBytes: options.maxBytes,
|
|
575
|
+
now
|
|
576
|
+
});
|
|
577
|
+
const directory = cache.directory;
|
|
578
|
+
const sharedDirectory = `${directory}shared/`;
|
|
579
|
+
let counter = 0;
|
|
580
|
+
const pending = new Map();
|
|
581
|
+
|
|
582
|
+
async function discard(uri) {
|
|
583
|
+
await fs.deleteAsync(uri, { idempotent: true }).catch(() => undefined);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
async function fetchInto(temporary, address, found, query) {
|
|
587
|
+
if (found.kind === 'data') {
|
|
588
|
+
const read = readDataAddress(address, { types: [found.mimeType] });
|
|
589
|
+
await fs.writeAsStringAsync(temporary, dataPayloadBase64(address, read), { encoding: 'base64' });
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
const source = await sources.resolve(address, { query });
|
|
593
|
+
if (!source) throw new PictureSourceError('refused', 'address');
|
|
594
|
+
const result = await fs.downloadAsync(source.uri, temporary, source.headers ? { headers: source.headers } : {});
|
|
595
|
+
const status = result && Number.isFinite(result.status) ? result.status : 200;
|
|
596
|
+
if (status < 200 || status >= 300) throw new PictureSourceError('http', undefined, status);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
async function download(address, key, found, query) {
|
|
600
|
+
await fs.makeDirectoryAsync(directory, { intermediates: true });
|
|
601
|
+
counter += 1;
|
|
602
|
+
const temporary = `${directory}${key}.${now()}-${counter}.tmp`;
|
|
603
|
+
let extension;
|
|
604
|
+
try {
|
|
605
|
+
await fetchInto(temporary, address, found, query);
|
|
606
|
+
const head = await fs.readAsStringAsync(temporary, { encoding: 'base64', position: 0, length: 16 });
|
|
607
|
+
const type = sniffPictureType(decodeBase64(head));
|
|
608
|
+
if (!type) throw new PictureSourceError('not_a_picture');
|
|
609
|
+
extension = type.extension;
|
|
610
|
+
} catch (error) {
|
|
611
|
+
await discard(temporary);
|
|
612
|
+
throw error;
|
|
613
|
+
}
|
|
614
|
+
const destination = `${directory}${key}.${extension}`;
|
|
615
|
+
try {
|
|
616
|
+
await fs.moveAsync({ from: temporary, to: destination });
|
|
617
|
+
} catch (error) {
|
|
618
|
+
await discard(temporary);
|
|
619
|
+
const info = await fs.getInfoAsync(destination);
|
|
620
|
+
if (!info || !info.exists) throw error;
|
|
621
|
+
}
|
|
622
|
+
void cache.tidy().catch(() => undefined);
|
|
623
|
+
return destination;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* The picture's original on the phone: the kept copy, or a fresh download.
|
|
628
|
+
* Two calls for the same picture at once share one download.
|
|
629
|
+
*
|
|
630
|
+
* @param {string} address
|
|
631
|
+
* @param {object} [originalOptions]
|
|
632
|
+
* @param {Record<string, string|number|boolean>} [originalOptions.query]
|
|
633
|
+
* For the app's own pictures, e.g. `{ original: 1 }`.
|
|
634
|
+
* @param {string|number} [originalOptions.version]
|
|
635
|
+
* @returns {Promise<string>} The file's URI.
|
|
636
|
+
*/
|
|
637
|
+
function original(address, originalOptions = {}) {
|
|
638
|
+
const found = sources.classify(address);
|
|
639
|
+
if (found.kind === 'refused') return Promise.reject(new PictureSourceError('refused', found.reason));
|
|
640
|
+
const key = sources.cacheKey(address, { variant: 'original', version: originalOptions.version });
|
|
641
|
+
if (pending.has(key)) return pending.get(key);
|
|
642
|
+
const job = (async () => {
|
|
643
|
+
const known = await cache.lookup(key);
|
|
644
|
+
return known || download(address, key, found, originalOptions.query);
|
|
645
|
+
})().finally(() => pending.delete(key));
|
|
646
|
+
pending.set(key, job);
|
|
647
|
+
return job;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* A copy named after the picture's title, for Photos and the share sheet —
|
|
652
|
+
* both read the type from the name. Only the latest named copy is kept: the
|
|
653
|
+
* previous ones are cleared first.
|
|
654
|
+
*
|
|
655
|
+
* @param {string} address
|
|
656
|
+
* @param {string} title
|
|
657
|
+
* @param {object} [namedOptions]
|
|
658
|
+
* @param {string} [namedOptions.fallback] The name when the title is empty.
|
|
659
|
+
* @param {Record<string, string|number|boolean>} [namedOptions.query]
|
|
660
|
+
* @param {string|number} [namedOptions.version]
|
|
661
|
+
*/
|
|
662
|
+
async function named(address, title, namedOptions = {}) {
|
|
663
|
+
const file = await original(address, namedOptions);
|
|
664
|
+
const extension = file.slice(file.lastIndexOf('.') + 1);
|
|
665
|
+
await fs.deleteAsync(sharedDirectory, { idempotent: true }).catch(() => undefined);
|
|
666
|
+
await fs.makeDirectoryAsync(sharedDirectory, { intermediates: true });
|
|
667
|
+
/* No title and no fallback: the file keeps its neutral key as a name. */
|
|
668
|
+
const name = pictureFileName(title, namedOptions) || file.slice(directory.length, file.lastIndexOf('.'));
|
|
669
|
+
const destination = `${sharedDirectory}${name}.${extension}`;
|
|
670
|
+
await fs.copyAsync({ from: file, to: destination });
|
|
671
|
+
return destination;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
return { directory, original, named, tidy: cache.tidy };
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
module.exports = {
|
|
678
|
+
PICTURE_ADDRESS_MAX_LENGTH,
|
|
679
|
+
PICTURE_DATA_MAX_BYTES,
|
|
680
|
+
PICTURE_DATA_TYPES,
|
|
681
|
+
PICTURE_EXTENSIONS,
|
|
682
|
+
PICTURE_FILE_EXTENSIONS,
|
|
683
|
+
PictureSourceError,
|
|
684
|
+
parseHttpAddress,
|
|
685
|
+
originOf,
|
|
686
|
+
isSameOrigin,
|
|
687
|
+
readDataAddress,
|
|
688
|
+
dataPayloadBase64,
|
|
689
|
+
decodeBase64,
|
|
690
|
+
encodeBase64,
|
|
691
|
+
sniffPictureType,
|
|
692
|
+
pictureFileName,
|
|
693
|
+
pictureUti,
|
|
694
|
+
createPictureSources,
|
|
695
|
+
createPictureFiles
|
|
696
|
+
};
|