@did-plc/lib 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/jest.config.js ADDED
@@ -0,0 +1,6 @@
1
+ const base = require('../../jest.config.base.js')
2
+
3
+ module.exports = {
4
+ ...base,
5
+ displayName: 'lib',
6
+ }
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@did-plc/lib",
3
+ "version": "0.0.1",
4
+ "main": "dist/index.js",
5
+ "license": "MIT",
6
+ "scripts": {
7
+ "test": "jest",
8
+ "prettier": "prettier --check src/",
9
+ "prettier:fix": "prettier --write src/",
10
+ "lint": "eslint . --ext .ts,.tsx",
11
+ "lint:fix": "yarn lint --fix",
12
+ "verify": "run-p prettier lint",
13
+ "verify:fix": "yarn prettier:fix && yarn lint:fix",
14
+ "build": "node ./build.js",
15
+ "postbuild": "tsc --build tsconfig.build.json",
16
+ "update-main-to-dist": "node ./update-pkg.js --update-main-to-dist",
17
+ "update-main-to-src": "node ./update-pkg.js --update-main-to-src",
18
+ "prepublish": "npm run update-main-to-dist",
19
+ "postpublish": "npm run update-main-to-src"
20
+ },
21
+ "dependencies": {
22
+ "@atproto/common": "0.1.0",
23
+ "@atproto/crypto": "0.1.0",
24
+ "@ipld/dag-cbor": "^7.0.3",
25
+ "axios": "^1.3.4",
26
+ "multiformats": "^9.6.4",
27
+ "uint8arrays": "3.0.0",
28
+ "zod": "^3.14.2"
29
+ },
30
+ "devDependencies": {
31
+ "eslint-plugin-prettier": "^4.2.1"
32
+ }
33
+ }
package/src/client.ts ADDED
@@ -0,0 +1,168 @@
1
+ import { check, cidForCbor } from '@atproto/common'
2
+ import { Keypair } from '@atproto/crypto'
3
+ import axios, { AxiosError } from 'axios'
4
+ import {
5
+ atprotoOp,
6
+ createUpdateOp,
7
+ didForCreateOp,
8
+ tombstoneOp,
9
+ updateAtprotoKeyOp,
10
+ updateHandleOp,
11
+ updatePdsOp,
12
+ updateRotationKeysOp,
13
+ } from './operations'
14
+ import * as t from './types'
15
+
16
+ export class Client {
17
+ constructor(public url: string) {}
18
+
19
+ private async makeGetReq(url: string) {
20
+ try {
21
+ const res = await axios.get(url)
22
+ return res.data
23
+ } catch (err) {
24
+ if (!axios.isAxiosError(err)) {
25
+ throw err
26
+ }
27
+ throw PlcClientError.fromAxiosError(err)
28
+ }
29
+ }
30
+
31
+ async getDocument(did: string): Promise<t.DidDocument> {
32
+ return await this.makeGetReq(`${this.url}/${encodeURIComponent(did)}`)
33
+ }
34
+
35
+ async getDocumentData(did: string): Promise<t.DocumentData> {
36
+ return await this.makeGetReq(`${this.url}/${encodeURIComponent(did)}/data`)
37
+ }
38
+
39
+ async getOperationLog(did: string): Promise<t.CompatibleOpOrTombstone[]> {
40
+ return await this.makeGetReq(`${this.url}/${encodeURIComponent(did)}/log`)
41
+ }
42
+
43
+ async getAuditableLog(did: string): Promise<t.ExportedOp[]> {
44
+ return await this.makeGetReq(
45
+ `${this.url}/${encodeURIComponent(did)}/log/audit`,
46
+ )
47
+ }
48
+
49
+ postOpUrl(did: string): string {
50
+ return `${this.url}/${encodeURIComponent(did)}`
51
+ }
52
+
53
+ async getLastOp(did: string): Promise<t.CompatibleOpOrTombstone> {
54
+ return await this.makeGetReq(
55
+ `${this.url}/${encodeURIComponent(did)}/log/last`,
56
+ )
57
+ }
58
+
59
+ async sendOperation(did: string, op: t.OpOrTombstone) {
60
+ try {
61
+ await axios.post(this.postOpUrl(did), op)
62
+ } catch (err) {
63
+ if (!axios.isAxiosError(err)) {
64
+ throw err
65
+ }
66
+ throw PlcClientError.fromAxiosError(err)
67
+ }
68
+ }
69
+
70
+ async export(after?: string, count?: number): Promise<t.ExportedOp[]> {
71
+ const url = new URL(`${this.url}/export`)
72
+ if (after) {
73
+ url.searchParams.append('after', after)
74
+ }
75
+ if (count !== undefined) {
76
+ url.searchParams.append('count', count.toString(10))
77
+ }
78
+ const res = await axios.get(url.toString())
79
+ const lines = res.data.split('\n')
80
+ return lines.map((l) => JSON.parse(l))
81
+ }
82
+
83
+ async createDid(opts: {
84
+ signingKey: string
85
+ handle: string
86
+ pds: string
87
+ rotationKeys: string[]
88
+ signer: Keypair
89
+ }): Promise<string> {
90
+ const op = await atprotoOp({ ...opts, prev: null })
91
+ const did = await didForCreateOp(op)
92
+ await this.sendOperation(did, op)
93
+ return did
94
+ }
95
+
96
+ private async ensureLastOp(did) {
97
+ const lastOp = await this.getLastOp(did)
98
+ if (check.is(lastOp, t.def.tombstone)) {
99
+ throw new Error('Cannot apply op to tombstone')
100
+ }
101
+ return lastOp
102
+ }
103
+
104
+ async updateData(
105
+ did: string,
106
+ signer: Keypair,
107
+ fn: (lastOp: t.UnsignedOperation) => Omit<t.UnsignedOperation, 'prev'>,
108
+ ) {
109
+ const lastOp = await this.ensureLastOp(did)
110
+ const op = await createUpdateOp(lastOp, signer, fn)
111
+ await this.sendOperation(did, op)
112
+ }
113
+
114
+ async updateAtprotoKey(did: string, signer: Keypair, atprotoKey: string) {
115
+ const lastOp = await this.ensureLastOp(did)
116
+ const op = await updateAtprotoKeyOp(lastOp, signer, atprotoKey)
117
+ await this.sendOperation(did, op)
118
+ }
119
+
120
+ async updateHandle(did: string, signer: Keypair, handle: string) {
121
+ const lastOp = await this.ensureLastOp(did)
122
+ const op = await updateHandleOp(lastOp, signer, handle)
123
+ await this.sendOperation(did, op)
124
+ }
125
+
126
+ async updatePds(did: string, signer: Keypair, endpoint: string) {
127
+ const lastOp = await this.ensureLastOp(did)
128
+ const op = await updatePdsOp(lastOp, signer, endpoint)
129
+ await this.sendOperation(did, op)
130
+ }
131
+
132
+ async updateRotationKeys(did: string, signer: Keypair, keys: string[]) {
133
+ const lastOp = await this.ensureLastOp(did)
134
+ const op = await updateRotationKeysOp(lastOp, signer, keys)
135
+ await this.sendOperation(did, op)
136
+ }
137
+
138
+ async tombstone(did: string, signer: Keypair) {
139
+ const lastOp = await this.ensureLastOp(did)
140
+ const prev = await cidForCbor(lastOp)
141
+ const op = await tombstoneOp(prev, signer)
142
+ await this.sendOperation(did, op)
143
+ }
144
+
145
+ async health() {
146
+ return await this.makeGetReq(`${this.url}/_health`)
147
+ }
148
+ }
149
+
150
+ export class PlcClientError extends Error {
151
+ constructor(
152
+ public status: number,
153
+ public data: unknown,
154
+ public message: string,
155
+ ) {
156
+ super(message)
157
+ }
158
+
159
+ static fromAxiosError(err: AxiosError) {
160
+ return new PlcClientError(
161
+ err.response?.status || 500,
162
+ err.response?.data,
163
+ err.message,
164
+ )
165
+ }
166
+ }
167
+
168
+ export default Client
package/src/data.ts ADDED
@@ -0,0 +1,132 @@
1
+ import { CID } from 'multiformats/cid'
2
+ import { check, cidForCbor, HOUR } from '@atproto/common'
3
+ import * as t from './types'
4
+ import {
5
+ assureValidCreationOp,
6
+ assureValidOp,
7
+ assureValidSig,
8
+ normalizeOp,
9
+ } from './operations'
10
+ import {
11
+ ImproperOperationError,
12
+ LateRecoveryError,
13
+ MisorderedOperationError,
14
+ } from './error'
15
+
16
+ export const assureValidNextOp = async (
17
+ did: string,
18
+ ops: t.IndexedOperation[],
19
+ proposed: t.OpOrTombstone,
20
+ ): Promise<{ nullified: CID[]; prev: CID | null }> => {
21
+ await assureValidOp(proposed)
22
+
23
+ // special case if account creation
24
+ if (ops.length === 0) {
25
+ await assureValidCreationOp(did, proposed)
26
+ return { nullified: [], prev: null }
27
+ }
28
+
29
+ const proposedPrev = proposed.prev ? CID.parse(proposed.prev) : undefined
30
+ if (!proposedPrev) {
31
+ throw new MisorderedOperationError()
32
+ }
33
+
34
+ const indexOfPrev = ops.findIndex((op) => proposedPrev.equals(op.cid))
35
+ if (indexOfPrev < 0) {
36
+ throw new MisorderedOperationError()
37
+ }
38
+
39
+ // if we are forking history, these are the ops still in the proposed canonical history
40
+ const opsInHistory = ops.slice(0, indexOfPrev + 1)
41
+ const nullified = ops.slice(indexOfPrev + 1)
42
+ const lastOp = opsInHistory.at(-1)
43
+ if (!lastOp) {
44
+ throw new MisorderedOperationError()
45
+ }
46
+ if (check.is(lastOp.operation, t.def.tombstone)) {
47
+ throw new MisorderedOperationError()
48
+ }
49
+ const lastOpNormalized = normalizeOp(lastOp.operation)
50
+ const firstNullified = nullified[0]
51
+
52
+ // if this does not involve nullification
53
+ if (!firstNullified) {
54
+ await assureValidSig(lastOpNormalized.rotationKeys, proposed)
55
+ return { nullified: [], prev: proposedPrev }
56
+ }
57
+
58
+ const disputedSigner = await assureValidSig(
59
+ lastOpNormalized.rotationKeys,
60
+ firstNullified.operation,
61
+ )
62
+
63
+ const indexOfSigner = lastOpNormalized.rotationKeys.indexOf(disputedSigner)
64
+ const morePowerfulKeys = lastOpNormalized.rotationKeys.slice(0, indexOfSigner)
65
+
66
+ await assureValidSig(morePowerfulKeys, proposed)
67
+
68
+ // recovery key gets a 72hr window to do historical re-wrties
69
+ if (nullified.length > 0) {
70
+ const RECOVERY_WINDOW = 72 * HOUR
71
+ const timeLapsed = Date.now() - firstNullified.createdAt.getTime()
72
+ if (timeLapsed > RECOVERY_WINDOW) {
73
+ throw new LateRecoveryError(timeLapsed)
74
+ }
75
+ }
76
+
77
+ return {
78
+ nullified: nullified.map((op) => op.cid),
79
+ prev: proposedPrev,
80
+ }
81
+ }
82
+
83
+ export const validateOperationLog = async (
84
+ did: string,
85
+ ops: t.CompatibleOpOrTombstone[],
86
+ ): Promise<t.DocumentData | null> => {
87
+ // make sure they're all validly formatted operations
88
+ const [first, ...rest] = ops
89
+ if (!check.is(first, t.def.compatibleOp)) {
90
+ throw new ImproperOperationError('incorrect structure', first)
91
+ }
92
+ for (const op of rest) {
93
+ if (!check.is(op, t.def.opOrTombstone)) {
94
+ throw new ImproperOperationError('incorrect structure', op)
95
+ }
96
+ }
97
+
98
+ // ensure the first op is a valid & signed create operation
99
+ let doc = await assureValidCreationOp(did, first)
100
+ let prev = await cidForCbor(first)
101
+
102
+ for (let i = 0; i < rest.length; i++) {
103
+ const op = rest[i]
104
+ if (!op.prev || !CID.parse(op.prev).equals(prev)) {
105
+ throw new MisorderedOperationError()
106
+ }
107
+ await assureValidSig(doc.rotationKeys, op)
108
+ if (check.is(op, t.def.tombstone)) {
109
+ if (i === rest.length - 1) {
110
+ return null
111
+ } else {
112
+ throw new MisorderedOperationError()
113
+ }
114
+ }
115
+ const { verificationMethods, rotationKeys, alsoKnownAs, services } = op
116
+ doc = { did, verificationMethods, rotationKeys, alsoKnownAs, services }
117
+ prev = await cidForCbor(op)
118
+ }
119
+
120
+ return doc
121
+ }
122
+
123
+ export const getLastOpWithCid = async (
124
+ ops: t.CompatibleOpOrTombstone[],
125
+ ): Promise<{ op: t.CompatibleOpOrTombstone; cid: CID }> => {
126
+ const op = ops.at(-1)
127
+ if (!op) {
128
+ throw new Error('log is empty')
129
+ }
130
+ const cid = await cidForCbor(op)
131
+ return { op, cid }
132
+ }
@@ -0,0 +1,84 @@
1
+ import * as uint8arrays from 'uint8arrays'
2
+ import * as crypto from '@atproto/crypto'
3
+ import * as t from './types'
4
+ import { UnsupportedKeyError } from './error'
5
+ import { ParsedDidKey } from '@atproto/crypto'
6
+
7
+ export const formatDidDoc = (data: t.DocumentData): t.DidDocument => {
8
+ const context = ['https://www.w3.org/ns/did/v1']
9
+
10
+ const verificationMethods: VerificationMethod[] = []
11
+ for (const [keyid, key] of Object.entries(data.verificationMethods)) {
12
+ const info = formatKeyAndContext(key)
13
+ if (!context.includes(info.context)) {
14
+ context.push(info.context)
15
+ }
16
+ verificationMethods.push({
17
+ id: `#${keyid}`,
18
+ type: info.type,
19
+ controller: data.did,
20
+ publicKeyMultibase: info.publicKeyMultibase,
21
+ })
22
+ }
23
+
24
+ const services: Service[] = []
25
+ for (const [serviceId, service] of Object.entries(data.services)) {
26
+ services.push({
27
+ id: `#${serviceId}`,
28
+ type: service.type,
29
+ serviceEndpoint: service.endpoint,
30
+ })
31
+ }
32
+
33
+ return {
34
+ '@context': context,
35
+ id: data.did,
36
+ alsoKnownAs: data.alsoKnownAs,
37
+ verificationMethod: verificationMethods,
38
+ service: services,
39
+ }
40
+ }
41
+
42
+ type VerificationMethod = {
43
+ id: string
44
+ type: string
45
+ controller: string
46
+ publicKeyMultibase: string
47
+ }
48
+
49
+ type Service = {
50
+ id: string
51
+ type: string
52
+ serviceEndpoint: string
53
+ }
54
+
55
+ type KeyAndContext = {
56
+ context: string
57
+ type: string
58
+ publicKeyMultibase
59
+ }
60
+
61
+ const formatKeyAndContext = (key: string): KeyAndContext => {
62
+ let keyInfo: ParsedDidKey
63
+ try {
64
+ keyInfo = crypto.parseDidKey(key)
65
+ } catch (err) {
66
+ throw new UnsupportedKeyError(key, err)
67
+ }
68
+ const { jwtAlg, keyBytes } = keyInfo
69
+
70
+ if (jwtAlg === crypto.P256_JWT_ALG) {
71
+ return {
72
+ context: 'https://w3id.org/security/suites/ecdsa-2019/v1',
73
+ type: 'EcdsaSecp256r1VerificationKey2019',
74
+ publicKeyMultibase: `z${uint8arrays.toString(keyBytes, 'base58btc')}`,
75
+ }
76
+ } else if (jwtAlg === crypto.SECP256K1_JWT_ALG) {
77
+ return {
78
+ context: 'https://w3id.org/security/suites/secp256k1-2019/v1',
79
+ type: 'EcdsaSecp256k1VerificationKey2019',
80
+ publicKeyMultibase: `z${uint8arrays.toString(keyBytes, 'base58btc')}`,
81
+ }
82
+ }
83
+ throw new UnsupportedKeyError(key, `Unsupported key type: ${jwtAlg}`)
84
+ }
package/src/error.ts ADDED
@@ -0,0 +1,58 @@
1
+ export class PlcError extends Error {
2
+ plcError = true
3
+ constructor(msg: string) {
4
+ super(msg)
5
+ }
6
+
7
+ static is(obj: unknown): obj is PlcError {
8
+ if (obj && typeof obj === 'object' && obj['plcError'] === true) {
9
+ return true
10
+ }
11
+ return false
12
+ }
13
+ }
14
+ export class ImproperOperationError extends PlcError {
15
+ constructor(public reason: string, public op: unknown) {
16
+ super(`Improperly formatted operation, ${reason}: ${op}`)
17
+ }
18
+ }
19
+
20
+ export class MisorderedOperationError extends PlcError {
21
+ constructor() {
22
+ super('Operations not correctly ordered')
23
+ }
24
+ }
25
+
26
+ export class LateRecoveryError extends PlcError {
27
+ constructor(public timeLapsed: number) {
28
+ super(
29
+ `Recovery operation occured outside of the allowed 72 hr recovery window. Time lapsed: ${timeLapsed}`,
30
+ )
31
+ }
32
+ }
33
+
34
+ export class GenesisHashError extends PlcError {
35
+ constructor(public expected: string) {
36
+ super(
37
+ `Hash of genesis operation does not match DID identifier: ${expected}`,
38
+ )
39
+ }
40
+ }
41
+
42
+ export class InvalidSignatureError extends PlcError {
43
+ constructor(public op: unknown) {
44
+ super(`Invalid signature on op: ${JSON.stringify(op)}`)
45
+ }
46
+ }
47
+
48
+ export class UnsupportedKeyError extends PlcError {
49
+ constructor(public key: string, public err: unknown) {
50
+ super(`Unsupported key type ${key}: ${err}`)
51
+ }
52
+ }
53
+
54
+ export class ImproperlyFormattedDidError extends PlcError {
55
+ constructor(public reason: string) {
56
+ super(`Improperly formatted did: ${reason}`)
57
+ }
58
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from './client'
2
+ export * from './data'
3
+ export * from './document'
4
+ export * from './error'
5
+ export * from './operations'
6
+ export * from './types'