local-first-auth-import-export 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Taddy Artist Database Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,244 @@
1
+ # Local First Auth — Import / Export
2
+
3
+ Let users **bring an identity they already have** into your mini app, or **back one up** — instead of creating a new profile.
4
+
5
+ This is the companion to [`local-first-auth`](https://github.com/antler-browser/local-first-auth). That package *creates* a profile (mints a fresh Ed25519 keypair + `did:key`). This one *moves* one:
6
+
7
+ - **Export** — download the user's profile (DID + public/private keypair, name, socials, avatar) as a portable `.json` file.
8
+ - **Import** — restore that file on another device or in another app. **The DID is preserved** — no new keypair is generated.
9
+
10
+ Both packages read and write the **same LocalStorage keys**, so they're fully interoperable: a profile created by `local-first-auth`'s `<Onboarding />` can be exported here, and a profile imported here works immediately with `local-first-auth`'s hooks, `window.localFirstAuth`, and JWT flow.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ npm install local-first-auth-import-export
16
+ ```
17
+
18
+ ## Quick Start
19
+
20
+ ### React
21
+
22
+ ```tsx
23
+ import { ImportExport } from 'local-first-auth-import-export/react'
24
+
25
+ function BackupPage() {
26
+ return (
27
+ <ImportExport
28
+ onComplete={(profile) => console.log('Imported:', profile.did)}
29
+ customStyles={{ primaryColor: '#403B51' }}
30
+ />
31
+ )
32
+ }
33
+ ```
34
+
35
+ Or use the two halves independently:
36
+
37
+ ```tsx
38
+ import { ImportProfile, ExportProfile } from 'local-first-auth-import-export/react'
39
+
40
+ <ExportProfile onExport={(p) => console.log('Backed up', p.did)} />
41
+ <ImportProfile onComplete={(p) => console.log('Restored', p.did)} />
42
+ ```
43
+
44
+ ### Vanilla JS
45
+
46
+ ```ts
47
+ import {
48
+ exportProfile,
49
+ downloadProfile,
50
+ importProfile,
51
+ importProfileFromFile,
52
+ } from 'local-first-auth-import-export'
53
+
54
+ // Export — triggers a .json download
55
+ downloadProfile()
56
+
57
+ // Import — from a file input
58
+ await importProfileFromFile(fileInput.files[0])
59
+
60
+ // Import — from a JSON string, or even a bare private key
61
+ const profile = await importProfile(jsonString)
62
+ console.log(profile.did) // same DID as before
63
+ ```
64
+
65
+ ## ⚠️ Security
66
+
67
+ **The exported file contains the user's private key in plain text.** Anyone who has it can act as that user — it *is* their identity.
68
+
69
+ - Never upload it to a server, log it, or send it over the network.
70
+ - Tell users to store it somewhere safe (a password manager, an encrypted drive).
71
+ - `<ExportProfile />` shows this warning and keeps the key hidden behind a "Reveal" click by default.
72
+
73
+ There is no password-encrypted export in v1.
74
+
75
+ ## The export file format
76
+
77
+ The file is **self-identifying and versioned**, so any consumer can cheaply confirm it's a valid Local First Auth export before trusting it.
78
+
79
+ ```json
80
+ {
81
+ "type": "local-first-auth:export",
82
+ "version": 1,
83
+ "did": "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK",
84
+ "publicKey": "3dxk...",
85
+ "privateKey": "hR8f...",
86
+ "name": "Alice Anderson",
87
+ "socials": [{ "platform": "INSTAGRAM", "handle": "alice" }],
88
+ "avatar": null,
89
+ "exportedAt": "2026-07-12T10:30:00.000Z"
90
+ }
91
+ ```
92
+
93
+ | Field | Type | Required | Description |
94
+ | --- | --- | --- | --- |
95
+ | `type` | string | Yes | Always `"local-first-auth:export"`. The magic string identifying the format. |
96
+ | `version` | number | Yes | Schema version. Currently `1`. |
97
+ | `did` | string | Yes | The user's DID (`did:key:z...`). |
98
+ | `publicKey` | string | Yes | base64, 32-byte Ed25519 public key. |
99
+ | `privateKey` | string | Yes | base64, 64-byte Ed25519 secret key. **Secret.** |
100
+ | `name` | string | No | Display name. |
101
+ | `socials` | array | No | `{ platform, handle }` entries. |
102
+ | `avatar` | string \| null | No | Avatar as a `data:` URI. |
103
+ | `exportedAt` | string | No | ISO 8601 export timestamp. |
104
+
105
+ ### Validation
106
+
107
+ A file is valid only if **all** of these hold — `validateExportedProfile()` checks them in order:
108
+
109
+ 1. It parses as a JSON object.
110
+ 2. `type` is exactly `"local-first-auth:export"`.
111
+ 3. `version` is a supported version (`1`).
112
+ 4. `privateKey` is base64 that decodes to exactly **64 bytes**.
113
+ 5. **Consistency:** `did` and `publicKey` are re-derivable from `privateKey`. A file whose DID doesn't match its key is corrupt or tampered with, and is rejected.
114
+ 6. `socials`, if present, is an array of `{ platform, handle }`.
115
+
116
+ ```ts
117
+ import { validateExportedProfile } from 'local-first-auth-import-export'
118
+
119
+ const result = validateExportedProfile(untrustedJson)
120
+ if (!result.valid) {
121
+ console.error(result.errors) // e.g. ["Unsupported export version: 99"]
122
+ }
123
+ ```
124
+
125
+ The private key is always the **source of truth**: on import, the DID and public key are re-derived from it rather than read from the file.
126
+
127
+ ## How import works
128
+
129
+ An Ed25519 secret key is 64 bytes: a 32-byte seed followed by the 32-byte public key. So the private key alone is enough to rebuild the whole identity:
130
+
131
+ ```
132
+ publicKey = secretKey[32..64]
133
+ did = "did:key:z" + base58btc(0xed 0x01 ‖ publicKey)
134
+ ```
135
+
136
+ That's why importing **never mints a new keypair** — it recovers the existing one. This is the same `did:key` derivation `local-first-auth` uses, so the DIDs match exactly.
137
+
138
+ Because of that, `importProfile()` also accepts a **bare base64 private key** with no envelope:
139
+
140
+ ```ts
141
+ await importProfile('hR8f...') // name defaults to 'anonymous'
142
+ ```
143
+
144
+ ## Overwrite protection
145
+
146
+ Importing over an existing, *different* identity would permanently destroy the user's current private key. So it throws unless you opt in:
147
+
148
+ ```ts
149
+ await importProfile(json) // throws if a different profile exists
150
+ await importProfile(json, { overwrite: true }) // explicitly replaces it
151
+ ```
152
+
153
+ Re-importing the **same** DID is always allowed (it's idempotent). `<ImportProfile />` surfaces this as a warning plus a confirmation checkbox.
154
+
155
+ ## API Reference
156
+
157
+ ### Core
158
+
159
+ ```ts
160
+ // Export
161
+ exportProfile(): ExportedProfile | null
162
+ exportProfileToJSON(pretty?: boolean): string | null
163
+ downloadProfile(filename?: string): ExportedProfile | null
164
+ defaultExportFilename(did: string): string
165
+
166
+ // Import
167
+ importProfile(input: string | ExportedProfile, opts?: { overwrite?: boolean }): Promise<Profile>
168
+ importProfileFromFile(file: File, opts?: { overwrite?: boolean }): Promise<Profile>
169
+ parseExportedProfile(input: string | ExportedProfile): ExportedProfile // throws
170
+ validateExportedProfile(input: unknown): ValidationResult // never throws
171
+
172
+ // Keys
173
+ deriveKeysFromPrivateKey(privateKey: string): ProfileKeys
174
+ validatePrivateKey(privateKey: unknown): { valid: boolean; error?: string }
175
+ createDidFromPublicKey(publicKey: Uint8Array): string
176
+ decodePublicKey(publicKey: string): Uint8Array
177
+
178
+ // JWT (Local First Auth spec)
179
+ createJWT(payload, privateKey): Promise<string>
180
+ decodeJWT(jwt): { header, payload, signature }
181
+ verifyJWT(jwt, publicKey: Uint8Array): boolean
182
+
183
+ // Storage (same keys as local-first-auth)
184
+ getCurrentProfile(), hasProfile(), clearProfile(), getPrivateKey(), STORAGE_KEYS
185
+
186
+ // Window API
187
+ injectLocalFirstAuthAPI(), removeLocalFirstAuthAPI(), hasLocalFirstAuthAPI()
188
+ ```
189
+
190
+ ### React
191
+
192
+ ```tsx
193
+ <ImportProfile customStyles? onComplete?(profile) onBack? />
194
+ <ExportProfile customStyles? onExport?(exported) emptyState? />
195
+ <ImportExport customStyles? onComplete? onExport? defaultTab? skipImport? skipExport? />
196
+
197
+ const { profile, refresh } = useProfile()
198
+ ```
199
+
200
+ All three components accept the same `customStyles` object as `local-first-auth`, so they theme identically:
201
+
202
+ ```tsx
203
+ <ImportExport customStyles={{
204
+ primaryColor: '#403B51',
205
+ backgroundColor: '#ffffff',
206
+ borderRadius: '12px',
207
+ fontFamily: 'Inter, sans-serif',
208
+ }} />
209
+ ```
210
+
211
+ ## Storage
212
+
213
+ Identical to `local-first-auth` — this is what makes them interoperable:
214
+
215
+ ```js
216
+ {
217
+ 'local-first-auth:profile': '{"did":"did:key:z6Mk...","name":"Alice",...}',
218
+ 'local-first-auth:privateKey': 'base64-encoded-64-byte-key'
219
+ }
220
+ ```
221
+
222
+ After a successful import, `window.localFirstAuth` is injected, so `getProfileDetails()` immediately returns JWTs signed by the imported key.
223
+
224
+ ## Development
225
+
226
+ ```bash
227
+ npm run build # dual CJS+ESM build with type declarations
228
+ npm run type-check # tsc --noEmit
229
+ npm test # build, then round-trip + component render tests
230
+ npm run dev:example # example app at http://localhost:5174
231
+ ```
232
+
233
+ ### Tests
234
+
235
+ - `test/roundtrip.mjs` — verifies against the built `dist`: DID derivation matches `local-first-auth`'s algorithm exactly, export → clear → import preserves the DID, JWTs signed by the imported key verify, the validator rejects tampered files, and the overwrite guard holds.
236
+ - `test/render.mjs` — smoke-renders the React components (including that the private key is hidden by default).
237
+
238
+ ### Example app
239
+
240
+ `/example` is a Vite + React harness with four demos: **Round Trip** (runs the core assertions in-browser), **Export**, **Import**, and **Combined UI** (themed `<ImportExport />`). Run `npm run build` first — the example resolves the package through its built `dist`.
241
+
242
+ ## License
243
+
244
+ MIT